Skip to content

Instantly share code, notes, and snippets.

@masiamj
Created January 14, 2022 15:15
Show Gist options
  • Save masiamj/4bff99d87a7467a77e80943a29aa3e0c to your computer and use it in GitHub Desktop.
Save masiamj/4bff99d87a7467a77e80943a29aa3e0c to your computer and use it in GitHub Desktop.
import pkg from '../../../package'
import _ from 'lodash'
import {
ApolloClient,
from,
HttpLink,
InMemoryCache,
split,
} from '@apollo/client'
import { onError } from '@apollo/link-error'
import { WebSocketLink } from '@apollo/link-ws'
import { setContext } from '@apollo/link-context'
import { getMainDefinition } from '@apollo/client/utilities'
import { env } from '../../../constants/environment'
import { getAuthenticationInformation } from '../../authentication'
/**
* Apollo cache instance
*/
export const cache = new InMemoryCache({
possibleTypes: {},
typePolicies: {
Company: {
keyFields: ['symbol'],
},
Quote: {
keyFields: ['symbol'],
},
},
})
/**
* HTTP Link
*/
const httpLink = new HttpLink({
uri: `${env.apiHost}/meatball`,
})
/**
* WebSocket link for subscriptions
*/
const wsLink = new WebSocketLink({
uri: `${env.wsHost}/meatball`,
options: {
reconnect: true,
connectionParams: async () => {
const { token } = await getAuthenticationInformation()
return {
authorization: `Bearer ${token}`,
}
},
},
})
/**
* Sets auth token on an individual request
*/
const authorizationLink = setContext(async (_request, _previousContext) => {
const { token } = await getAuthenticationInformation()
const headers = {
authorization: `Bearer ${token}`,
}
return { headers }
})
/**
* Single place to handle errors
*/
const handleErrorLink = onError(
({ forward, graphQLErrors, operation, response }) => {
/**
* Do error handling here
*/
return forward(operation)
}
)
const remoteDataLink = split(
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
wsLink,
httpLink
)
/**
* Apollo Client instance
*/
export const client = new ApolloClient({
cache,
link: from([authorizationLink, handleErrorLink, remoteDataLink]),
name: _.get(pkg, ['name']),
version: _.get(pkg, ['version']),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment