Skip to content

Commit

Permalink
feat: implement fetchWithExponentialBackoff
Browse files Browse the repository at this point in the history
  • Loading branch information
eudiwtech committed Dec 12, 2024
1 parent f098e4e commit cdf18bb
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions ts/features/wallet/utils/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,36 @@ export function createWalletProviderFetch(
return (input: RequestInfo | URL, init?: RequestInit) =>
fetch(input, addAuthHeaders(authHeader, init));
}

type FetchOptions = RequestInit & {
headers?: Record<string, string>;
};

export async function fetchWithExponentialBackoff(
url: string,
options: FetchOptions,
maxRetries = 5,
baseDelay = 500,
retries = 0
): Promise<Response> {
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;
}
}

0 comments on commit cdf18bb

Please sign in to comment.