import ApolloClient from 'apollo-client' ; import { setContext } from 'apollo-link-context' ; import { ApolloLink , from } from 'apollo-link' ; import { createHttpLink } from 'apollo-link-http' ; import { InMemoryCache , IntrospectionFragmentMatcher } from 'apollo-cache-inmemory' ; import { resolve } from 'url' ; import { onError } from 'apollo-link-error' ; import { showSessionExpireConfirmation } from '@client/notification/actions' ; import { IStoreState } from '@client/store' ; import { AnyAction , Store } from 'redux' ; import * as Sentry from '@sentry/browser' ; import TimeoutLink from '@client/utils/timeoutLink' ; export let client ; export const createClient = ( store ) => { const httpLink = createHttpLink ( { uri : resolve ( window . config . API_GATEWAY_URL , 'graphql' ) } ) ; const authLink = setContext ( ( _ , { headers } ) => { const token = localStorage . getItem ( 'opencrvs' ) ; return { headers : { ... headers , authorization : token ? `Bearer ${ token }` : '' } } ; } ) ; const errorLink = onError ( ( error ) => { if ( ( error . networkError && error . networkError . statusCode && error . networkError . statusCode === 401 ) || ( error . graphQLErrors && error . graphQLErrors [ 0 ] && error . graphQLErrors [ 0 ] . extensions && error . graphQLErrors [ 0 ] . extensions . code && error . graphQLErrors [ 0 ] . extensions . code === 'UNAUTHENTICATED' ) ) { store . dispatch ( showSessionExpireConfirmation ( ) ) ; } else { Sentry . captureException ( error ) ; } } ) ; const timeoutLink = new TimeoutLink ( ) as ApolloLink ; const fragmentMatcher = new IntrospectionFragmentMatcher ( { introspectionQueryResultData : { __schema : { types : [ ] } } } ) ; client = new ApolloClient ( { link : from ( [ errorLink , timeoutLink , authLink , httpLink ] ) , cache : new InMemoryCache ( { fragmentMatcher } ) } ) ; return client ; } ;