24 lines
753 B
TypeScript
24 lines
753 B
TypeScript
import { sleep } from './sleep.js';
|
|
import { logger } from './logger.js';
|
|
|
|
export async function retry<T>(
|
|
fn: () => Promise<T>,
|
|
options: { maxAttempts?: number; delayMs?: number; label?: string } = {},
|
|
): Promise<T> {
|
|
const { maxAttempts = 3, delayMs = 1000, label = 'operation' } = options;
|
|
|
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
try {
|
|
return await fn();
|
|
} catch (err) {
|
|
if (attempt === maxAttempts) {
|
|
logger.error({ err, attempt, label }, `${label} failed after ${maxAttempts} attempts`);
|
|
throw err;
|
|
}
|
|
logger.warn({ err, attempt, label }, `${label} failed, retrying in ${delayMs}ms...`);
|
|
await sleep(delayMs * attempt);
|
|
}
|
|
}
|
|
|
|
throw new Error('Unreachable');
|
|
}
|