All files / app/common/utility retry.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 29147x                   147x       11x     11x   4x 1x     6x   3x      
const DEFAULT_OPTIONS = {
    count: 5,
    interval: 1000,
};
 
export interface RetryOptions {
    count?: number;
    interval?: number;
}
 
export default async function retry<T>(
    fn: () => Promise<T>,
    options?: RetryOptions
): Promise<T> {
    const { count, interval } = { ...DEFAULT_OPTIONS, ...options };
 
    try {
        return await fn();
    } catch (error) {
        if (count === 1) {
            throw error;
        }
 
        await new Promise(resolve => setTimeout(resolve, interval));
 
        return retry(fn, { interval, count: count - 1 });
    }
}