2022-08-17 08:42:25 +02:00
|
|
|
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
|
2022-07-05 23:05:08 +02:00
|
|
|
import { setContext } from '@apollo/client/link/context'
|
2020-06-21 19:06:41 +02:00
|
|
|
import { useAuth } from './auth'
|
2020-06-21 17:59:14 +02:00
|
|
|
|
|
|
|
|
const apiUrl = process.env.graphqlApi || '/query'
|
2020-04-06 10:19:18 +02:00
|
|
|
|
2022-07-05 23:05:08 +02:00
|
|
|
const cache = new InMemoryCache()
|
2020-04-06 10:19:18 +02:00
|
|
|
|
2020-01-21 15:51:51 +01:00
|
|
|
const httpLink = createHttpLink({
|
|
|
|
|
uri: apiUrl
|
|
|
|
|
})
|
|
|
|
|
|
2022-08-03 18:40:05 +02:00
|
|
|
const getToken = (options) => {
|
2020-04-06 10:19:18 +02:00
|
|
|
const { getTokenSilently } = useAuth()
|
2022-08-03 18:40:05 +02:00
|
|
|
return getTokenSilently(options)
|
2020-01-25 14:59:14 +01:00
|
|
|
}
|
2020-01-21 15:51:51 +01:00
|
|
|
|
2022-08-03 18:40:05 +02:00
|
|
|
const authLink = setContext((_, { headers }) => {
|
2022-08-17 08:42:25 +02:00
|
|
|
return getToken()
|
2024-02-02 14:46:42 +01:00
|
|
|
.then(token => ({
|
2022-08-17 08:42:25 +02:00
|
|
|
headers: {
|
|
|
|
|
...headers,
|
|
|
|
|
authorization: token ? `Bearer ${token}` : ''
|
|
|
|
|
}
|
|
|
|
|
})).catch(() => {
|
|
|
|
|
return {}
|
|
|
|
|
})
|
2020-01-21 15:51:51 +01:00
|
|
|
})
|
|
|
|
|
|
2020-06-21 17:59:14 +02:00
|
|
|
const link = authLink.concat(httpLink)
|
|
|
|
|
|
|
|
|
|
const instance = new ApolloClient({
|
|
|
|
|
connectToDevTools: true,
|
|
|
|
|
link,
|
2020-04-06 10:19:18 +02:00
|
|
|
cache,
|
2020-01-21 15:51:51 +01:00
|
|
|
defaultOptions: {
|
2020-06-21 17:59:14 +02:00
|
|
|
query: {
|
|
|
|
|
fetchPolicy: 'cache-and-network'
|
|
|
|
|
},
|
2020-01-21 15:51:51 +01:00
|
|
|
watchQuery: {
|
2020-01-25 14:59:14 +01:00
|
|
|
fetchPolicy: 'cache-and-network'
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-01-21 15:51:51 +01:00
|
|
|
})
|
|
|
|
|
|
2024-02-02 14:46:42 +01:00
|
|
|
export default function (_, inject) {
|
2022-08-03 18:40:05 +02:00
|
|
|
inject('apollo', instance)
|
2021-11-19 20:20:04 +01:00
|
|
|
}
|