Store
coderljw 2024-10-13 小于 1 分钟
# 1. Store
- 新增有效期设置,localforage (opens new window)
import localforage from 'localforage'
interface StoreData {
value?: any
expiryTime?: number
createTime: number
}
const getItem = async (key: string) => {
const data = await localforage.getItem<StoreData>(key)
if (!data) return null
if (data.expiryTime && Date.now() - data?.createTime > data.expiryTime) {
localforage.removeItem(key)
return null
}
return data.value
}
const setItem = async (key: string, value?: any, expiryTime?: number) => {
await localforage.setItem<StoreData>(key, {
value,
expiryTime,
createTime: Date.now(),
})
return value
}
type LocalForage = typeof localforage & {
setItem: typeof setItem
}
const store = {
...localforage,
getItem,
setItem,
} as LocalForage
export default store
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
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