-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCustomApolloProvider.tsx
68 lines (56 loc) · 1.68 KB
/
CustomApolloProvider.tsx
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
'use client';
import { ReactNode } from 'react';
import {
ApolloClient,
ApolloNextAppProvider,
InMemoryCache,
SSRMultipartLink,
} from '@apollo/experimental-nextjs-app-support';
import { getCookie } from 'cookies-next/client';
import { ApolloLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import createUploadLink from 'apollo-upload-client/createUploadLink.mjs';
import { GRAPHQL_ENDPOINT } from '~/constants/apiRelated';
const defaultHeader = {
'Content-Type': 'application/json',
};
const makeClient = () => {
const authLink = setContext(async (_, { headers }) => {
const token = getCookie('token');
return {
headers: {
...headers,
...defaultHeader,
...(token && { Authorization: `Bearer ${token}` }),
},
};
});
const httpLink = createUploadLink({
uri: GRAPHQL_ENDPOINT,
});
const errorLink = onError(({ graphQLErrors }) => {
if (graphQLErrors) {
const unauthorized = graphQLErrors.some(({ message }) => message === 'Unauthorized');
if (unauthorized) {
// Do something
}
}
});
const linkList = ApolloLink.from([authLink, errorLink, httpLink]);
return new ApolloClient({
cache: new InMemoryCache(),
link:
typeof window === 'undefined'
? ApolloLink.from([
new SSRMultipartLink({
stripDefer: true,
}),
linkList,
])
: linkList,
});
};
export const CustomApolloProvider = ({ children }: { children: ReactNode }) => {
return <ApolloNextAppProvider makeClient={makeClient}>{children}</ApolloNextAppProvider>;
};