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: retry callback #359

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,16 @@ await ofetch("http://google.com/404", {
});
```

You can also pass a callback as a `retry` option. It takes a fetch context object and the count of retries and returns a boolean.

```ts
await $fetch("/api", {
retry: (ctx, count) => {
return count <= 3 && ctx.error?.code === "007";
},
});
```

## βœ”οΈ Timeout

You can specify `timeout` in milliseconds to automatically abort a request after a timeout (default is disabled).
Expand Down
37 changes: 26 additions & 11 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
AbortController = globalThis.AbortController,
} = globalOptions;

async function onError(context: FetchContext): Promise<FetchResponse<any>> {
async function getRetryResponse(
context: FetchContext
): Promise<FetchResponse<any> | void> {
// Is Abort
// If it is an active abort, it will not retry automatically.
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names
Expand All @@ -56,24 +58,35 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
}

const responseCode = (context.response && context.response.status) || 500;
if (
retries > 0 &&
(Array.isArray(context.options.retryStatusCodes)
? context.options.retryStatusCodes.includes(responseCode)
: retryStatusCodes.has(responseCode))
) {
const retryDelay = context.options.retryDelay || 0;
const hasStatusCode = Array.isArray(context.options.retryStatusCodes)
? context.options.retryStatusCodes.includes(responseCode)
: retryStatusCodes.has(responseCode);
// @ts-expect-error value for internal use
const { retry, retryDelay = 0, _retryCount = 1 } = context.options;
const shouldRetry =
typeof retry === "function" ? await retry(context, _retryCount) : false;

if ((retries > 0 && hasStatusCode) || shouldRetry) {
if (retryDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
}
// Timeout
return $fetchRaw(context.request, {
...context.options,
retry: retries - 1,
timeout: context.options.timeout,
retry: typeof retry === "function" ? retry : retries - 1,
// @ts-expect-error value for internal use
_retryCount: _retryCount + 1,
});
}
}
}

async function onError(context: FetchContext): Promise<FetchResponse<any>> {
const retryResponse = await getRetryResponse(context);

if (retryResponse) {
return retryResponse;
}

// Throw normalized error
const error = createFetchError(context);
Expand Down Expand Up @@ -213,7 +226,9 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
return await onError(context);
}

return context.response;
const retryResponse = await getRetryResponse(context);

return retryResponse || context.response;
};

const $fetch = async function $fetch(request, options) {
Expand Down
5 changes: 4 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export interface FetchOptions<R extends ResponseType = ResponseType>
/** timeout in milliseconds */
timeout?: number;

retry?: number | false;
retry?:
| number
| false
| ((context: FetchContext, count: number) => Promise<boolean> | boolean);
/** Delay between retries in milliseconds. */
retryDelay?: number;
/** Default is [408, 409, 425, 429, 500, 502, 503, 504] */
Expand Down
9 changes: 8 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
readRawBody,
toNodeListener,
} from "h3";
import { describe, beforeAll, afterAll, it, expect } from "vitest";
import { describe, beforeAll, afterAll, it, expect, vi } from "vitest";
import { Headers, FormData, Blob } from "node-fetch-native";
import { nodeMajorVersion } from "std-env";
import { $fetch } from "../src/node";
Expand Down Expand Up @@ -287,6 +287,13 @@ describe("ofetch", () => {
expect(race).to.equal("fast");
});

it("retry callback", async () => {
const retry = vi.fn().mockImplementation((_, count) => count <= 3);
await $fetch<string>(getURL("ok"), { retry });

expect(retry).toHaveBeenCalledTimes(4);
});

it("abort with retry", () => {
const controller = new AbortController();
async function abortHandle() {
Expand Down