Skip to content

Commit

Permalink
feat: dynamic headers (#341)
Browse files Browse the repository at this point in the history
  • Loading branch information
sethidden committed Apr 23, 2022
1 parent 80efbfd commit 016a15c
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 5 deletions.
26 changes: 26 additions & 0 deletions README.md
Expand Up @@ -19,6 +19,7 @@ Minimal GraphQL client supporting Node and browsers for scripts or simple apps
- [Authentication via HTTP header](#authentication-via-http-header)
- [Incrementally setting headers](#incrementally-setting-headers)
- [Passing Headers in each request](#passing-headers-in-each-request)
- [Passing dynamic headers to the client](#passing-dynamic-headers-to-the-client)
- [Passing more options to `fetch`](#passing-more-options-to-fetch)
- [Custom JSON serializer](#custom-json-serializer)
- [Using GraphQL Document variables](#using-graphql-document-variables)
Expand Down Expand Up @@ -214,6 +215,31 @@ const requestHeaders = {
const data = await client.request(query, variables, requestHeaders)
```

#### Passing dynamic headers to the client

It's possible to recalculate the global client headers dynamically before each request.
To do that, pass a function that returns the headers to the `headers` property when creating a new `GraphQLClient`.

```js
import { GraphQLClient } from 'graphql-request'

const client = new GraphQLClient(endpoint,
{
headers: () => ({ 'X-Sent-At-Time': Date.now() })
}
)

const query = gql`
query getCars {
cars {
name
}
}
// Function saved in the client runs and calculates fresh headers before each request
const data = await client.request(query)
```

### Passing more options to `fetch`

```js
Expand Down
16 changes: 11 additions & 5 deletions src/index.ts
Expand Up @@ -24,6 +24,8 @@ import {
RawRequestExtendedOptions,
RequestExtendedOptions,
Variables,
PatchedRequestInit,
MaybeFunction,
} from './types'
import * as Dom from './types.dom'

Expand Down Expand Up @@ -190,9 +192,9 @@ const get = async <V = Variables>({
*/
export class GraphQLClient {
private url: string
private options: Dom.RequestInit
private options: PatchedRequestInit

constructor(url: string, options?: Dom.RequestInit) {
constructor(url: string, options?: PatchedRequestInit) {
this.url = url
this.options = options || {}
}
Expand Down Expand Up @@ -228,7 +230,7 @@ export class GraphQLClient {
query: rawRequestOptions.query,
variables: rawRequestOptions.variables,
headers: {
...resolveHeaders(headers),
...resolveHeaders(callOrIdentity(headers)),
...resolveHeaders(rawRequestOptions.requestHeaders),
},
operationName,
Expand Down Expand Up @@ -267,7 +269,7 @@ export class GraphQLClient {
query,
variables: requestOptions.variables,
headers: {
...resolveHeaders(headers),
...resolveHeaders(callOrIdentity(headers)),
...resolveHeaders(requestOptions.requestHeaders),
},
operationName,
Expand Down Expand Up @@ -309,7 +311,7 @@ export class GraphQLClient {
query: queries,
variables,
headers: {
...resolveHeaders(headers),
...resolveHeaders(callOrIdentity(headers)),
...resolveHeaders(batchRequestOptions.requestHeaders),
},
operationName: undefined,
Expand Down Expand Up @@ -592,6 +594,10 @@ function resolveRequestDocument(document: RequestDocument): { query: string; ope
return { query: print(document), operationName }
}

function callOrIdentity<T>(value: MaybeFunction<T>) {
return typeof value === 'function' ? (value as () => T)() : value;
}

/**
* Convenience passthrough template tag to get the benefits of tooling for the gql template tag. This does not actually parse the input into a GraphQL DocumentNode like graphql-tag package does. It just returns the string with any variables given interpolated. Can save you a bit of performance and having to install another package.
*
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Expand Up @@ -55,8 +55,13 @@ export class ClientError extends Error {
}
}

export type MaybeFunction<T> = T | (() => T);

export type RequestDocument = string | DocumentNode

export type PatchedRequestInit = Omit<Dom.RequestInit, "headers">
& {headers?: MaybeFunction<Dom.RequestInit['headers']>};

export type BatchRequestDocument<V = Variables> = {
document: RequestDocument
variables?: V
Expand Down
20 changes: 20 additions & 0 deletions tests/headers.test.ts
Expand Up @@ -92,6 +92,26 @@ describe('using class', () => {
});

})

describe('gets fresh dynamic headers before each request', () => {
test('with request method', async () => {
const objectChangedThroughReference = { 'x-foo': 'old' }
const client = new GraphQLClient(ctx.url, { headers: () => objectChangedThroughReference });
objectChangedThroughReference['x-foo'] = 'new';
const mock = ctx.res()
await client.request(`{ me { id } }`);
expect(mock.requests[0].headers['x-foo']).toEqual('new')
})

test('with rawRequest method', async () => {
const objectChangedThroughReference = { 'x-foo': 'old' }
const client = new GraphQLClient(ctx.url, { headers: () => objectChangedThroughReference });
objectChangedThroughReference['x-foo'] = 'new';
const mock = ctx.res()
await client.rawRequest(`{ me { id } }`);
expect(mock.requests[0].headers['x-foo']).toEqual('new')
})
})
})
})

Expand Down

0 comments on commit 016a15c

Please sign in to comment.