-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
59 lines (48 loc) · 1.61 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
/* eslint-disable import/no-unused-modules */
const RETRIES_LEFT = 3
const INTERVAL = 500
/** Retryable function */
export type RetryableFunction<T> = (...args: any[]) => Promise<T>
/** Retry options */
export interface RetryOptions {
/** Maximum amount of times to retry the operation, default is 3 */
retries?: number
/** Number of milliseconds before starting the retry, default is 500 */
timeout?: number
/** Check an error to need retry, by default retry on every error */
shouldRetry?: (error: Error) => boolean
/** AbortSignal instance to abort retry via an AbortController */
signal?: AbortSignal
}
/** Retry function call */
export function retry<T>(
retryableFunction: RetryableFunction<T>,
options: RetryOptions = {}
): RetryableFunction<T> {
let {retries = RETRIES_LEFT} = options
const {timeout = INTERVAL, shouldRetry = () => true, signal} = options
async function call(...args: any[]): Promise<T> {
try {
return await retryableFunction(...args)
} catch (error: any) {
if (--retries < 1 || !shouldRetry(error)) {
throw error
}
await wait(timeout, signal)
return call(...args)
}
}
return (...args: any[]): Promise<T> => call(...args)
}
/** Wait function call */
export function wait(timeout: number, signal?: AbortSignal): Promise<void> {
return new Promise<void>((resolve, reject) => {
const timeoutId = window.setTimeout(resolve, timeout)
signal?.addEventListener('abort', () => {
if (timeoutId) {
clearTimeout(timeoutId)
}
reject(new DOMException('The user aborted a timeout.', 'AbortError'))
})
})
}