Files
Sankofa/src/lib/graphql/client.ts

59 lines
1.7 KiB
TypeScript
Raw Normal View History

import { ApolloClient, InMemoryCache, createHttpLink, from, ApolloLink } from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { onError } from '@apollo/client/link/error'
import { handleApiError, getUserFriendlyMessage } from '@/lib/error-handler'
// HTTP Link - configured to use the GraphQL API
const httpLink = createHttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql',
})
// Auth Link - for adding authentication headers
const authLink = setContext((_, { headers }) => {
// Get the authentication token from secure storage
let token: string | null = null
if (typeof window !== 'undefined') {
// Try to get from secure storage
token = sessionStorage.getItem('auth_token')
}
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
}
})
// Error Link - handle GraphQL and network errors
const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) => {
const error = handleApiError(new Error(message))
console.error(
`[GraphQL error]: Message: ${getUserFriendlyMessage(error)}, Location: ${locations}, Path: ${path}`
)
})
}
if (networkError) {
const error = handleApiError(networkError)
console.error(`[Network error]: ${getUserFriendlyMessage(error)}`)
}
})
// Create Apollo Client
export const apolloClient = new ApolloClient({
link: from([errorLink, authLink, httpLink]),
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
errorPolicy: 'all',
},
query: {
errorPolicy: 'all',
},
},
})