50 lines
957 B
JavaScript
50 lines
957 B
JavaScript
import {
|
|
ApolloClient,
|
|
InMemoryCache,
|
|
createHttpLink
|
|
} 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}` : ''
|
|
}
|
|
}))
|
|
})
|
|
|
|
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)
|
|
}
|