Last active
February 1, 2024 12:30
-
-
Save jadepark-dev/bbd9b1d7a17e39b01e634540727c46e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Interface for fetch options. | |
*/ | |
interface FetchOptions { | |
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | |
headers?: Headers | |
body?: any | |
} | |
/** | |
* Fetches a resource from the specified URL with retry functionality. | |
* @param url - The URL of the resource to fetch. | |
* @param options - The fetch options. | |
* @param retry - The number of retries to attempt. | |
* @param delay - The delay in milliseconds between retries. | |
* @returns A Promise that resolves to the Response object. | |
* @throws Error if the fetch operation fails after all retries. | |
*/ | |
async function fetchWithRetry( | |
url: string, | |
options: FetchOptions, | |
retry = 3, | |
delay = 1000 | |
): Promise<Response> { | |
const { method, headers, body } = options | |
try { | |
return await fetch(url, { method, headers, body }) | |
} catch (error) { | |
console.error(`Error occurred during fetch`, error) | |
if (retry > 0) { | |
console.log(`Retrying fetch for ${url}. Remaining retries: ${retry}`) | |
await new Promise((resolve) => setTimeout(resolve, delay)) | |
return fetchWithRetry(url, options, retry - 1, delay) | |
} else { | |
throw new Error(`Failed to fetch ${url}`) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment