29 lines
756 B
TypeScript
29 lines
756 B
TypeScript
import pRetry from 'p-retry';
|
|
import type { Logger } from './logger.js';
|
|
|
|
export async function withRetry<T>(
|
|
fn: () => Promise<T>,
|
|
options: {
|
|
retries?: number;
|
|
logger?: Logger;
|
|
operationName?: string;
|
|
} = {}
|
|
): Promise<T> {
|
|
const { retries = 3, logger, operationName = 'operation' } = options;
|
|
|
|
return pRetry(fn, {
|
|
retries,
|
|
minTimeout: 5000,
|
|
maxTimeout: 60000,
|
|
factor: 2,
|
|
randomize: true,
|
|
onFailedAttempt: (context) => {
|
|
const errorMessage = context.error instanceof Error ? context.error.message : String(context.error);
|
|
logger?.warn(
|
|
`${operationName} attempt ${context.attemptNumber} failed: ${errorMessage}. ` +
|
|
`${context.retriesLeft} retries left.`
|
|
);
|
|
},
|
|
});
|
|
}
|