import ApolloClient from 'apollo-client'; // Polyfill fetch import 'isomorphic-unfetch'; import { InitApolloClient, InitApolloOptions } from './types'; let _apolloClient: ApolloClient; const ssrMode = typeof window === 'undefined'; export default function initApollo( clientFn: InitApolloClient, options?: InitApolloOptions ): ApolloClient { if (!clientFn) { throw new Error( '[withApollo] the first param is missing and is required to get the ApolloClient' ); } if (ssrMode) { return getClient(clientFn, options); } if (!_apolloClient) { _apolloClient = getClient(clientFn, options); } return _apolloClient; } function getClient( clientFn: InitApolloClient, options: InitApolloOptions = {} ) { if (typeof clientFn !== 'function') { throw new Error( '[withApollo] requires a function that returns an ApolloClient' ); } return clientFn(options); }