-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage-factory.ts
75 lines (67 loc) · 1.57 KB
/
storage-factory.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
75
export function storageFactory(getStorage: () => Storage): Storage {
let inMemoryStorage: { [key: string]: string } = {}
function isSupported() {
try {
const testKey = '__some_random_key_you_are_not_going_to_use__'
getStorage().setItem(testKey, testKey)
getStorage().removeItem(testKey)
return true
} catch (e) {
return false
}
}
function clear(): void {
if (isSupported()) {
getStorage().clear()
} else {
inMemoryStorage = {}
}
}
function getItem(name: string): string | null {
if (isSupported()) {
return getStorage().getItem(name)
}
if (inMemoryStorage.hasOwnProperty(name)) {
return inMemoryStorage[name]
}
return null
}
function key(index: number): string | null {
if (isSupported()) {
return getStorage().key(index)
} else {
return Object.keys(inMemoryStorage)[index] || null
}
}
function removeItem(name: string): void {
if (isSupported()) {
getStorage().removeItem(name)
} else {
delete inMemoryStorage[name]
}
}
function setItem(name: string, value: string): void {
if (isSupported()) {
getStorage().setItem(name, value)
} else {
inMemoryStorage[name] = String(value) // not everyone uses TypeScript
}
}
function length(): number {
if (isSupported()) {
return getStorage().length
} else {
return Object.keys(inMemoryStorage).length
}
}
return {
getItem,
setItem,
removeItem,
clear,
key,
get length() {
return length()
},
}
}