|
1 |
| -import { getToken } from "@/helpers"; |
2 |
| -import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client"; |
| 1 | +import { |
| 2 | + ApolloClient, |
| 3 | + ApolloProvider, |
| 4 | + HttpLink, |
| 5 | + InMemoryCache, |
| 6 | +} from "@apollo/client"; |
| 7 | +import { onError } from "@apollo/client/link/error"; |
| 8 | +import { setContext } from "@apollo/client/link/context"; |
| 9 | +import { RetryLink } from "@apollo/client/link/retry"; |
3 | 10 | import { PropsWithChildren } from "react";
|
| 11 | +import Storage from "@/apis/storage"; |
| 12 | +import { TOKEN } from "@/constants"; |
| 13 | +import { refresh } from "@/apis/token"; |
4 | 14 |
|
5 |
| -const client = new ApolloClient({ |
| 15 | +const authLink = setContext((_, { headers }) => { |
| 16 | + const token = Storage.getItem(TOKEN.ACCESS); |
| 17 | + return { |
| 18 | + headers: { |
| 19 | + ...headers, |
| 20 | + authorization: token ? `Bearer ${token}` : "", |
| 21 | + }, |
| 22 | + }; |
| 23 | +}); |
| 24 | + |
| 25 | +const errorLink = onError(({ operation, forward }) => { |
| 26 | + refresh().then(() => forward(operation)); |
| 27 | +}); |
| 28 | + |
| 29 | +const httpLink = new HttpLink({ |
6 | 30 | uri: `${process.env.NEXT_PUBLIC_BASE_URL}api/graphql`,
|
| 31 | +}); |
| 32 | + |
| 33 | +const retryLink = new RetryLink({ |
| 34 | + delay: { |
| 35 | + initial: 300, |
| 36 | + max: Infinity, |
| 37 | + jitter: true, |
| 38 | + }, |
| 39 | + attempts: { |
| 40 | + max: 2, |
| 41 | + retryIf: (error) => !!error, |
| 42 | + }, |
| 43 | +}); |
| 44 | + |
| 45 | +const client = new ApolloClient({ |
| 46 | + link: retryLink.concat(errorLink).concat(authLink).concat(httpLink), |
7 | 47 | headers: {
|
8 |
| - Authorization: getToken(), |
| 48 | + Authorization: Storage.getItem(TOKEN.ACCESS) ?? "", |
9 | 49 | },
|
10 | 50 | cache: new InMemoryCache(),
|
11 | 51 | connectToDevTools: true,
|
|
0 commit comments