-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.ts
63 lines (51 loc) · 1.49 KB
/
storage.ts
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
type ConstructParams = { storage: Storage; namespace?: string }
class Store {
storage: Storage
namespace: string
constructor({ storage, namespace }: ConstructParams) {
this.storage = storage
this.namespace = namespace || ''
}
_namespaceKey = (key: string): string => {
return key + this.namespace
}
_expiredKey = (key: string): string => {
return key + this.namespace + '__expiration'
}
get = (key: string): unknown => {
if (this._hasExpired(key)) {
return null
}
let val = this.storage.getItem(this._namespaceKey(key))
if (val === null) {
return val
}
try {
val = JSON.parse(val)
} catch (e) {
// val is string instead of a JSON serialized string
}
return val
}
set = (key: string, val: Parameters<typeof JSON.stringify>[0], expiration?: number): void => {
this.storage.setItem(this._namespaceKey(key), JSON.stringify(val))
expiration && this.storage.setItem(this._expiredKey(key), JSON.stringify(expiration))
}
remove = (key: string): void => {
this.storage.removeItem(this._namespaceKey(key))
this.storage.removeItem(this._expiredKey(key))
}
clearAll = (): void => {
this.storage.clear()
}
_hasExpired = (key: string): boolean => {
const expiredKey = this._expiredKey(key)
const val = this.storage.getItem(expiredKey)
const expired = val ? Date.now() > JSON.parse(val) : false
if (expired) {
this.remove(key)
}
return expired
}
}
export default Store