From cdf18bb4e5f138d66b14d945cd30614a97c5ddaa Mon Sep 17 00:00:00 2001 From: eudiwtech Date: Thu, 12 Dec 2024 11:55:12 +0100 Subject: [PATCH] feat: implement fetchWithExponentialBackoff --- ts/features/wallet/utils/fetch.ts | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/ts/features/wallet/utils/fetch.ts b/ts/features/wallet/utils/fetch.ts index 1fe2f82..d231a98 100644 --- a/ts/features/wallet/utils/fetch.ts +++ b/ts/features/wallet/utils/fetch.ts @@ -61,3 +61,36 @@ export function createWalletProviderFetch( return (input: RequestInfo | URL, init?: RequestInit) => fetch(input, addAuthHeaders(authHeader, init)); } + +type FetchOptions = RequestInit & { + headers?: Record; +}; + +export async function fetchWithExponentialBackoff( + url: string, + options: FetchOptions, + maxRetries = 5, + baseDelay = 500, + retries = 0 +): Promise { + try { + const response = await fetch(url, options); + if (!response.ok) { + throw new Error(`HTTP Error: ${response.status}`); + } + return response; + } catch (error) { + if (retries < maxRetries) { + const delay = baseDelay * Math.pow(2, retries); + await new Promise(resolve => setTimeout(resolve, delay)); + return fetchWithExponentialBackoff( + url, + options, + maxRetries, + baseDelay, + retries + 1 + ); + } + throw error; + } +}