Skip to content

Commit

Permalink
Timeout triggered on createApi endpoint now correctly returns `TIME…
Browse files Browse the repository at this point in the history
…OUT_ERROR` instead of generic `AbortError`.
  • Loading branch information
andrejpavlovic committed Sep 19, 2024
1 parent bc0bf0f commit b6c5d1f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
15 changes: 12 additions & 3 deletions packages/toolkit/src/query/fetchBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export function fetchBaseQuery({
)
}
return async (arg, api) => {
const { signal, getState, extra, endpoint, forced, type } = api
const { getState, extra, endpoint, forced, type } = api
let meta: FetchBaseQueryMeta | undefined
let {
url,
Expand All @@ -224,6 +224,14 @@ export function fetchBaseQuery({
timeout = defaultTimeout,
...rest
} = typeof arg == 'string' ? { url: arg } : arg

let abortController: AbortController | undefined, signal = api.signal
if (timeout) {
abortController = new AbortController()
api.signal.addEventListener('abort', abortController.abort)
signal = abortController.signal
}

let config: RequestInit = {
...baseFetchOptions,
signal,
Expand Down Expand Up @@ -272,10 +280,10 @@ export function fetchBaseQuery({
let response,
timedOut = false,
timeoutId =
timeout &&
abortController &&
setTimeout(() => {
timedOut = true
api.abort()
abortController.abort()
}, timeout)
try {
response = await fetchFn(request)
Expand All @@ -289,6 +297,7 @@ export function fetchBaseQuery({
}
} finally {
if (timeoutId) clearTimeout(timeoutId)
abortController?.signal.removeEventListener('abort', abortController.abort)
}
const responseClone = response.clone()

Expand Down
35 changes: 35 additions & 0 deletions packages/toolkit/src/query/tests/createApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1128,3 +1128,38 @@ describe('custom serializeQueryArgs per endpoint', () => {
})
})
})

describe('timeout behavior', () => {
test('triggers TIMEOUT_ERROR', async () => {
const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com', timeout: 5 }),
endpoints: (build) => ({
query: build.query<unknown, void>({
query: () => '/success',
}),
}),
})

const storeRef = setupApiStore(api, undefined, {
withoutTestLifecycles: true,
})

server.use(
http.get(
'https://example.com/success',
async () => {
await delay(10)
return HttpResponse.json({ value: 'failed' }, { status: 500 })
},
{ once: true },
),
)

const result = await storeRef.store.dispatch(api.endpoints.query.initiate())

expect(result?.error).toEqual({
status: 'TIMEOUT_ERROR',
error: expect.stringMatching(/^AbortError:/),
})
})
})

0 comments on commit b6c5d1f

Please sign in to comment.