Skip to content

Commit

Permalink
feat: support customizable retryStatusCodes (resolves #109)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 23, 2023
1 parent 9e20440 commit c1f075f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ await ofetch("/url", { ignoreResponseError: true });
- `503` - Service Unavailable
- `504` - Gateway Timeout

You can specifcy amount of retry and delay between them using `retry` and `retryDelay` options.
You can specifcy amount of retry and delay between them using `retry` and `retryDelay` options and also pass a custom array of codes using `retryStatusCodes` option.

Default for `retry` is `1` retry, except for `POST`, `PUT`, `PATCH` and `DELETE` methods where `ofetch` does not retry.

Expand Down
13 changes: 11 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,15 @@ export interface FetchOptions<R extends ResponseType = ResponseType>
query?: SearchParameters;
parseResponse?: (responseText: string) => any;
responseType?: R;
retry?: number | false;

/** timeout in milliseconds */
timeout?: number;

retry?: number | false;
/** Delay between retries in milliseconds. */
retryDelay?: number;
/** Default is [408, 409, 425, 429, 500, 502, 503, 504] */
retryStatusCodes?: number[];

onRequest?(context: FetchContext): Promise<void> | void;
onRequestError?(
Expand Down Expand Up @@ -113,7 +117,12 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
}

const responseCode = (context.response && context.response.status) || 500;
if (retries > 0 && retryStatusCodes.has(responseCode)) {
if (
retries > 0 &&
(Array.isArray(context.options.retryStatusCodes)
? context.options.retryStatusCodes.includes(responseCode)
: retryStatusCodes.has(responseCode))
) {
const retryDelay = context.options.retryDelay || 0;
if (retryDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
Expand Down

0 comments on commit c1f075f

Please sign in to comment.