-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapollo.js
47 lines (38 loc) · 1.18 KB
/
apollo.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
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { setContext } from "apollo-link-context";
import { ApolloLink } from "apollo-link";
import { createUploadLink } from "apollo-upload-client";
const httpLink = createUploadLink({
uri: `${process.env.REACT_APP_SERVER_URL}/graphql`
});
const middlewareLink = setContext(() => ({
headers: {
"x-token": localStorage.getItem("token"),
"x-refresh-token": localStorage.getItem("refreshToken")
}
}));
const afterwareLink = new ApolloLink((operation, forward) =>
forward(operation).map(response => {
const {
response: { headers }
} = operation.getContext();
if (headers) {
const token = headers.get("x-token");
const refreshToken = headers.get("x-refresh-token");
if (token) {
localStorage.setItem("token", token);
}
if (refreshToken) {
localStorage.setItem("refreshToken", refreshToken);
}
}
return response;
})
);
const link = afterwareLink.concat(middlewareLink.concat(httpLink));
export default new ApolloClient({
link,
ssrMode: true,
cache: new InMemoryCache().restore(window.__APOLLO_STATE__)
});