-
Notifications
You must be signed in to change notification settings - Fork 5
/
initApollo.ts
84 lines (70 loc) · 2.29 KB
/
initApollo.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
import {
ApolloClient,
ApolloLink,
InMemoryCache,
NormalizedCacheObject
} from "apollo-boost";
import { setContext } from "apollo-link-context";
import { onError } from "apollo-link-error";
import { createHttpLink } from "apollo-link-http";
import fetch from "isomorphic-unfetch";
import Router from "next/router";
let apolloClient: ApolloClient<NormalizedCacheObject> | null = null;
export const isBrowser: boolean = (process as any).browser;
// Polyfill fetch() on the server (used by apollo-client)
if (!isBrowser) {
(global as any).fetch = fetch;
}
interface IOptions {
getToken: () => string;
}
function create(initialState: any, { getToken }: IOptions) {
const httpLink = createHttpLink({
uri: "http://localhost:4000/graphql",
credentials: "include"
});
const authLink = setContext((_, { headers }) => {
const token = getToken();
return {
headers: {
...headers,
cookie: token ? `qid=${token}` : ""
}
};
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) => {
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
if (isBrowser && message.includes("not authenticated")) {
Router.replace("/login");
}
});
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
});
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
return new ApolloClient({
connectToDevTools: isBrowser,
ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
// link: authLink.concat(httpLink),
link: ApolloLink.from([errorLink, authLink, httpLink]), // Composing Links
cache: new InMemoryCache().restore(initialState || {})
});
}
export default function initApollo(initialState: any, options: IOptions) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (!isBrowser) {
return create(initialState, options);
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = create(initialState, options);
}
return apolloClient;
}