Skip to content

Commit

Permalink
fix: send headers from .setHeaders to server (#202)
Browse files Browse the repository at this point in the history
closes #203
  • Loading branch information
vecerek authored Sep 4, 2020
1 parent 10c23fa commit e666f69
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ import { Headers, RequestInit, Response } from './types.dom'

export { ClientError } from './types'

const transformHeaders = (headers: RequestInit["headers"]): Record<string, string> => {
let oHeaders: Record<string, string> = {};
if (headers) {
if (headers instanceof Headers) {
headers.forEach((v, k) => { oHeaders[k] = v })
} else if (headers instanceof Array) {
headers.forEach(([k, v]) => { oHeaders[k] = v })
} else {
oHeaders = headers as Record<string, string>
}
}

return oHeaders
};

/**
* todo
*/
Expand All @@ -24,14 +39,14 @@ export class GraphQLClient {
variables?: V
): Promise<{ data?: T; extensions?: any; headers: Headers; status: number; errors?: GraphQLError[] }> {
const { headers, ...others } = this.options

const oHeaders = transformHeaders(headers)
const body = createRequestBody(query, variables)

const response = await fetch(this.url, {
method: 'POST',
headers: {
...(typeof body === 'string' ? { 'Content-Type': 'application/json' } : {}),
...headers,
...oHeaders,
},
body,
...others,
Expand All @@ -56,6 +71,7 @@ export class GraphQLClient {
*/
async request<T = any, V = Variables>(document: RequestDocument, variables?: V): Promise<T> {
const { headers, ...others } = this.options
const oHeaders = transformHeaders(headers)
const resolvedDoc = resolveRequestDocument(document)

const body = createRequestBody(resolvedDoc, variables)
Expand All @@ -64,7 +80,7 @@ export class GraphQLClient {
method: 'POST',
headers: {
...(typeof body === 'string' ? { 'Content-Type': 'application/json' } : {}),
...headers,
...oHeaders,
},
body,
...others,
Expand All @@ -80,7 +96,7 @@ export class GraphQLClient {
}
}

setHeaders(headers: Response['headers']): GraphQLClient {
setHeaders(headers: RequestInit['headers']): GraphQLClient {
this.options.headers = headers
return this
}
Expand Down

0 comments on commit e666f69

Please # to comment.