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

fix(xsfetch): make retry work, remove the exposure of retryCount #88

Merged
merged 2 commits into from
Mar 4, 2025
Merged
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
31 changes: 16 additions & 15 deletions packages/xsfetch/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,42 @@
import { sleep } from '../../utils-stream/src/_sleep'

export interface CreateFetchOptions {
debug: boolean
retry: number
/** @internal */
retryCount: number
retryDelay: number
retryStatusCodes: number[]
}

export const defaultCreateFetchOptions: CreateFetchOptions = {
debug: false,
retry: 3,
retryDelay: 500,
// https://github.com/unjs/ofetch#%EF%B8%8F-auto-retry
retryStatusCodes: [408, 409, 425, 429, 500, 502, 503, 504],
}

export const createFetch = (userOptions: Partial<CreateFetchOptions>): typeof globalThis.fetch => {
const options: CreateFetchOptions = {
retry: 3,
retryCount: 0,
retryDelay: 500,
// https://github.com/unjs/ofetch#%EF%B8%8F-auto-retry
retryStatusCodes: [408, 409, 425, 429, 500, 502, 503, 504],
const options: Readonly<CreateFetchOptions> = {
...defaultCreateFetchOptions,
...userOptions,
}

const xsfetch = async (options: CreateFetchOptions, input: Request | string | URL, init?: RequestInit) => {
const xsfetch = async (retriesLeft: number, input: Request | string | URL, init?: RequestInit) => {
const res = await fetch(input, init)

if (!res.ok && options.retryStatusCodes.includes(res.status) && options.retry < options.retryCount) {
if (!res.ok && retriesLeft > 0 && options.retryStatusCodes.includes(res.status)) {
options.debug && console.warn('[xsfetch] Failed, retrying... Times left:', retriesLeft)
await sleep(options.retryDelay)

return async () => xsfetch({
...options,
retryCount: options.retryCount + 1,
}, input, init)
return async () => xsfetch(retriesLeft - 1, input, init)
}
else {
return res
}
}

return async (input: Request | string | URL, init?: RequestInit) => {
let res = await xsfetch(options, input, init)
let res = await xsfetch(options.retry, input, init)

while (typeof res === 'function')
res = await res()
Expand Down
Loading