-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathhandlers.ts
74 lines (71 loc) · 2.27 KB
/
handlers.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
import { currentInstancesStatus, initialize } from './initializer';
/**
*
* A handler function used to handle all the
* calls made to native code. The purpose is
* to make sure that the storage is initialized
* before any read/write requests are sent to the
* MMKV instance.
*
*
* @param action The native function that will be called
* @param args Arguments for the native function
*/
export function handleAction<T extends (...args: any[]) => any | undefined | null>(
action: T,
...args: any[]
): ReturnType<T> | undefined {
// The last argument is always the instance id.
let id: string = args[args.length - 1];
if (!currentInstancesStatus[id]) {
currentInstancesStatus[id] = initialize(id);
}
if (!action) return undefined;
let result = action(...args);
if (result === undefined) currentInstancesStatus[id] = initialize(id);
result = action(...args);
return result;
}
/**
*
* A handler function used to handle all the
* calls made to native code. The purpose is
* to make sure that the storage is initialized
* before any read/write requests are sent to the
* MMKV instance.
*
*
* @param action The native function that will be called
* @param args Arguments for the native function
*/
export async function handleActionAsync<T extends (...args: any[]) => any | undefined | null>(
action: T,
...args: any[]
): Promise<ReturnType<T> | undefined | null> {
let id = args[args.length - 1];
return new Promise(resolve => {
if (!currentInstancesStatus[id]) {
currentInstancesStatus[id] = initialize(id);
}
if (!action) return resolve(undefined);
let result = action(...args);
if (result === undefined) currentInstancesStatus[id] = initialize(id);
result = action(...args);
resolve(result);
});
}
export async function handlePromise<T extends (...args: any[]) => any | undefined | null>(
action: T,
...args: any[]
): Promise<ReturnType<T> | undefined> {
// The last argument is always the instance id.
let id: string = args[args.length - 1];
if (!currentInstancesStatus[id]) {
currentInstancesStatus[id] = initialize(id);
}
if (!action) return undefined;
let result = await action(...args);
if (result === undefined) currentInstancesStatus[id] = initialize(id);
result = await action(...args);
return result;
}