-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
43 lines (38 loc) · 1.11 KB
/
Copy pathutils.ts
File metadata and controls
43 lines (38 loc) · 1.11 KB
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
34
35
36
37
38
39
40
41
42
43
export interface RetryOptions {
maxAttempts: number;
delayMs: number;
}
/**
* Retries an asynchronous function with a constant delay.
*/
export async function withRetry<T>(
operation: () => Promise<T>,
options: RetryOptions = { maxAttempts: 3, delayMs: 1000 }
): Promise<T> {
let lastError: Error | unknown;
for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
try {
return await operation();
} catch (err) {
lastError = err;
if (attempt < options.maxAttempts) {
await new Promise((resolve) => setTimeout(resolve, options.delayMs));
}
}
}
throw lastError instanceof Error
? lastError
: new Error(`Operation failed after ${options.maxAttempts} attempts: ${String(lastError)}`);
}
/**
* Wrapper for network calls to ensure resilience.
*/
export const fetchWithRetry = <T>(url: string, init?: RequestInit): Promise<T> => {
return withRetry(async () => {
const response = await fetch(url, init);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json() as Promise<T>;
});
};