Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix: send headers from .setHeaders to server #202

Merged
merged 1 commit into from
Sep 4, 2020
Merged
Changes from all commits
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
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