forked from react-native-async-storage/async-storage
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
106 lines (96 loc) · 2.31 KB
/
index.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
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
/**
* Copyright (c) React Native Community.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {
IStorageBackend,
EmptyStorageModel,
StorageOptions,
} from '@react-native-community/async-storage';
class WebStorage<T extends EmptyStorageModel = EmptyStorageModel>
implements IStorageBackend<T> {
storage: any;
constructor(sessionStorage: boolean | string = false) {
this.storage = sessionStorage ? window.sessionStorage : window.localStorage;
}
async getSingle<K extends keyof T>(
key: K,
opts?: StorageOptions,
): Promise<T[K] | null> {
if (opts) {
// noop
}
return this.storage.getItem(key);
}
async setSingle<K extends keyof T>(
key: K,
value: T[K],
opts?: StorageOptions,
): Promise<void> {
if (opts) {
// noop
}
return this.storage.setItem(key, value);
}
async getMany<K extends keyof T>(
keys: Array<K>,
opts?: StorageOptions,
): Promise<{[k in K]: T[k] | null}> {
if (opts) {
// noop
}
return keys.reduce(
(storageValues, key) => {
return {
...storageValues,
[key]: this.storage.getItem(key),
};
},
{} as {[k in K]: T[k] | null},
);
}
async setMany<K extends keyof T>(
values: Array<Partial<{[k in K]: T[k]}>>,
opts?: StorageOptions,
): Promise<void> {
if (opts) {
// noop
}
for (let keyValue of values) {
const key = Object.getOwnPropertyNames(keyValue)[0] as K;
if (!key) {
continue;
}
this.storage.setItem(key, keyValue[key]);
}
}
async removeSingle(key: keyof T, opts?: StorageOptions): Promise<void> {
if (opts) {
// noop
}
return this.storage.removeItem(key);
}
async removeMany(keys: Array<keyof T>, opts?: StorageOptions): Promise<void> {
if (opts) {
// noop
}
Promise.all(keys.map(k => this.storage.removeItem(k)));
}
async getKeys(opts?: StorageOptions): Promise<Array<keyof T>> {
if (opts) {
// noop
}
return Object.keys(this.storage);
}
async dropStorage(opts?: StorageOptions): Promise<void> {
if (opts) {
// noop
}
const keys = await this.getKeys();
await this.removeMany(keys);
}
}
export default WebStorage;