| 1 | export interface RetryOptions { |
| 2 | maxRetries?: number |
| 3 | delayMs?: number |
| 4 | backoff?: 'linear' | 'exponential' |
| 5 | onRetry?: (error: Error, attempt: number) => void |
| 6 | } |
| 7 | |
| 8 | const DEFAULT_OPTIONS: Required<Omit<RetryOptions, 'onRetry'>> = { |
| 9 | maxRetries: 3, |
| 10 | delayMs: 1000, |
| 11 | backoff: 'linear', |
| 12 | } |
| 13 | |
| 14 | export async function retry<T>( |
| 15 | fn: () => Promise<T>, |
| 16 | options?: RetryOptions, |
| 17 | ): Promise<T> { |
| 18 | const { maxRetries, delayMs, backoff } = { ...DEFAULT_OPTIONS, ...options } |
| 19 | |
| 20 | let lastError: Error | undefined |
| 21 | |
| 22 | for (let attempt = 1; attempt <= maxRetries; attempt++) { |
| 23 | try { |
| 24 | return await fn() |
| 25 | } |
| 26 | catch (error) { |
| 27 | lastError = error instanceof Error ? error : new Error(String(error)) |
| 28 | options?.onRetry?.(lastError, attempt) |
| 29 | |
| 30 | if (attempt < maxRetries) { |
| 31 | const delay = backoff === 'exponential' |
| 32 | ? delayMs * 2 ** (attempt - 1) |
| 33 | : delayMs * attempt |
| 34 | await new Promise(resolve => setTimeout(resolve, delay)) |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | throw lastError |
| 40 | } |
| 41 |