import { useMemo } from 'react' ; import { ApolloClient , InMemoryCache , NormalizedCacheObject } from '@apollo/client' ; import { Context } from '@typeDefs/resolver' ; let apolloClient ; const createIsomorphLink = ( context = { } ) => { if ( typeof window === 'undefined' ) { const { SchemaLink } = require ( '@apollo/client/link/schema' ) ; const { schema } = require ( './schema' ) ; return new SchemaLink ( { schema , context } ) ; } else { const { HttpLink } = require ( '@apollo/client/link/http' ) ; return new HttpLink ( { uri : '/api/graphql' , credentials : 'same-origin' , } ) ; } } ; const createApolloClient = ( context ? ) => { return new ApolloClient ( { ssrMode : typeof window === 'undefined' , link : createIsomorphLink ( context ) , cache : new InMemoryCache ( ) , } ) ; } ; export const initializeApollo = ( initialState = null , context ? ) => { const _apolloClient = apolloClient ?? createApolloClient ( context ) ; if ( initialState ) { _apolloClient . cache . restore ( initialState ) ; } if ( typeof window === 'undefined' ) return _apolloClient ; if ( ! apolloClient ) apolloClient = _apolloClient ; return _apolloClient ; } ; export const useApollo = ( initialState ? ) => { const store = useMemo ( ( ) => initializeApollo ( initialState ) , [ initialState ] ) ; return store ; } ;