Skip to content

Commit

Permalink
Merge pull request #4628 from andrejpavlovic/fix/timeout-on-createApi…
Browse files Browse the repository at this point in the history
…-endpoint-should-throw-TIMEOUT_ERROR

Fix `AbortError` being triggered incorrectly on `createApi` endpoint timeout
  • Loading branch information
EskiMojo14 authored Sep 24, 2024
2 parents f009cc9 + d9a9106 commit eb11019
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 @@ -1147,3 +1147,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 eb11019

Please sign in to comment.