-
Notifications
You must be signed in to change notification settings - Fork 97
/
storage.js
108 lines (93 loc) · 2.68 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// @flow
export interface Storage {
merge(
key: string,
reduce: (prev: string | null) => string | null,
): Promise<string | null>;
set(key: string, value: string): Promise<void>;
get(key: string): Promise<string | null>;
multiGet(keys: string[]): Promise<{ [string]: string | null }>;
remove(key: string): Promise<void>;
keys(): Promise<Array<string>>;
}
export class InMemory implements Storage {
storage: { [string]: string };
constructor(storage: { [string]: string } = {}) {
this.storage = storage;
}
merge(
key: string,
reduce: (prev: string | null) => string | null,
): Promise<string | null> {
const value = reduce(
this.storage.hasOwnProperty(key) ? this.storage[key] : null,
);
if (value !== null) {
this.storage[key] = value;
} else {
delete this.storage[key];
}
return Promise.resolve(value);
}
set(key: string, value: string): Promise<void> {
this.storage[key] = value;
return Promise.resolve();
}
get(key: string): Promise<string | null> {
const v = this.storage[key];
return Promise.resolve(typeof v === 'undefined' ? null : v);
}
multiGet(keys: string[]): Promise<{ [string]: string | null }> {
const ret = {};
for (const k of keys) {
ret[k] = this.storage[k];
if (typeof ret[k] === 'undefined') ret[k] = null;
}
return Promise.resolve(ret);
}
remove(key: string): Promise<void> {
delete this.storage[key];
return Promise.resolve();
}
keys(): Promise<Array<string>> {
return Promise.resolve(Object.keys(this.storage));
}
}
export class LocalStorage implements Storage {
merge(
key: string,
reduce: (prev: string | null) => string | null,
): Promise<string | null> {
// $FlowFixMe
const value = reduce(localStorage.getItem(key));
if (value !== null) {
localStorage.setItem(key, value);
} else {
localStorage.removeItem(key);
}
return Promise.resolve(value);
}
set(key: string, value: string): Promise<void> {
localStorage.setItem(key, value);
return Promise.resolve();
}
get(key: string): Promise<string | null> {
const v = localStorage.getItem(key);
return Promise.resolve(typeof v === 'undefined' ? null : v);
}
multiGet(keys: string[]): Promise<{ [string]: string | null }> {
const ret = {};
for (const k of keys) {
const item = localStorage.getItem(k);
ret[k] = typeof item === 'undefined' ? null : item;
}
return Promise.resolve(ret);
}
remove(key: string): Promise<void> {
localStorage.removeItem(key);
return Promise.resolve();
}
keys(): Promise<Array<string>> {
return Promise.resolve(Object.keys(localStorage));
}
}