Files
dancefinder-app/plugins/apollo.js
T
2022-08-17 08:42:25 +02:00

49 lines
1002 B
JavaScript

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
import { setContext } from '@apollo/client/link/context'
import { useAuth } from './auth'
const apiUrl = process.env.graphqlApi || '/query'
const cache = new InMemoryCache()
const httpLink = createHttpLink({
uri: apiUrl
})
const getToken = (options) => {
const { getTokenSilently } = useAuth()
return getTokenSilently(options)
}
const authLink = setContext((_, { headers }) => {
return getToken()
.then((token) => ({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
})).catch(() => {
return {}
})
})
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(_, inject) {
inject('apollo', instance)
}