Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support retryDelay with callback function #372

Merged
merged 1 commit into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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