import { ApolloClient } from 'apollo-client'; import { ApolloLink } from 'apollo-link'; import { createHttpLink } from 'apollo-link-http'; import { defaultDataIdFromObject, InMemoryCache } from 'apollo-cache-inmemory'; import { BACKEND } from './vars'; import { AppContext, PluginParams } from './index'; const isBrowser = typeof window !== 'undefined'; const base = isBrowser ? location.origin + '/graphql' : BACKEND; const httpLink = createHttpLink({ uri: base, useGETForQueries: true, }); export function getClient({ initialState = {} } = {}): ApolloClient { return new ApolloClient({ link: ApolloLink.from([httpLink]), cache: new InMemoryCache({ dataIdFromObject: (object: any): any => { switch (object.__typename) { case 'EntityUrl': return `${object.type}-${object.id}`; // use `type + id` as the primary key default: return defaultDataIdFromObject(object); // fall back to default handling } }, }).restore(initialState), }); } export function apolloClientPlugin(params: PluginParams, appCtx: AppContext): AppContext { const client = getClient(params.initialGQLState); return { ...appCtx, client, }; }