All files / src/common/utils retry.ts

52.94% Statements 9/17
50% Branches 4/8
50% Functions 1/2
57.14% Lines 8/14

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 2417x       30x 30x 30x 30x 30x 30x 30x                          
export async function withRetry<T>(
  fn: () => Promise<T>,
  options: { tries?: number; baseDelayMs?: number; maxDelayMs?: number; onAttempt?: (attempt: number, err: unknown) => void } = {},
): Promise<T> {
  const tries = options.tries ?? 3;
  const base = options.baseDelayMs ?? 100;
  const max = options.maxDelayMs ?? 2000;
  let lastErr: unknown = undefined;
  for (let i = 1; i <= tries; i++) {
    try {
      return await fn();
    } catch (err) {
      lastErr = err;
      options.onAttempt?.(i, err);
      Iif (i === tries) break;
      const delay = Math.min(max, Math.floor(base * Math.pow(2, i - 1)) + Math.floor(Math.random() * 50));
      await new Promise((r) => setTimeout(r, delay));
    }
  }
  throw lastErr;
}