-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathfetch.ts
More file actions
33 lines (29 loc) · 768 Bytes
/
fetch.ts
File metadata and controls
33 lines (29 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
type RetryOptions = RequestInit & {
maxRetry?: number;
delay?: number;
};
const isTimeoutError = (e: unknown): boolean =>
e instanceof Error &&
typeof e.cause === 'object' &&
e.cause !== null &&
'code' in e.cause &&
e.cause.code === 'ETIMEDOUT';
export const fetchWithRetry = async (
url: string,
{ maxRetry = 3, delay = 100, ...options }: RetryOptions = {}
) => {
for (let i = 1; i <= maxRetry; i++) {
try {
return await fetch(url, options);
} catch (e) {
console.debug(
`fetch of ${url} failed at ${Date.now()}, attempt ${i}/${maxRetry}`,
e
);
if (i === maxRetry || !isTimeoutError(e)) {
throw e;
}
await new Promise(resolve => setTimeout(resolve, delay * i));
}
}
};