RM
Ravi Menon · Cap backoff at one minute
18 lines
import type { Job, JobHandler } from './types'// Wait 1s, 2s, 4s... capped at one minute.export function backoff(attempts: number) {return Math.min(2 ** attempts * 1000, 60_000)}export function withRetry<Payload>(handler: JobHandler<Payload>, maxAttempts = 5): JobHandler<Payload> {return async (job: Job<Payload>) => {try {await handler(job)} catch (error) {if (job.attempts + 1 >= maxAttempts) throw errorawait new Promise(resolve => setTimeout(resolve, backoff(job.attempts)))await withRetry(handler, maxAttempts)({ ...job, attempts: job.attempts + 1 })}}}