import ApolloClient from "apollo-client" ; import { NormalizedCacheObject , InMemoryCache } from "apollo-cache-inmemory" ; import { createUploadLink } from "apollo-upload-client" ; import { setContext } from "apollo-link-context" ; import { onError } from "apollo-link-error" ; import { createHttpLink } from "apollo-link-http" ; import fetch from "isomorphic-unfetch" ; import Router from "next/router" ; import Cookies from "js-cookie" ; import { isBrowser } from "./isBrowser" ; let apolloClient = null ; if ( ! isBrowser ) { ( global as any ) . fetch = fetch ; } function create ( initialState ) { const httpLink = createUploadLink ( { uri : "http://127.0.0.1/graphql" , credentials : "include" , } ) ; const errorLink = onError ( ( { graphQLErrors , networkError } ) => { if ( graphQLErrors ) graphQLErrors . map ( ( { message , locations , path } ) => { console . log ( `[GraphQL error]: Message: ${ message }, Location: ${ locations }, Path: ${ path }` ) ; if ( isBrowser && message . includes ( "Access denied! You need to be authorized to perform this action!" ) ) { Router . replace ( "/users/login" ) ; } } ) ; if ( networkError ) console . log ( `[Network error]: ${ networkError }` ) ; } ) ; const authLink = setContext ( ( _ , { headers } ) => { const token = Cookies . get ( "jwt" ) ; return { headers : { ... headers , authorization : token ? `Bearer ${ token }` : "" , } , } ; } ) ; return new ApolloClient ( { connectToDevTools : isBrowser , ssrMode : ! isBrowser , link : errorLink . concat ( authLink . concat ( httpLink ) ) , cache : new InMemoryCache ( ) . restore ( initialState || { } ) , } ) ; } export default function initApollo ( initialState ) { if ( ! isBrowser ) { return create ( initialState ) ; } if ( ! apolloClient ) { apolloClient = create ( initialState ) ; } return apolloClient ; }