ApolloProvider.js
1.16 KB
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
import React from "react";
import App from "./App";
import ApolloClient from "apollo-client";
import { ApolloProvider } from "@apollo/react-hooks";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { setContext } from "apollo-link-context";
import { onError } from "apollo-link-error";
const httpLink = createHttpLink({ uri: "http://localhost:5001" });
const authLink = setContext(() => {
const token = localStorage.getItem("jwtToken");
return {
headers: {
Authorization: token ? `Bearer ${token}` : ""
}
};
});
const errorLink = onError(({ graphQLErrors, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case "UNAUTHENTICATED":
window.location.href = "/login";
// retry the request, returning the new observable
return forward(operation);
}
}
}
});
const link = errorLink.concat(authLink);
const client = new ApolloClient({
link: link.concat(httpLink),
cache: new InMemoryCache()
});
export default (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);