storage.js
1.3 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
/**
* Set storage
*
* @param name
* @param content
* @param maxAge
*/
export const setStore = (name, content, maxAge = null) => {
if (!global.window || !name) {
return;
}
if (typeof content !== 'string') {
content = JSON.stringify(content)
}
let storage = global.window.localStorage
storage.setItem(name, content)
if (maxAge && !isNaN(parseInt(maxAge))) {
let timeout = parseInt(new Date().getTime() / 1000)
storage.setItem(`${name}_expire`, timeout + maxAge)
}
};
/**
* Get storage
*
* @param name
* @returns {*}
*/
export const getStore = name => {
if (!global.window || !name) {
return;
}
let content = window.localStorage.getItem(name)
let _expire = window.localStorage.getItem(`${name}_expire`)
if (_expire) {
let now = parseInt(new Date().getTime() / 1000)
if (now > _expire) {
return;
}
}
try {
return JSON.parse(content)
} catch (e) {
return content
}
};
/**
* Clear storage
*
* @param name
*/
export const clearStore = name => {
if (!global.window || !name) {
return;
}
window.localStorage.removeItem(name)
window.localStorage.removeItem(`${name}_expire`)
};
/**
* Clear all storage
*/
export const clearAll = () => {
if (!global.window || !name) {
return;
}
window.localStorage.clear()
}