Skip to content

Commit e26c0dc

Browse files
committed
feat: add ExpireStorage class
1 parent 10d0f14 commit e26c0dc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

js/expire_storage.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-29 11:19:24
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-29 13:18:34
6+
*/
7+
8+
/**
9+
* Expire storage,支持过期时间的 localStorage
10+
*/
11+
12+
class ExpireStorage {
13+
prefix = "Chacha";
14+
15+
tag = "|Chacha|";
16+
17+
defaultTime = Date.now() + 24 * 60 * 60 * 31 * 1000; // 默认时长1个月
18+
19+
constructor(prefix, tag) {
20+
this.prefix = prefix;
21+
this.tag = tag;
22+
}
23+
24+
setItem(key, value, time) {
25+
key = `${this.prefix}${key}`;
26+
time = time ? new Date(time).getTime() : this.defaultTime;
27+
28+
// 构造一个形如 1646094676134|Chacha|"Hello World" 结构的字符串
29+
window.localStorage.setItem(
30+
key,
31+
`${time}${this.tag}${JSON.stringify(value)}`
32+
);
33+
}
34+
35+
getItem(key) {
36+
key = `${this.prefix}${key}`;
37+
let value = window.localStorage.getItem(key);
38+
39+
if (value) {
40+
let index = value.indexOf(this.tag);
41+
let time = +value.slice(0, index);
42+
43+
// 判断时间是否已过期
44+
if (time > Date.now()) {
45+
value = JSON.parse(value.slice(index + this.tag.length));
46+
} else {
47+
value = null;
48+
window.localStorage.removeItem(key);
49+
}
50+
}
51+
52+
return value;
53+
}
54+
}

0 commit comments

Comments
 (0)