import { HttpLink, ApolloLink, StoreObject, InMemoryCache, ApolloClient, } from '@apollo/client'; import { makeLoggingLink, makeErrorLink, } from '@elephant-healthcare/apollo-client-observability'; import { ErrorEvent, Event } from '../types'; export function setUserLanguage(language?: string) { if (language) { localStorage.setItem('user-language', language); } } function getUserLanguage() { return localStorage.getItem('user-language') || undefined; } const getHttpLink = (federationPath: string) => new HttpLink({ uri: federationPath }); const headersMiddleware = new ApolloLink((operation, forward) => { const token = window.sessionStorage.getItem('token'); const headers: { [k: string]: string | undefined } = { 'X-Elephant-Locale': getUserLanguage(), }; if (token) { headers.authorization = token; } operation.setContext({ headers, }); return forward(operation); }); /** * We require a custom id identifier due to the use of uuids * @param {*} object is the object from the store */ export function customDataIdFromObject(object: Readonly) { // eslint-disable-next-line @typescript-eslint/naming-convention const { __typename, id, _id, uuid } = object; if (typeof __typename === 'string') { if (typeof id === 'string') return `${__typename}:${id}`; if (typeof _id === 'string') return `${__typename}:${_id}`; if (typeof uuid === 'string') return `${__typename}:${uuid}`; } return undefined; } export const newCache = () => new InMemoryCache({ dataIdFromObject: customDataIdFromObject, }); export const getApolloClient = ({ federationPath, territory, emitAnalyticsEvent, emitErrorEvent, appVersion, cache, }: { federationPath: string; territory: string; emitAnalyticsEvent: (event: Event) => void; emitErrorEvent: (event: ErrorEvent) => void; appVersion: string; cache?: InMemoryCache; }) => new ApolloClient({ cache: cache || newCache(), link: ApolloLink.from([ headersMiddleware, makeLoggingLink({ emitEvent: emitAnalyticsEvent }), makeErrorLink({ emitErrorEvent }), getHttpLink(federationPath), ]), name: `web-shell-wrapper-${territory}`, version: appVersion, });