(
opts?: {
onError?: (e: any, failuresCount: number) => void,
minDelay?: number,
maxDelay?: number,
maxFailureCount?: number
})
| 10 | export type BackoffFunc = <T>(callback: () => Promise<T>) => Promise<T>; |
| 11 | |
| 12 | export function createBackoff( |
| 13 | opts?: { |
| 14 | onError?: (e: any, failuresCount: number) => void, |
| 15 | minDelay?: number, |
| 16 | maxDelay?: number, |
| 17 | maxFailureCount?: number |
| 18 | }): BackoffFunc { |
| 19 | return async <T>(callback: () => Promise<T>): Promise<T> => { |
| 20 | let currentFailureCount = 0; |
| 21 | const minDelay = opts && opts.minDelay !== undefined ? opts.minDelay : 250; |
| 22 | const maxDelay = opts && opts.maxDelay !== undefined ? opts.maxDelay : 1000; |
| 23 | const maxFailureCount = opts && opts.maxFailureCount !== undefined ? opts.maxFailureCount : 50; |
| 24 | while (true) { |
| 25 | try { |
| 26 | return await callback(); |
| 27 | } catch (e) { |
| 28 | if (currentFailureCount < maxFailureCount) { |
| 29 | currentFailureCount++; |
| 30 | } |
| 31 | if (opts && opts.onError) { |
| 32 | opts.onError(e, currentFailureCount); |
| 33 | } |
| 34 | let waitForRequest = exponentialBackoffDelay(currentFailureCount, minDelay, maxDelay, maxFailureCount); |
| 35 | await delay(waitForRequest); |
| 36 | } |
| 37 | } |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | export let backoff = createBackoff(); |
no test coverage detected