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
|
/**
* localStorage utils
*/
const lastUpdatedSuffix = '__lastUpdated';
export default {
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
}
catch (err) {
return false;
}
},
get(key) {
const value = localStorage.getItem(key);
try {
return JSON.parse(value);
}
catch (err) {
return value;
}
},
remove(key) {
try {
localStorage.removeItem(key);
return true;
}
catch (err) {
return false;
}
},
// Watch changes to a specified key - returns value on change
watch(key, callback) {
window.addEventListener('storage', event => {
if (event.key === key) callback(this.get(key));
});
},
// set() with an additional key containing the current time + expiration time
setWithExpireTime(key, value, maxAge) {
const lastUpdatedKey = key + lastUpdatedSuffix;
const lastUpdatedTime = Date.now() + maxAge;
this.set(key, value) && this.set(lastUpdatedKey, lastUpdatedTime);
},
// Whether the value of a key set with setWithExpireTime() has expired
hasExpired(key) {
const lastUpdatedKey = key + lastUpdatedSuffix;
const lastUpdatedTime = this.get(lastUpdatedKey);
if (Date.now() > lastUpdatedTime) {
return true;
}
return false;
},
};
|