import { ApolloClient , InMemoryCache , createHttpLink } from '@apollo/client' ; import { setContext } from '@apollo/client/link/context' ; import fetch from 'cross-fetch' ; import { LOGIN_TOKEN_KEY } from '../constants' ; import { cookies } from './cookies' ; export function createApolloClient ( ctx ? ) { let host ; let protocol ; let hostUrl = process . env . API_URL ; if ( ctx ) { host = ctx ?. req . headers [ 'x-forwarded-host' ] ; protocol = ctx ?. req . headers [ 'x-forwarded-proto' ] || 'http' ; hostUrl = `${ protocol }://${ host }` ; } else if ( typeof location !== 'undefined' ) { host = location . host ; protocol = location . protocol ; hostUrl = `${ protocol }//${ host }` ; } const uri = `${ hostUrl }/api/graphql` ; const httpLink = createHttpLink ( { uri , fetch , } ) ; const authLink = setContext ( ( _ , { headers } ) => { const token = cookies ( ) . get ( LOGIN_TOKEN_KEY ) ; return { headers : { ... headers , authorization : token ? `Bearer ${ token }` : '' , } , } ; } ) ; const client = new ApolloClient ( { link : authLink . concat ( httpLink ) , cache : new InMemoryCache ( ) , } ) ; return client ; }