Skip to content

Commit

Permalink
feat: retry interval
Browse files Browse the repository at this point in the history
  • Loading branch information
Bekacru committed Jul 15, 2024
1 parent 31582be commit 2de0e27
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 deletions.
12 changes: 10 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,18 @@ export const betterFetch = async <
await onError(errorContext);
}
}
if (options?.retry) {
if (options?.retry && options.retry.count > 0) {
if (options.retry.interval) {
await new Promise((resolve) =>
setTimeout(resolve, options.retry?.interval),
);
}
return await betterFetch(url, {
...options,
retry: options.retry - 1,
retry: {
count: options.retry.count - 1,
interval: options.retry.interval,
},
});
}

Expand Down
9 changes: 7 additions & 2 deletions src/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,10 @@ describe("fetch", () => {
it("should retry on error", async () => {
let count = 0;
await betterFetch(getURL("error"), {
retry: 3,
retry: {
count: 3,
interval: 0,
},
onError() {
count++;
},
Expand All @@ -169,7 +172,9 @@ describe("fetch", () => {
controller.abort();
const response = await betterFetch("", {
baseURL: getURL("ok"),
retry: 3,
retry: {
count: 3,
},
signal: controller.signal,
});
}
Expand Down
14 changes: 10 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export type BetterFetchOption<
FetchHooks & {
/**
* a timeout that will be used to abort the
* request
* request. Should be in milliseconds.
*/
timeout?: number;
/**
Expand All @@ -43,7 +43,7 @@ export type BetterFetchOption<
customFetchImpl?: FetchEsque;
/**
* Better fetch plugins
* @see https://better-fetch.vercel.app/plugins
* @see https://better-fetch.vercel.app/docs/plugins
*/
plugins?: BetterFetchPlugin[];
/**
Expand Down Expand Up @@ -85,13 +85,19 @@ export type BetterFetchOption<
*/
duplex?: "full" | "half";
/**
* JSON parser
* Custom JSON parser
*/
jsonParser?: <T>(text: string) => Promise<T | undefined>;
/**
* Retry count
*/
retry?: number;
retry?: {
count: number;
/**
* Retry interval in milliseconds
*/
interval?: number;
};
/**
* HTTP method
*/
Expand Down

0 comments on commit 2de0e27

Please sign in to comment.