-
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathstorage.ts
37 lines (33 loc) · 839 Bytes
/
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
function withStorage<T>(f: (s: Storage) => T | void): T | void | null {
// can throw an exception when storage is full
try {
return window.localStorage ? f(window.localStorage) : null
} catch (e) { /* noop */ }
}
export default {
get,
set,
remove,
}
function get<T>(k: string): T | null {
return withStorage((s) => {
const item = s.getItem(k)
return item ? JSON.parse(item) : null
})
}
function remove(k: string): void {
withStorage((s) => {
s.removeItem(k)
})
}
function set<T>(k: string, v: T): void {
withStorage((s) => {
try {
s.setItem(k, JSON.stringify(v))
} catch (_) {
// http://stackoverflow.com/questions/2603682/is-anyone-else-receiving-a-quota-exceeded-err-on-their-ipad-when-accessing-local
s.removeItem(k)
s.setItem(k, JSON.stringify(v))
}
})
}