-
Notifications
You must be signed in to change notification settings - Fork 0
/
apollo.ts
172 lines (146 loc) · 4.82 KB
/
apollo.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
} from '@apollo/client/core';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloLink, from, split, Operation, NextLink } from '@apollo/client/link/core';
import { ErrorResponse, onError } from '@apollo/client/link/error';
import { RetryLink } from '@apollo/client/link/retry';
import { HttpLink } from '@apollo/client/link/http';
import { GraphQLError } from 'graphql/error/GraphQLError';
import { FragmentDefinitionNode, OperationDefinitionNode } from 'graphql';
import { makeVar } from '@apollo/client';
export const clerkToken = makeVar<string | null>(null);
// obtain the host name
const hostName = window.location.hostname;
let routeUrl = `http://${hostName}:4000/graphql`;
let wsUrl = `ws://${hostName}:4000/subscriptions`;
if (process.env.REACT_APP_GQL_URL) {
routeUrl = process.env.REACT_APP_GQL_URL;
}
if (process.env.REACT_APP_GQL_WS_URL) {
wsUrl = process.env.REACT_APP_GQL_WS_URL;
}
console.log('routeUrl', routeUrl);
console.log('wsUrl', wsUrl);
// export the client as a window object if it does not exist
interface customWindow extends Window {
'apollo-client': ApolloClient<NormalizedCacheObject>;
}
declare const window: customWindow;
// create a web socket link
const wsLink = new GraphQLWsLink(
createClient({
url: wsUrl,
connectionParams: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
credentials: true,
// authorization: clerkToken() ? `Bearer ${clerkToken()}` : null,
},
on: {
connected: () => console.log('GraphQLWsLink connected'),
closed: () => console.log('GraphQLWsLink closed'),
}
}),
);
// create a httpLink
const httpLink: HttpLink = new HttpLink({
uri: routeUrl,
});
// create an auth link
const authLink = new ApolloLink((operation: Operation, forward: NextLink) => {
const token = clerkToken();
console.log('[authLink] token', (token) ? token.substring(0, 10) : 'no token ');
// add the authorization to the headers
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : null,
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
credentials: true
}
});
return forward(operation);
});
// create error link
const errorLink: ApolloLink = onError(({ graphQLErrors, networkError }: ErrorResponse) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }: GraphQLError) => console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
));
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
// Prevent ApolloClient from retrying infinitely on failures
// Doc: https://www.apollographql.com/docs/link/links/retry/
const retryLink = new RetryLink({
delay: {
initial: 300,
max: 20000,
jitter: true,
},
attempts: {
max: 3,
retryIf: error => !!error,
},
});
const opsLink: ApolloLink = from([errorLink, retryLink, authLink, httpLink]);
const terminatingLink: ApolloLink = split(
({ query }: Operation) => {
const mainDefinition: OperationDefinitionNode | FragmentDefinitionNode = getMainDefinition(query);
return (
mainDefinition.kind === 'OperationDefinition' && mainDefinition.operation === 'subscription'
);
},
wsLink,
opsLink
);
let clientInstance: ApolloClient<NormalizedCacheObject>;
if (!window['apollo-client']) {
const newClient = new ApolloClient({
name: 'react-web-client',
link: terminatingLink,
cache: new InMemoryCache(),
defaultOptions: {
// See https://www.apollographql.com/docs/react/data/queries#setting-a-fetch-policy
watchQuery: {
fetchPolicy: 'cache-first',
nextFetchPolicy: 'cache-and-network'
},
query: {
fetchPolicy: 'cache-first',
errorPolicy: 'all',
},
}
});
window['apollo-client'] = newClient;
clientInstance = newClient;
}
else
clientInstance = window['apollo-client'];
export const client: ApolloClient<NormalizedCacheObject> = clientInstance;
// import { createClient, ClientOptions, Client } from 'graphql-sse';
// SSE class for subscriptions
// class SSELink extends ApolloLink {
// private client: Client;
// constructor(options: ClientOptions) {
// super();
// this.client = createClient(options);
// }
// public request(operation: Operation): Observable<FetchResult> {
// return new Observable((sink) => {
// return this.client.subscribe<FetchResult>(
// { ...operation, query: print(operation.query) },
// {
// next: sink.next.bind(sink),
// complete: sink.complete.bind(sink),
// error: sink.error.bind(sink),
// },
// );
// });
// }
// }