-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapollo-client.ts
59 lines (53 loc) · 1.38 KB
/
apollo-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
import {
ApolloClient,
InMemoryCache,
HttpLink,
ApolloLink,
concat,
split,
} from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { getMainDefinition } from "@apollo/client/utilities";
import { createClient } from "graphql-ws";
const httpLink = new HttpLink({ uri: process.env.httpsUri });
const wsLink =
typeof window !== "undefined"
? new GraphQLWsLink(
createClient({
url: process.env.wsUri as string,
})
)
: null;
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
if (typeof window !== "undefined") {
const token = localStorage.getItem("jwtToken");
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
Authorization: token ? `Bearer ${token}` : null,
},
}));
}
return forward(operation);
});
const splitLink =
typeof window !== "undefined" && wsLink != null
? split(
({ query }) => {
const def = getMainDefinition(query);
return (
def.kind === "OperationDefinition" &&
def.operation === "subscription"
);
},
wsLink,
httpLink
)
: httpLink;
const client = new ApolloClient({
ssrMode: true,
cache: new InMemoryCache(),
link: concat(authMiddleware, splitLink),
});
export default client;