-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCustomApolloProvider.tsx
More file actions
68 lines (56 loc) · 1.72 KB
/
Copy pathCustomApolloProvider.tsx
File metadata and controls
68 lines (56 loc) · 1.72 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
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/client-integration-nextjs';
import { getCookie } from 'cookies-next/client';
import { ApolloLink, CombinedGraphQLErrors } from '@apollo/client';
import { SetContextLink } from '@apollo/client/link/context';
import { ErrorLink } from '@apollo/client/link/error';
import UploadHttpLink from 'apollo-upload-client/UploadHttpLink.mjs';
import { GRAPHQL_ENDPOINT } from '~/constants/apiRelated';
const defaultHeader = {
'Content-Type': 'application/json',
};
const makeClient = () => {
const authLink = new SetContextLink(async ({ headers }) => {
const token = getCookie('token');
return {
headers: {
...headers,
...defaultHeader,
...(token && { Authorization: `Bearer ${token}` }),
},
};
});
const httpLink = new UploadHttpLink({
uri: GRAPHQL_ENDPOINT,
});
const errorLink = new ErrorLink(({ error }) => {
if (CombinedGraphQLErrors.is(error)) {
const unauthorized = error.errors.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>;
};