Skip to content

Commit 0b08f39

Browse files
committedNov 26, 2024
Add utility function retry, we will use this function in case of failure in AI streaming response to retry with variable like maxAttempts, baseDelay, maxDelay which we can pass in based on our need
1 parent c7a0d77 commit 0b08f39

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
 

‎utils/retry.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
interface RetryConfig {
2+
maxAttempts?: number;
3+
baseDelay?: number;
4+
maxDelay?: number;
5+
}
6+
7+
export async function withRetry<T>(
8+
fn: () => Promise<T>,
9+
config: RetryConfig = {}
10+
): Promise<T> {
11+
const { maxAttempts = 3, baseDelay = 1000, maxDelay = 10000 } = config;
12+
13+
let attempt = 1;
14+
15+
while (true) {
16+
try {
17+
return await fn();
18+
} catch (error) {
19+
if (attempt >= maxAttempts) {
20+
throw error;
21+
}
22+
23+
const delay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxDelay);
24+
25+
await new Promise(resolve => setTimeout(resolve, delay));
26+
attempt++;
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)
Please sign in to comment.