diff --git a/src/index.ts b/src/index.ts index bceaec67..99944bc4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,9 +16,7 @@ export class GraphQLClient { constructor(url: string, options?: Options) { this.url = url - this.options = { - headers: (options && options.headers) ? options.headers : {}, - } + this.options = options || {}; } async request(query: string, variables?: Variables): Promise { @@ -29,6 +27,7 @@ export class GraphQLClient { const response = await fetch(this.url, { method: 'POST', + ...this.options, headers: Object.assign({'Content-Type': 'application/json'}, this.options.headers), body, }) diff --git a/src/types.ts b/src/types.ts index 318cdc80..4b2e1c3e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,15 @@ export type Variables = { [key: string]: any } export interface Options { + method?: RequestInit['method'] headers?: { [key: string]: string } + mode?: RequestInit['mode'] + credentials?: RequestInit['credentials'] + cache?: RequestInit['cache'] + redirect?: RequestInit['redirect'] + referrer?: RequestInit['referrer'] + referrerPolicy?: RequestInit['referrerPolicy'] + integrity?: RequestInit['integrity'] } export interface GraphQLError { @@ -46,4 +54,3 @@ export class ClientError extends Error { } } } - diff --git a/tests/index.test.ts b/tests/index.test.ts index af903132..be75f402 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,6 +1,7 @@ import test from 'ava' import * as fetchMock from 'fetch-mock' -import { ClientError, request } from '../src/index' +import { ClientError, request, GraphQLClient } from '../src/index' +import { Options } from '../src/types' test('minimal query', async (t) => { const data = { @@ -46,6 +47,26 @@ test('content-type with charset', async (t) => { }) }) + +test('extra fetch options', async (t) => { + const options:Options = { + credentials: 'include', + mode: 'cors', + cache: 'reload', + } + + const client = new GraphQLClient('https://mock-api.com/graphql', options) + await mock({ + body: { data: {test: 'test'} } + }, async () => { + await client.request('{ test }') + const actualOptions = fetchMock.lastCall()[1] + for (let name in options) { + t.deepEqual(actualOptions[name], options[name]); + } + }) +}) + async function mock(response: any, testFn: () => Promise) { fetchMock.mock({ matcher: '*',