| 1 | export function withExponentialBackoff<T, Args extends any[]>( |
| 2 | fn: (...args: Args) => Promise<T>, |
| 3 | maxAttempts: number = 3, |
| 4 | baseDelay: number = 1000, |
| 5 | ): (...args: Args) => Promise<T> { |
| 6 | return async (...args: Args): Promise<T> => { |
| 7 | for (let attempt = 0; attempt < maxAttempts; attempt++) { |
| 8 | try { |
| 9 | return await fn(...args); |
| 10 | } catch (error) { |
| 11 | if (attempt === maxAttempts - 1) throw error; |
| 12 | |
| 13 | const delay = baseDelay * Math.pow(2, attempt); |
| 14 | await new Promise((resolve) => setTimeout(resolve, delay)); |
| 15 | } |
| 16 | } |
| 17 | throw new Error("Unreachable code"); |
| 18 | }; |
| 19 | } |