-
Notifications
You must be signed in to change notification settings - Fork 3k
/
PersistedRequests.ts
61 lines (52 loc) · 1.98 KB
/
PersistedRequests.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
import isEqual from 'lodash/isEqual';
import Onyx from 'react-native-onyx';
import Log from '@libs/Log';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Request} from '@src/types/onyx';
let persistedRequests: Request[] = [];
Onyx.connect({
key: ONYXKEYS.PERSISTED_REQUESTS,
callback: (val) => (persistedRequests = val ?? []),
});
/**
* This promise is only used by tests. DO NOT USE THIS PROMISE IN THE APPLICATION CODE
*/
function clear() {
return Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, []);
}
function getLength(): number {
return persistedRequests.length;
}
function save(requestToPersist: Request) {
const requests = [...persistedRequests, requestToPersist];
persistedRequests = requests;
Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, requests).then(() => {
Log.info(`[SequentialQueue] '${requestToPersist.command}' command queued. Queue length is ${getLength()}`);
});
}
function remove(requestToRemove: Request) {
/**
* We only remove the first matching request because the order of requests matters.
* If we were to remove all matching requests, we can end up with a final state that is different than what the user intended.
*/
const requests = [...persistedRequests];
const index = requests.findIndex((persistedRequest) => isEqual(persistedRequest, requestToRemove));
if (index === -1) {
return;
}
requests.splice(index, 1);
persistedRequests = requests;
Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, requests).then(() => {
Log.info(`[SequentialQueue] '${requestToRemove.command}' removed from the queue. Queue length is ${getLength()}`);
});
}
function update(oldRequestIndex: number, newRequest: Request) {
const requests = [...persistedRequests];
requests.splice(oldRequestIndex, 1, newRequest);
persistedRequests = requests;
Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, requests);
}
function getAll(): Request[] {
return persistedRequests;
}
export {clear, save, getAll, remove, update, getLength};