| 27 | * @throws An error if the maximum number of retries is exceeded. |
| 28 | */ |
| 29 | export async function fetchWithRetry( |
| 30 | url: string, |
| 31 | options: RequestInit = {}, |
| 32 | retryConfig: { retries?: number; delay?: number; backoff?: number } = {}, |
| 33 | ): Promise<Response> { |
| 34 | const { retries = 6, delay = 1000, backoff = 2 } = retryConfig |
| 35 | |
| 36 | // Loop for the specified number of retries |
| 37 | for (let i = 0; i <= retries; i++) { |
| 38 | try { |
| 39 | const response = await fetch(url, options) |
| 40 | |
| 41 | // If the response is OK, return it immediately |
| 42 | if (response.ok) { |
| 43 | return response |
| 44 | } |
| 45 | |
| 46 | // If it's a non-200 response, log the status and prepare to retry |
| 47 | console.warn( |
| 48 | `Fetch attempt ${i + 1} failed with status: ${response.status}. Retrying...`, |
| 49 | ) |
| 50 | |
| 51 | // Wait before the next attempt, with exponential backoff |
| 52 | if (i < retries) { |
| 53 | const currentDelay = delay * Math.pow(backoff, i) |
| 54 | await new Promise((resolve) => setTimeout(resolve, currentDelay)) |
| 55 | } |
| 56 | } catch (error) { |
| 57 | // Catch network errors and log a message |
| 58 | console.error( |
| 59 | `Fetch attempt ${i + 1} failed due to a network error:`, |
| 60 | error, |
| 61 | ) |
| 62 | |
| 63 | // Wait before the next attempt, with exponential backoff |
| 64 | if (i < retries) { |
| 65 | const currentDelay = delay * Math.pow(backoff, i) |
| 66 | await new Promise((resolve) => setTimeout(resolve, currentDelay)) |
| 67 | } else { |
| 68 | // If all retries have failed, re-throw the original error |
| 69 | throw error |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | // If the loop completes without a successful response, throw a final error |
| 75 | throw new Error(`Failed to fetch ${url} after ${retries} retries.`) |
| 76 | } |
| 77 | |
| 78 | // Define schema |
| 79 | const todoSchema = z.object({ |