Files
FictionArchive/fictionarchive-web/src/apolloClient.ts
2025-11-24 13:36:49 -05:00

31 lines
865 B
TypeScript

import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'
import {SetContextLink} from '@apollo/client/link/context'
import { userManager } from './auth/oidcClient'
const uri = import.meta.env.VITE_GRAPHQL_URI ?? 'https://localhost:5001/graphql'
const httpLink = new HttpLink({ uri })
const authLink = new SetContextLink(async ({ headers }, _) => {
if (!userManager) return { headers }
try {
const user = await userManager.getUser()
const token = user?.access_token
if (!token) return { headers }
return {
headers: {
...headers,
Authorization: `Bearer ${token}`,
},
}
} catch (error) {
console.warn('Failed to load user for auth header', error)
return { headers }
}
})
export const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
})