-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathretry.ts
41 lines (35 loc) · 952 Bytes
/
retry.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
// Import Internal Dependencies
import Operation, { OperationResult } from "./class/Operation.class";
import { PolicyCallback, none } from "./policies";
/**
* Those options are inspired by the retry package
* @see https://www.npmjs.com/package/retry
*/
export interface RetryOptions {
retries?: number;
minTimeout?: number;
maxTimeout?: number;
unref?: boolean;
factor?: number;
forever?: boolean;
signal?: AbortSignal | null;
}
export type RetryCallback<T> = (() => Promise<T>) | (() => T);
export async function retry<T>(
callback: RetryCallback<T>, options: RetryOptions = {}, policy: PolicyCallback = none
): Promise<OperationResult<T>> {
const op = new Operation<T>(options);
do {
try {
const data = await callback();
op.success(data);
}
catch (error: any) {
if (policy(error)) {
throw error;
}
await op.retry();
}
} while (op.continue);
return op.toJSON();
}