forked from graffle-js/graffle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
other-middleware.ts
61 lines (51 loc) · 1.64 KB
/
other-middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* 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, ResponseMiddleware } from '../src/types.js'
const endpoint = `https://api.spacex.land/graphql/`
const getAccessToken = () => Promise.resolve(`some special token here`)
{
/**
* Request middleware example (set actual auth token to each request):
*/
const requestMiddleware: RequestMiddleware = async (request) => {
return {
...request,
headers: {
...request.headers,
'x-auth-token': await getAccessToken(),
},
}
}
const _client = new GraphQLClient(endpoint, { requestMiddleware })
}
{
/**
* It's also possible to use an async function as a request middleware. The resolved data will be passed to the request:
*/
const requestMiddleware: RequestMiddleware = async (request) => {
const token = await getAccessToken()
return {
...request,
headers: { ...request.headers, 'x-auth-token': token },
}
}
const _client = new GraphQLClient(endpoint, { requestMiddleware })
}
{
/**
* Response middleware example (log request trace id if error caused):
*/
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.map((_) => _.message).join(`, `)}`
)
}
}
const _client = new GraphQLClient(endpoint, { responseMiddleware })
}