-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorage.ts
74 lines (60 loc) · 1.75 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
64
65
66
67
68
69
70
71
72
73
74
import isType from 'sewing/dist/isType'
import get from 'sewing/dist/get'
export interface StorageTarget {
[propName: string]: any
[propName: number]: any
}
const { MAX_SAFE_INTEGER = 9007199254740991 } = Number
export default class Storage {
private prefix: string
static parse (value: any) {
try {
return isType(value, 'String') && (Math.abs(value) > MAX_SAFE_INTEGER)
? value
: JSON.parse(value)
} catch (e) {
return value
}
}
static update <T extends StorageTarget> (obj: T, path: string[], value: any): T {
const temp = obj
while (path.length > 1) {
obj = obj[path.shift()!]
}
obj[path.shift()!] = value
return temp
}
constructor (name = '', prefix = 'app') {
this.prefix = `${prefix}_${name ? name + '_' : ''}`
}
split (path: string) {
const [target, ...route] = path.split(/\./)
return { target: this.prefix + target, route }
}
get (path: string, defaultValue: any) {
const { target, route } = this.split(path)
const item = Storage.parse(localStorage.getItem(target))
return get(item, route.join('.'), defaultValue)
}
set (path: string, value: any) {
const { target, route } = this.split(path)
const preItemValue = Storage.parse(localStorage.getItem(target))
const item = route.length > 1
? Storage.update(preItemValue, route, value)
: value
localStorage.setItem(target,
isType(item, ['Object', 'Array'])
? JSON.stringify(item)
: item
)
}
remove (item: string) {
const { target } = this.split(item)
localStorage.removeItem(target)
}
clear () {
Object.keys(localStorage).forEach(storage => {
if (storage.startsWith(this.prefix)) localStorage.removeItem(storage)
})
}
}