storage实例

封装的本地缓存处理工具

利用web Storage技术实现前端缓存数据。G__Cache_Duration支持自定义缓存有效时间。适用于多租户,多用户切换的使用场景。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* localStorage 本地缓存处理工具
* @author https://github.com 2019/06/24.
* @version 1.0
*
* getStorage(key) - 获取localStorage数据
* @param {string} [key] - 返回对象或字符串
*
* setStorage(key,value) - 设置localStorage数据,
* @param {string} [key] - 设置的localStorage的名称
* @param {object/string} [value] - 设置的localStorage的名称对应的值
*
* clearStorage() - 清空localStorage数据
*
* removeStorage(key) - 删除localStorage数据
* @param {string} [key]
*
*/

export const setCache = (key, data, G__Cache_Duration) => {
try{
const _obj = {
data: data, // 需要缓存的数据
tenant;: 'moumou', // 当前租户
user: 'zhangsan', // 当前用户
datetime: (new Date()).getTime(),
duration: G__Cache_Duration // 有效时间
}
setStorage(key, _obj);
}catch(e){
console.log("ERR100:setCache出错了\n" + e);
}
}

export const getCache = (key) => {
try{
const curT = (new Date()).getTime();
var old = null;//旧数据
try{
old = getStorage(key);
}catch(e){
console.log("ERR104:缓存数据转json出错了,\n仅支持json数据缓存\n" + e);
return null;
}
if(old == null) return;
const otenant = old.tenant;
const ouser = old.user;
if(otenant === 'moumou' && ouser === 'zhangsan'){
const oldT = old.datetime;
const dur = old.duration;
if(curT - parseInt(oldT) <= parseInt(dur)){
return old.data;
}else{
removeStorage(key);
return null;
}
}else{
//缓存数据不是当前租户当前用户的缓存
return null;
}
}catch(e){
console.log("ERR103:getCache出错了\n" + e);
}
}

export const getStorage = (key) => {
var v = localStorage.getItem(key);
if(!v) {
return null
}
const v4 = v.slice(0, 4);
if(v4 == 'obj-') {
v = JSON.parse(v.slice(4));
} else if(v4 == 'str-') {
v = v.slice(4);
}
return v
}

export const setStorage = (key, value) => {
var v = value;
if(typeof v == "object") {
v = "obj-" + JSON.stringify(v)
} else {
if(value == null || value == undefined) {
v = "str-"
} else {
v = "str-" + v
}
}
localStorage.setItem(key, v);
//console.log(localStorage.getItem(key));
}

export const clearStorage = () => {
localStorage.clear();
}

export const removeStorage = () => {
localStorage.remove(key);
}

组件引入方式

import { setCache, getCache, clearStorage } from ‘../storage’;