Skip to content

Commit

Permalink
feat: support retryDelay with callback function (#372)
Browse files Browse the repository at this point in the history
  • Loading branch information
escral committed May 16, 2024
1 parent c24c9a3 commit 9a5640c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export interface FetchOptions<R extends ResponseType = ResponseType>

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[];

Expand Down
16 changes: 15 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>(getURL("408"), {
retry: 2,
retryDelay: 100,
Expand All @@ -287,6 +287,20 @@ describe("ofetch", () => {
expect(race).to.equal("fast");
});

it("retry with callback delay", async () => {
const slow = $fetch<string>(getURL("408"), {
retry: 2,
retryDelay: () => 100,
}).catch(() => "slow");
const fast = $fetch<string>(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() {
Expand Down

0 comments on commit 9a5640c

Please sign in to comment.