-
Notifications
You must be signed in to change notification settings - Fork 97
/
asyncStorage.js
81 lines (72 loc) · 1.9 KB
/
asyncStorage.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
// @flow
// $FlowFixMe
import { AsyncStorage } from 'react-native';
import Mutex from './mutex';
export default class {
mu: Mutex;
constructor() {
this.mu = new Mutex();
}
merge(
key: string,
reduce: (prev: string | null) => string | null,
): Promise<string | null> {
return this.mu.lock(key, async () => {
let prev = await AsyncStorage.getItem(key);
prev = typeof prev === 'undefined' ? null : prev;
const value = reduce(prev);
if (value !== null) {
await AsyncStorage.setItem(key, value);
} else if (prev !== null) {
await AsyncStorage.removeItem(key);
}
return value;
});
}
set(key: string, value: string): Promise<void> {
return new Promise((res, rej) => {
AsyncStorage.setItem(key, value, err => {
if (err) return rej(err);
res();
});
});
}
get(key: string): Promise<string | null> {
return new Promise((res, rej) => {
AsyncStorage.getItem(key, (err, result) => {
if (err) return rej(err);
res(typeof result === 'undefined' ? null : result);
});
});
}
multiGet(keys: string[]): Promise<{ [string]: string | null }> {
return new Promise((res, rej) => {
AsyncStorage.multiGet(keys, (err, tuples) => {
if (err) return rej(err);
const ret = {};
tuples.map((result, i, store) => {
const key = store[i][0];
const value = store[i][1];
ret[key] = value;
});
res(ret);
});
});
}
remove(key: string): Promise<void> {
return new Promise((res, rej) => {
AsyncStorage.removeItem(key, err => {
if (err) return rej(err);
res();
});
});
}
keys(): Promise<Array<string>> {
return new Promise((res, rej) => {
AsyncStorage.getAllKeys((err, keys) => {
if (err) return rej(err);
res(keys || []);
});
});
}
}