Files
schemas-app/app/plugins/apollo.client.ts
T

76 lines
2.0 KiB
TypeScript
Raw Normal View History

import { ApolloClient, from, HttpLink, InMemoryCache } from '@apollo/client/core'
import { setContext } from '@apollo/client/link/context'
import { DefaultApolloClient } from '@vue/apollo-composable'
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
// Determine API URL based on current host
const getApiUrl = () => {
if (typeof window === 'undefined') {
return config.public.apiBase
}
const hostname = window.location.hostname
// If running on localhost, use localhost:8080
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return 'http://localhost:8080'
}
// If running on schemas.unbound.se, use the same domain
if (hostname === 'schemas.unbound.se') {
return 'https://schemas.unbound.se'
}
// Fallback to config or construct from current location
return config.public.apiBase || `${window.location.protocol}//${window.location.host}`
}
// HTTP link for GraphQL endpoint
const httpLink = new HttpLink({
uri: `${getApiUrl()}/query`,
})
// Auth link to add authorization header
const authLink = setContext(async (_, { headers }) => {
try {
// Access Auth0 from the global app instance
const auth0Instance = (nuxtApp.vueApp.config.globalProperties as any).$auth0
if (auth0Instance?.isAuthenticated?.value) {
// Get the access token for API calls
const token = await auth0Instance.getAccessTokenSilently()
if (token) {
return {
headers: {
...headers,
authorization: `Bearer ${token}`,
},
}
}
}
} catch (error) {
console.error('[Apollo] Failed to get Auth0 token:', error)
}
return { headers }
})
// Create Apollo client
const apolloClient = new ApolloClient({
link: from([authLink, httpLink]),
cache: new InMemoryCache(),
})
// Provide Apollo client to the app
nuxtApp.vueApp.provide(DefaultApolloClient, apolloClient)
return {
provide: {
apolloClient,
},
}
})