-
Notifications
You must be signed in to change notification settings - Fork 94
/
RCTAsyncLocalStorage.js
86 lines (76 loc) · 2.12 KB
/
RCTAsyncLocalStorage.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
/** @flow */
import * as idbKeyval from "idb-keyval";
import deepmerge from "deepmerge";
import RCTModule from "RCTModule";
import type RCTBridge from "RCTBridge";
class RCTAsyncLocalStorage extends RCTModule {
static moduleName = "RCTAsyncLocalStorage";
$multiGet(keys: string[], callbackId: number) {
const callback = this.bridge.callbackFromId(callbackId);
Promise.all(
keys.map((key) => {
return idbKeyval.get(key);
})
)
.then((result) => {
callback(null, result.map((value, index) => [keys[index], value]));
})
.catch((err) => {
callback(err);
});
}
$multiMerge(kvPairs: [string, any][], callbackId: number) {
const callback = this.bridge.callbackFromId(callbackId);
Promise.all(
kvPairs.map(([key, prevValue]) => {
return idbKeyval.get(key).then((nextValue) => {
if (nextValue == null || typeof nextValue !== "object") {
return idbKeyval.set(key, prevValue);
}
return idbKeyval.set(key, deepmerge(prevValue, nextValue));
});
})
).then(() => {
callback();
});
}
$multiSet(kvPairs: [string, any][], callbackId: number) {
const callback = this.bridge.callbackFromId(callbackId);
Promise.all(
kvPairs.map(([key, value]) => {
return idbKeyval.set(key, value);
})
).then(() => {
callback();
});
}
$multiRemove(keys: string[], callbackId: number) {
const callback = this.bridge.callbackFromId(callbackId);
Promise.all(
keys.map((key) => {
return idbKeyval.del(key);
})
).then(() => {
callback();
});
}
async $getAllKeys(callbackId: number) {
const callback = this.bridge.callbackFromId(callbackId);
try {
const keys = await idbKeyval.keys();
callback(null, keys);
} catch (err) {
callback(err, null);
}
}
async $clear(callbackId: number) {
const callback = this.bridge.callbackFromId(callbackId);
try {
await idbKeyval.clear();
callback(null);
} catch (err) {
callback(err);
}
}
}
export default RCTAsyncLocalStorage;