-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.ts
116 lines (106 loc) · 2.87 KB
/
client.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import { LocalStore } from '@/lib/storage';
import {
ApolloClient,
InMemoryCache,
HttpLink,
ApolloLink,
concat,
from,
split,
} from '@apollo/client';
import { onError } from '@apollo/client/link/error';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { getMainDefinition } from '@apollo/client/utilities';
// HTTP Link
const httpLink = new HttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
},
});
// WebSocket Link
const wsLink = new GraphQLWsLink(
createClient({
url: process.env.NEXT_PUBLIC_GRAPHQL_URL?.replace('http', 'ws') || '',
connectionParams: () => {
if (typeof window === 'undefined') return {};
const token = localStorage.getItem(LocalStore.accessToken);
return {
Authorization: token ? `Bearer ${token}` : '',
};
},
on: {
connected: () => console.log('WebSocket Connected'),
error: (err) => console.error('WebSocket Error:', err),
closed: () => console.log('WebSocket Closed'),
},
})
);
// Logging Middleware
const requestLoggingMiddleware = new ApolloLink((operation, forward) => {
console.log('GraphQL Request:', {
operationName: operation.operationName,
variables: operation.variables,
query: operation.query.loc?.source.body,
});
return forward(operation).map((response) => {
console.log('GraphQL Response:', response.data);
return response;
});
});
// Auth Middleware
const authMiddleware = new ApolloLink((operation, forward) => {
if (typeof window === 'undefined') {
return forward(operation);
}
const token = localStorage.getItem(LocalStore.accessToken);
if (token) {
operation.setContext({
headers: {
Authorization: `Bearer ${token}`,
},
});
}
return forward(operation);
});
// Error Link
const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) => {
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
});
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
// Split traffic based on operation type
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
from([errorLink, requestLoggingMiddleware, authMiddleware, httpLink])
);
// Create Apollo Client
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
},
query: {
fetchPolicy: 'no-cache',
},
},
});
export default client;