Files
dancefinder-app/plugins/apollo.js
T

59 lines
1.4 KiB
JavaScript

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 { useAuth } from './auth'
import { provide } from '@vue/composition-api'
import introspectionQueryResultData from '../fragmentTypes.json'
import { onGlobalSetup } from 'nuxt-composition-api'
import { DefaultApolloClient } from '@vue/apollo-composable'
import Vue from 'vue'
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'
}
}
})
Vue.use(() => {
onGlobalSetup(() => {
provide(DefaultApolloClient, instance)
})
})