import { ApolloClient } from 'apollo-client' import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory' import { createHttpLink } from 'apollo-link-http' import { setContext } from 'apollo-link-context' import { provide } from '@vue/composition-api' import { DefaultApolloClient } from '@vue/apollo-composable' import introspectionQueryResultData from '../fragmentTypes.json' import { useAuth } from './auth' const apiUrl = process.env.graphqlApi || '/query' const fragmentMatcher = new IntrospectionFragmentMatcher({ introspectionQueryResultData }) const cache = new InMemoryCache({ fragmentMatcher }) const httpLink = createHttpLink({ uri: apiUrl }) const getToken = async (options) => { const { getTokenSilently } = useAuth() return getTokenSilently.value(options) } const authLink = setContext(async (_, { headers }) => { return getToken().then((token) => ({ headers: { ...headers, authorization: token ? `Bearer ${token}` : '' } })) }) const link = authLink.concat(httpLink) const instance = new ApolloClient({ connectToDevTools: true, link, cache, defaultOptions: { query: { fetchPolicy: 'cache-and-network' }, watchQuery: { fetchPolicy: 'cache-and-network' } } }) export default function ({ app }) { app.setup = () => { provide(DefaultApolloClient, instance) } }