Skip to content

Commit

Permalink
fix: do not overwrite user-provided Content-Type header (#614)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonkoops authored Nov 2, 2023
1 parent c838ea7 commit dbd7c7f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,14 @@ const createHttpMethodFetcher =
async <V extends Variables>(params: RequestVerbParams<V>) => {
const { url, query, variables, operationName, fetch, fetchOptions, middleware } = params

const headers = { ...params.headers }
const headers = new Headers(params.headers as HeadersInit)
let queryParams = ``
let body = undefined

if (method === `POST`) {
body = createRequestBody(query, variables, operationName, fetchOptions.jsonSerializer)
if (typeof body === `string`) {
// @ts-expect-error todo
headers[`Content-Type`] = `application/json`
if (typeof body === `string` && !headers.has(`Content-Type`)) {
headers.set(`Content-Type`, `application/json`)
}
} else {
// @ts-expect-error todo needs ADT for TS to understand the different states
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ type RequestExtendedInit<V extends Variables = Variables> = RequestInit & {
variables?: V
}

// TODO: Replace this type with the built-in `HeadersInit` type.
// See: https://github.com/jasonkuhrt/graphql-request/issues/608
export type GraphQLClientRequestHeaders = Headers | string[][] | Record<string, string>

// prettier-ignore
Expand Down
18 changes: 18 additions & 0 deletions tests/headers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,24 @@ describe(`using class`, () => {
expect(mock.requests[0]?.headers[`x-foo`]).toEqual(`new`)
})
})

describe(`allows content-type header to be overwritten`, () => {
test(`with request method`, async () => {
const headers = new Headers({ 'content-type': `text/plain` })
const client = new GraphQLClient(ctx.url, { headers })
const mock = ctx.res()
await client.request(`{ me { id } }`)
expect(mock.requests[0]?.headers[`content-type`]).toEqual(`text/plain`)
})

test(`with rawRequest method`, async () => {
const headers = new Headers({ 'content-type': `text/plain` })
const client = new GraphQLClient(ctx.url, { headers })
const mock = ctx.res()
await client.rawRequest(`{ me { id } }`)
expect(mock.requests[0]?.headers[`content-type`]).toEqual(`text/plain`)
})
})
})
})

Expand Down

0 comments on commit dbd7c7f

Please sign in to comment.