Skip to content

Commit

Permalink
feat: export middleware function types
Browse files Browse the repository at this point in the history
There are now types exported that you can use to type middleware
functions that are defined apart from their use. Example:

```ts
const requestMiddleware: RequestMiddleware = async (request) => {
  return {
    ...request,
    headers: {
      ...request.headers,
      'x-auth-token': await getAccessToken(),
    },
  }
}

const _client = new GraphQLClient(endpoint, { requestMiddleware })
```
  • Loading branch information
jasonkuhrt committed Apr 16, 2023
1 parent 6b3396b commit 81c8bb2
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 14 deletions.
17 changes: 8 additions & 9 deletions examples/other-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/* eslint-disable */

/**
* It's possible to use a middleware to pre-process any request or handle raw response.
*/

import { GraphQLClient } from '../src/index.js'
import type { RequestMiddleware } from '../src/types.js'
import type { RequestMiddleware, ResponseMiddleware } from '../src/types.js'

const endpoint = `https://api.spacex.land/graphql/`

Expand All @@ -17,10 +15,12 @@ const getAccessToken = () => Promise.resolve(`some special token here`)
*/

const requestMiddleware: RequestMiddleware = async (request) => {
const token = await getAccessToken()
return {
...request,
headers: { ...request.headers, 'x-auth-token': token },
headers: {
...request.headers,
'x-auth-token': await getAccessToken(),
},
}
}

Expand All @@ -46,14 +46,13 @@ const getAccessToken = () => Promise.resolve(`some special token here`)
* Response middleware example (log request trace id if error caused):
*/

// @ts-expect-error TODO export a response middleware type
const responseMiddleware = (response: Response<unknown>) => {
if (response.errors) {
const responseMiddleware: ResponseMiddleware = (response) => {
if (!(response instanceof Error) && response.errors) {
const traceId = response.headers.get(`x-b3-trace-id`) || `unknown`
console.error(
`[${traceId}] Request error:
status ${response.status}
details: ${response.errors}`
details: ${response.errors.map((_) => _.message).join(`, `)}`
)
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from './parseArgs.js'
import { resolveRequestDocument } from './resolveRequestDocument.js'
import type {
BatchRequestDocument,
FetchOptions,
GraphQLClientRequestHeaders,
GraphQLClientResponse,
Expand All @@ -17,10 +18,10 @@ import type {
MaybeLazy,
RequestConfig,
RequestMiddleware,
ResponseMiddleware,
VariablesAndRequestHeadersArgs,
} from './types.js'
import {
BatchRequestDocument,
BatchRequestsExtendedOptions,
BatchRequestsOptions,
ClientError,
Expand All @@ -43,7 +44,9 @@ export {
RawRequestOptions,
RequestDocument,
RequestExtendedOptions,
RequestMiddleware,
RequestOptions,
ResponseMiddleware,
Variables,
}

Expand Down
9 changes: 5 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export interface RequestConfig extends Omit<RequestInit, 'headers' | 'method'>,
method?: HTTPMethodInput
headers?: MaybeLazy<GraphQLClientRequestHeaders>
requestMiddleware?: RequestMiddleware
responseMiddleware?: (response: GraphQLClientResponse<unknown> | Error) => void
responseMiddleware?: ResponseMiddleware
jsonSerializer?: JsonSerializer
}

Expand Down Expand Up @@ -144,9 +144,10 @@ export interface BatchRequestsExtendedOptions<V extends Variables = Variables>
url: string
}

export type RequestMiddleware<V extends Variables = Variables> = (
request: RequestExtendedInit<V>
) => RequestExtendedInit | Promise<RequestExtendedInit>
export type ResponseMiddleware = (response: GraphQLClientResponse<unknown> | Error) => void

// prettier-ignore
export type RequestMiddleware<V extends Variables = Variables> = (request: RequestExtendedInit<V>) => RequestExtendedInit | Promise<RequestExtendedInit>

type RequestExtendedInit<V extends Variables = Variables> = RequestInit & {
url: string
Expand Down
2 changes: 2 additions & 0 deletions tests/exports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* eslint-disable */
import { RequestMiddleware, ResponseMiddleware } from '../src/index.js'

0 comments on commit 81c8bb2

Please sign in to comment.