1 import { setTimeout } from "timers/promises"
2
3 const ONE_SECOND = 1000
4
5 /**
6 * Retry the function to be executed until it succeeds or the max retries is reached.
7 *
8 * @param fn - The function to be executed.
9 * @param options - The options for the retry execution.
10 * @param options.shouldRetry - The function to determine if the function should be retried based on the error argument.
11 * @param options.maxRetries - The maximum number of retries.
12 * @param options.retryDelay - The delay between retries. If a function is provided, it will be called with the current retry count and the maximum number of retries and should return the delay in milliseconds.
13 * @param options.onRetry - The function to be called when the function fails to execute.
14 * @returns The result of the function.
15 */
16 export async function retryExecution<T>(
17 fn: () => Promise<T>,
18 options: {
19 shouldRetry?: (error: any) => boolean
20 onRetry?: (error: any) => void
21 maxRetries?: number
22 retryDelay?: number | ((retries: number, maxRetries: number) => number)
23 } = {
24 shouldRetry: () => true,
25 onRetry: () => {},
26 maxRetries: 5,
27 retryDelay: ONE_SECOND,
28 }
29 ): Promise<T> {
30 let { shouldRetry, onRetry, maxRetries, retryDelay } = options
31 shouldRetry = shouldRetry ?? (() => true)
32 maxRetries = maxRetries ?? 5
33 onRetry = onRetry ?? (() => {})
34
35 const retryDelayFn =
36 typeof retryDelay === "function"
37 ? retryDelay
38 : (retries: number, maxRetries: number) => retryDelay
39
40 let retries = 0
41 while (retries < maxRetries) {
42 try {
43 return await fn()
44 } catch (error) {
45 if (!shouldRetry(error as Error)) {
46 throw error
47 }
48 retries++
49 if (retries === maxRetries) {
50 throw error
51 }
52
53 onRetry(error)
54
55 await setTimeout(retryDelayFn(retries, maxRetries))
56 }
57 }
58
59 // This should never be reached
60 throw new Error("Retry execution failed. Max retries reached.")
61 }