-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathstorage.ts
110 lines (97 loc) · 2.71 KB
/
storage.ts
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
103
104
105
106
107
108
109
110
/**
* @model Stroage
* @Date 2020-04-11 21:55:46
* @LastEditTime 2024-08-25 10:20:04
*/
import { PlainObject } from 'utils';
const DEFAULT_EXPIRATION = 1000 * 60 * 60 * 24 * 7; // 7 days
/**
* @function deserialize
* @description 尝试将字符串转换为JSON对象,反序列化
* @param {unknown} value 需要反序列化的值
* @return {JSON | undefined}
*/
function deserialize(value: unknown) {
if (typeof value !== 'string') {
return undefined;
}
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
const STORAGE_CONST_ROLER = {
local: localStorage,
session: sessionStorage,
};
/**
* Storage
* @param {string} type storage type, default: 'local'
* @example:
* Storage('local').set(a, [1, 2, 3]);
* Storage('session').get('a');
*/
function Storage(type = 'local') {
const _controller = STORAGE_CONST_ROLER[type as keyof typeof STORAGE_CONST_ROLER];
return {
/**
* Storage.setLocal 设置Storage
* @param {String} key Storage key
* @param {String|Object} value Storage value
*/
set(
key: string,
value:
| string
| {
[key: string]: unknown;
},
expiration: number = DEFAULT_EXPIRATION
) {
const item = {
value: typeof value === 'object' ? JSON.stringify(value) : value,
expiration: expiration === 0 ? 0 : Date.now() + expiration * 1000,
};
_controller.setItem(key, JSON.stringify(item));
},
/**
* Storage.getLocal 获取Storage
* @param {String|undefined} key Storage key
*/
get(key?: string) {
if (key) {
const itemStr = _controller.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
if (item.expiration !== 0 && Date.now() > item.expiration) {
_controller.removeItem(key);
return null;
}
return deserialize(item.value);
} else {
const _obj: PlainObject = {};
for (const i in _controller) {
if (i && typeof _controller[i] === 'string') {
const item = JSON.parse(_controller[i]);
if (item.expiration !== 0 && Date.now() > item.expiration) {
_controller.removeItem(i);
continue;
}
_obj[i] = deserialize(item.value);
}
}
return _obj;
}
},
/**
* Storage.removeLocal 删除Storage
* @param {String|undefined} key Storage key
*/
remove(key: string) {
if (key) _controller.removeItem(key);
else _controller.clear();
},
};
}
export default Storage;