-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapolloServerClient.ts
47 lines (37 loc) · 1.25 KB
/
apolloServerClient.ts
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
'use server';
import { registerApolloClient } from '@apollo/experimental-nextjs-app-support';
import { cookies } from 'next/headers';
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { GRAPHQL_ENDPOINT } from '~/constants/apiRelated';
export const apolloServerClient = async () => {
const cookieStore = await cookies();
const token = cookieStore.get('token');
const authLink = setContext(async (_, { headers = {} }) => {
if (!headers?.Authorization && token) {
Object.assign(headers, { Authorization: `Bearer ${token}` });
}
return {
headers,
};
});
const httpLink = new HttpLink({
uri: GRAPHQL_ENDPOINT,
fetchOptions: { cache: 'no-store' },
});
const errorLink = onError(({ graphQLErrors }) => {
if (graphQLErrors) {
const unauthorized = graphQLErrors.some(({ message }) => message === 'Unauthorized');
if (unauthorized) {
// Do something
}
}
});
return registerApolloClient(() => {
return new ApolloClient({
link: ApolloLink.from([authLink, errorLink, httpLink]),
cache: new InMemoryCache(),
});
});
};