diff --git a/src/fetch.ts b/src/fetch.ts index c0021c0..2c12000 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -62,7 +62,9 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch { ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode)) ) { - const retryDelay = context.options.retryDelay || 0; + const retryDelay = typeof context.options.retryDelay === 'function' ? + context.options.retryDelay(context) : + context.options.retryDelay || 0; if (retryDelay > 0) { await new Promise((resolve) => setTimeout(resolve, retryDelay)); } diff --git a/src/types.ts b/src/types.ts index d4f2e11..0db7537 100644 --- a/src/types.ts +++ b/src/types.ts @@ -53,7 +53,7 @@ export interface FetchOptions retry?: number | false; /** Delay between retries in milliseconds. */ - retryDelay?: number; + retryDelay?: number | ((context: FetchContext) => number); /** Default is [408, 409, 425, 429, 500, 502, 503, 504] */ retryStatusCodes?: number[]; diff --git a/test/index.test.ts b/test/index.test.ts index de25338..4c7bcb4 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -273,7 +273,7 @@ describe("ofetch", () => { expect(error.request).to.equal(getURL("404")); }); - it("retry with delay", async () => { + it("retry with number delay", async () => { const slow = $fetch(getURL("408"), { retry: 2, retryDelay: 100, @@ -287,6 +287,20 @@ describe("ofetch", () => { expect(race).to.equal("fast"); }); + it("retry with callback delay", async () => { + const slow = $fetch(getURL("408"), { + retry: 2, + retryDelay: () => 100, + }).catch(() => "slow"); + const fast = $fetch(getURL("408"), { + retry: 2, + retryDelay: () => 1, + }).catch(() => "fast"); + + const race = await Promise.race([slow, fast]); + expect(race).to.equal("fast"); + }); + it("abort with retry", () => { const controller = new AbortController(); async function abortHandle() {