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

Add isJsonContentType predicate to fetchBaseQuery #2331

Merged
merged 3 commits into from
Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 16 additions & 2 deletions packages/toolkit/src/query/fetchBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ const defaultFetchFn: typeof fetch = (...args) => fetch(...args)
const defaultValidateStatus = (response: Response) =>
response.status >= 200 && response.status <= 299

const isJsonContentType = (headers: Headers) =>
headers.get('content-type')?.trim()?.startsWith('application/json')
const defaultIsJsonContentType = (headers: Headers) =>
!!headers.get('content-type')?.trim()?.startsWith('application/json')
phryneas marked this conversation as resolved.
Show resolved Hide resolved

const handleResponse = async (
response: Response,
Expand Down Expand Up @@ -123,6 +123,15 @@ export type FetchBaseQueryArgs = {
init?: RequestInit | undefined
) => Promise<Response>
paramsSerializer?: (params: Record<string, any>) => string
/**
* By default, we only check for 'application/json' as the content-type for json. If you need to support another format, you can pass
phryneas marked this conversation as resolved.
Show resolved Hide resolved
* in a predicate function for your given api to get the same automatic stringifying behavior
* @example
* ```ts
* const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json"].includes(headers.get("content-type")?.trim());
phryneas marked this conversation as resolved.
Show resolved Hide resolved
* ```
*/
isJsonContentType?: (headers: Headers) => boolean
} & RequestInit

export type FetchBaseQueryMeta = { request: Request; response?: Response }
Expand Down Expand Up @@ -162,12 +171,17 @@ export type FetchBaseQueryMeta = { request: Request; response?: Response }
*
* @param {(params: Record<string, unknown>) => string} paramsSerializer
* An optional function that can be used to stringify querystring parameters.
*
* @param {(headers: Headers) => boolean} isJsonContentType
* An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`

*/
export function fetchBaseQuery({
baseUrl,
prepareHeaders = (x) => x,
fetchFn = defaultFetchFn,
paramsSerializer,
isJsonContentType = defaultIsJsonContentType,
...baseFetchOptions
}: FetchBaseQueryArgs = {}): BaseQueryFn<
string | FetchArgs,
Expand Down
28 changes: 28 additions & 0 deletions packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,34 @@ describe('fetchBaseQuery', () => {
`${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c`
)
})

it('should supports a custom isJsonContentType function', async () => {
const testBody = {
i_should_be_stringified: true,
}
const baseQuery = fetchBaseQuery({
baseUrl,
fetchFn: fetchFn as any,
isJsonContentType: (headers) =>
['application/vnd.api+json', 'application/json'].includes(
phryneas marked this conversation as resolved.
Show resolved Hide resolved
headers.get('content-type') ?? ''
),
})

let request: any
;({ data: request } = await baseQuery(
{
url: '/echo',
method: 'POST',
body: testBody,
headers: { 'content-type': 'application/vnd.api+json' },
phryneas marked this conversation as resolved.
Show resolved Hide resolved
},
commonBaseQueryApi,
{}
))

expect(request.body).toMatchObject(testBody)
})
})

describe('validateStatus', () => {
Expand Down