StorageUtils.ts
2.09 KB
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
/**
* 微信存储功能工具
*/
import WxStorage from "../platform/wx/WxStorage";
import Storage from "../platform/Storage";
export default class StorageUtils {
private store: any = null
constructor() {
if (typeof localStorage === 'object')
this.store = new Storage;
if (typeof (wx) != "undefined")
this.store = new WxStorage;
}
private __isExpired(entity: any) {
if (!entity) return true;
let isExpired = this.timestamp - (entity.timestamp + entity.expiration) >= 0;
return isExpired;
}
get timestamp() {
return +(new Date().getTime() / 1000).toFixed(0);
}
set(key: string, value: Object, expiration = 0) {
const entity = {
timestamp: this.timestamp,
expiration,
key,
value
};
this.store.setItem(key, JSON.stringify(entity));
return this;
}
get(key: string) {
let entity: any;
try {
entity = this.store.getItem(key);
if (entity) {
entity = JSON.parse(entity);
} else {
return null;
}
} catch (err) {
console.warn(err);
return null;
}
// 没有设置过期时间, 则直接返回值
if (!entity.expiration)
return entity.value;
// 已过期
if (this.__isExpired(entity)) {
this.remove(key);
return null;
} else {
return entity.value;
}
}
remove(key: string) {
try {
this.store.removeItem(key);
} catch (err) {
console.warn(err);
}
return this;
}
clear() {
try {
this.store.clear();
} catch (err) {
console.warn(err);
}
return this;
}
isExist(key: string): boolean {
return this.store.hasKey(key);
}
private static instance: StorageUtils;
static get I(): StorageUtils {
return this.instance || (this.instance = new StorageUtils);
}
}