forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
68 lines (57 loc) · 2.5 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
import * as ActiveClientManager from '@libs/ActiveClientManager';
import CONST from '@src/CONST';
import type {Request} from '@src/types/onyx';
import type Response from '@src/types/onyx/Response';
import pkg from '../../../package.json';
import * as MainQueue from './MainQueue';
import * as SequentialQueue from './SequentialQueue';
let processQueueInterval: NodeJS.Timer;
// We must wait until the ActiveClientManager is ready so that we ensure only the "leader" tab processes any persisted requests
ActiveClientManager.isReady().then(() => {
SequentialQueue.flush();
// Start main queue and process once every n ms delay
processQueueInterval = setInterval(MainQueue.process, CONST.NETWORK.PROCESS_REQUEST_DELAY_MS);
});
// Clear interval
function clearProcessQueueInterval() {
if (!processQueueInterval) {
return;
}
clearInterval(processQueueInterval as unknown as number);
}
/**
* Perform a queued post request
*/
function post(command: string, data: Record<string, unknown> = {}, type = CONST.NETWORK.METHOD.POST, shouldUseSecure = false): Promise<Response> {
return new Promise((resolve, reject) => {
const request: Request = {
command,
data,
type,
shouldUseSecure,
};
// By default, request are retry-able and cancellable
// (e.g. any requests currently happening when the user logs out are cancelled)
request.data = {
...data,
shouldRetry: data?.shouldRetry ?? true,
canCancel: data?.canCancel ?? true,
appversion: pkg.version,
};
// Add promise handlers to any request that we are not persisting
request.resolve = resolve;
request.reject = reject;
// Add the request to a queue of actions to perform
MainQueue.push(request);
// This check is mainly used to prevent API commands from triggering calls to MainQueue.process() from inside the context of a previous
// call to MainQueue.process() e.g. calling a Log command without this would cause the requests in mainQueue to double process
// since we call Log inside MainQueue.process().
const shouldProcessImmediately = request?.data?.shouldProcessImmediately ?? true;
if (!shouldProcessImmediately) {
return;
}
// Try to fire off the request as soon as it's queued so we don't add a delay to every queued command
MainQueue.process();
});
}
export {post, clearProcessQueueInterval};