35 lines
1.1 KiB
JavaScript
35 lines
1.1 KiB
JavaScript
import { createLink } from './link';
|
|
import { ApolloClient, InMemoryCache } from '@apollo/client';
|
|
import { isServer } from 'tools/common';
|
|
|
|
/** @type {import('@apollo/client').ApolloClient<import('@apollo/client').NormalizedCacheObject>} */
|
|
let apolloClient;
|
|
|
|
function createApolloClient(headers) {
|
|
return new ApolloClient({
|
|
cache: new InMemoryCache(),
|
|
link: createLink(headers),
|
|
ssrMode: isServer(),
|
|
});
|
|
}
|
|
|
|
export default function initializeApollo(initialState, headers) {
|
|
if (isServer() && !headers) {
|
|
throw new Error('initializeApollo: headers must be provided in server side');
|
|
}
|
|
|
|
const _apolloClient = apolloClient ?? createApolloClient(headers);
|
|
|
|
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
|
|
// gets hydrated here
|
|
if (initialState) {
|
|
_apolloClient.cache.restore(initialState);
|
|
}
|
|
// For SSG and SSR always create a new Apollo Client
|
|
if (isServer()) return _apolloClient;
|
|
// Create the Apollo Client once in the client
|
|
if (!apolloClient) apolloClient = _apolloClient;
|
|
|
|
return _apolloClient;
|
|
}
|