storage.js
1.24 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
/*
* @Author: limin
* @Date: 2018-06-23 11:13:44
* @Last Modified by: limin
* @Last Modified time: 2018-08-31 18:28:26
*/
const TYPE = {
LOCAL: "localStorage",
SESSION: "sessionStorage",
};
function isObject(val) {
return val !== null && typeof val === "object";
}
function set(key, val, type = TYPE.LOCAL) {
if (isObject(val)) window[type].setItem(key, JSON.stringify(val));
else window[type].setItem(key, val);
}
function get(key, type = TYPE.LOCAL) {
var val = window[type].getItem(key);
try {
if (val && val.startsWith("#")) {
return val;
}
const value = JSON.parse(val);
return value;
} catch (e) {
throw e;
}
}
function remove(key, type = TYPE.LOCAL) {
window[type].removeItem(key);
}
function setSession(key, val, ex = 20) {
set(key, val, TYPE.SESSION);
}
function getSession(key) {
return get(key, TYPE.SESSION);
}
function removeSession(key) {
remove(key, TYPE.SESSION);
}
// 默认30minute
function setExpire(key, val, ex = 1.8e6) {
set(key, { v: val, t: Date.now() + ex });
}
function getExpire(key) {
var obj = get(key);
if (obj.t > Date.now()) return obj.v;
else return null;
}
export default {
set,
get,
remove,
setSession,
getSession,
removeSession,
setExpire,
getExpire,
};