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

fetchBaseQuery: expose extraOptions to prepareHeaders #4291

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 21 additions & 6 deletions packages/toolkit/src/query/fetchBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,14 @@ function stripUndefined(obj: any) {
return copy
}

export type FetchBaseQueryArgs = {
export type FetchBaseQueryArgs<ExtraOptions = {}> = {
baseUrl?: string
prepareHeaders?: (
headers: Headers,
api: Pick<
BaseQueryApi,
'getState' | 'extra' | 'endpoint' | 'type' | 'forced'
>,
> & { extraOptions: ExtraOptions },
) => MaybePromise<Headers | void>
fetchFn?: (
input: RequestInfo,
Expand Down Expand Up @@ -188,7 +188,21 @@ export type FetchBaseQueryMeta = { request: Request; response?: Response }
* @param {number} timeout
* A number in milliseconds that represents the maximum time a request can take before timing out.
*/
export function fetchBaseQuery({
export function fetchBaseQuery(options?: FetchBaseQueryArgs<{}>): BaseQueryFn<
string | FetchArgs,
unknown,
FetchBaseQueryError,
{},
FetchBaseQueryMeta
>
export function fetchBaseQuery<ExtraOptions>(options?: FetchBaseQueryArgs<ExtraOptions>): BaseQueryFn<
string | FetchArgs,
unknown,
FetchBaseQueryError,
ExtraOptions,
FetchBaseQueryMeta
>
export function fetchBaseQuery<ExtraOptions>({
baseUrl,
prepareHeaders = (x) => x,
fetchFn = defaultFetchFn,
Expand All @@ -200,19 +214,19 @@ export function fetchBaseQuery({
responseHandler: globalResponseHandler,
validateStatus: globalValidateStatus,
...baseFetchOptions
}: FetchBaseQueryArgs = {}): BaseQueryFn<
}: FetchBaseQueryArgs<ExtraOptions> = {}): BaseQueryFn<
string | FetchArgs,
unknown,
FetchBaseQueryError,
{},
ExtraOptions,
FetchBaseQueryMeta
> {
if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {
console.warn(
'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.',
)
}
return async (arg, api) => {
return async (arg, api, extraOptions) => {
const { signal, getState, extra, endpoint, forced, type } = api
let meta: FetchBaseQueryMeta | undefined
let {
Expand All @@ -238,6 +252,7 @@ export function fetchBaseQuery({
endpoint,
forced,
type,
extraOptions
})) || headers

// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.
Expand Down
47 changes: 47 additions & 0 deletions packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createSlice } from '@reduxjs/toolkit'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import { headersToObject } from 'headers-polyfill'
import { HttpResponse, delay, http } from 'msw'
// @ts-ignore
import nodeFetch from 'node-fetch'
import queryString from 'query-string'
import { vi } from 'vitest'
Expand Down Expand Up @@ -850,6 +851,52 @@ describe('fetchBaseQuery', () => {
expect(_forced).toBe(true)
expect(_extra).toBe(fakeAuth0Client)
})

test('can be instantiated with a `ExtraOptions` generic and `extraOptions` will be available in `prepareHeaders', async () => {
const prepare = vitest.fn()
const baseQuery = fetchBaseQuery<{ foo?: string; bar?: number }>({
prepareHeaders(headers, api) {
expectTypeOf(api.extraOptions).toEqualTypeOf<{ foo?: string; bar?: number }>()
prepare.apply(undefined, arguments)
},
})
baseQuery('http://example.com', commonBaseQueryApi, { foo: 'baz', bar: 5 })
expect(prepare).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ extraOptions: { foo: 'baz', bar: 5 } })
)

// ensure types
createApi({
baseQuery,
endpoints(build) {
return {
testQuery: build.query({
query: () => ({ url: '/echo', headers: {} }),
extraOptions: {
foo: 'asd',
bar: 1,
// @ts-expect-error
baz: 5,
},
}),
testMutation: build.mutation({
query: () => ({
url: '/echo',
method: 'POST',
credentials: 'omit',
}),
extraOptions: {
foo: 'qwe',
bar: 15,
// @ts-expect-error
baz: 5,
},
}),
}
},
})
})
})

test('can pass `headers` into `fetchBaseQuery`', async () => {
Expand Down