-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathapolloClient.js
48 lines (41 loc) · 1.25 KB
/
apolloClient.js
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
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloLink } from 'apollo-client-preset';
import persist from './persist';
let apolloClient = null;
const httpLink = createHttpLink({
uri: 'https://api.graph.cool/simple/v1/cj7ke77fv0e9i0122pflagbvx',
credentials: 'include'
});
function createClient(headers, token, initialState) {
let accessToken = token;
(async () => {
// eslint-disable-next-line no-param-reassign
accessToken = token || (await persist.willGetAccessToken());
})();
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
authorization: accessToken
}
});
return forward(operation);
}).concat(httpLink);
return new ApolloClient({
headers,
link: authLink,
connectToDevTools: process.browser,
ssrMode: !process.browser,
cache: new InMemoryCache().restore(initialState || {})
});
}
export default (headers, token, initialState) => {
if (!process.browser) {
return createClient(headers, token, initialState);
}
if (!apolloClient) {
apolloClient = createClient(headers, token, initialState);
}
return apolloClient;
};