Skip to content

Commit

Permalink
feat: Allow passing more options to fetch
Browse files Browse the repository at this point in the history
issue #6
  • Loading branch information
RomanHotsiy committed Jul 14, 2017
1 parent fcb4673 commit 329238e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
5 changes: 2 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends any>(query: string, variables?: Variables): Promise<T> {
Expand All @@ -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,
})
Expand Down
9 changes: 8 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -46,4 +54,3 @@ export class ClientError extends Error {
}
}
}

23 changes: 22 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -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<void>) {
fetchMock.mock({
matcher: '*',
Expand Down

0 comments on commit 329238e

Please sign in to comment.