-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapolloServerClient.ts
More file actions
47 lines (38 loc) · 1.21 KB
/
apolloServerClient.ts
File metadata and controls
47 lines (38 loc) · 1.21 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
import { registerApolloClient } from '@apollo/client-integration-nextjs';
import { cookies } from 'next/headers';
import {
ApolloClient,
ApolloLink,
CombinedGraphQLErrors,
HttpLink,
InMemoryCache,
} from '@apollo/client';
import { SetContextLink } from '@apollo/client/link/context';
import { ErrorLink } from '@apollo/client/link/error';
import { GRAPHQL_ENDPOINT } from '~/constants/apiRelated';
const authLink = new SetContextLink(async ({ headers = {} }) => {
const cookieStore = await cookies();
const token = cookieStore.get('token');
if (!headers?.Authorization && token) {
Object.assign(headers, { Authorization: `Bearer ${token.value}` });
}
return { headers };
});
const httpLink = new HttpLink({
uri: GRAPHQL_ENDPOINT,
fetchOptions: { cache: 'no-store' },
});
const errorLink = new ErrorLink(({ error }) => {
if (CombinedGraphQLErrors.is(error)) {
const unauthorized = error.errors.some(({ message }) => message === 'Unauthorized');
if (unauthorized) {
// Do something
}
}
});
export const { getClient } = registerApolloClient(() => {
return new ApolloClient({
link: ApolloLink.from([authLink, errorLink, httpLink]),
cache: new InMemoryCache(),
});
});