This repository was archived by the owner on Feb 25, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapollo-link.ts
More file actions
76 lines (65 loc) · 2.13 KB
/
apollo-link.ts
File metadata and controls
76 lines (65 loc) · 2.13 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { ApolloLink, HttpLink } from '@apollo/client';
import { ErrorLink } from '@apollo/client/link/error';
import {
CombinedGraphQLErrors,
CombinedProtocolErrors,
} from "@apollo/client/errors";
import { log, logError, LogContext } from '@/lib/log';
import { map } from 'rxjs';
const uri = process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT;
export default function getApolloLink ( requestContext: LogContext = {} ) {
// If endpoint is undefined, throw for visibility.
if ( 'undefined' === typeof uri ) {
throw new Error( 'GraphQL endpoint is undefined' );
}
return ApolloLink.from( [
// Error link to log GraphQL errors.
new ErrorLink( ( { error } ) => {
if ( CombinedGraphQLErrors.is(error)) {
error.errors.forEach( err => {
const { locations, path } = err;
const context = {
locations: JSON.stringify( locations ),
path: JSON.stringify( path ),
};
logError( err, context, requestContext );
} )
} else if ( CombinedProtocolErrors.is(error)) {
logError( error, {}, requestContext );
}
} ),
// Custom ApolloLink to log successful queries for debugging.
new ApolloLink( ( operation, forward ) => {
const { operationName, setContext, variables } = operation;
const debug = {
operationName,
variables: JSON.stringify( variables ),
};
const startTime = Date.now();
setContext( ( { headers = {} } ) => ( {
headers: {
...headers,
// Here is where you can set custom request headers for your GraphQL
// requests. If the request is client-side, it must be allowed by the
// CORS policy in WPGraphQL.
},
} ) );
return forward( operation )
.pipe(
map( data => {
const response = operation.getContext().response;
const context = {
...debug,
cacheStatus: response?.headers?.get( 'x-cache' ),
cacheAge: response?.headers?.get( 'age' ),
payloadSize: response?.body?.bytesWritten,
requestDurationInMs: Date.now() - startTime,
};
log( 'GraphQL request', context, requestContext );
return data;
} ) );
} ),
// Standard HttpLink to connect to GraphQL.
new HttpLink( { uri } ),
] );
}