-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.js
66 lines (57 loc) · 1.43 KB
/
storage.js
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
/*
* @Author: baosheng
* @Date: 2018-04-02 22:28:51
* @Last Modified by: baosheng
* @Last Modified time: 2018-04-02 22:32:17
*/
const storage = { version: '1.3.17' }
storage.has = key => storage.get(key) !== undefined
storage.transact = (key, defaultVal, transactionFn) => {
let val = ''
if (transactionFn === null) {
transactionFn = defaultVal
defaultVal = null
}
if (defaultVal === null) {
defaultVal = {}
}
val = storage.get(key, defaultVal)
transactionFn(val)
storage.set(key, val)
}
storage.serialize = value => JSON.stringify(value)
storage.deserialize = value => {
if (typeof value !== 'string') { return undefined }
try {
return JSON.parse(value)
} catch (e) {
return value || undefined
}
}
storage.set = (key, val) => {
if (val === undefined) { return storage.remove(key) }
localStorage.setItem(key, storage.serialize(val))
return val
}
storage.get = (key, defaultVal) => {
const val = storage.deserialize(localStorage.getItem(key))
return (val === undefined ? defaultVal : val)
}
storage.remove = key => localStorage.removeItem(key)
storage.clear = () => localStorage.clear()
storage.getAll = () => {
const ret = {}
storage.forEach((key, val) => {
ret[key] = val
})
return ret
}
storage.forEach = callback => {
let i = 0
let key = ''
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i)
callback(key, storage.get(key))
}
}
export default storage