Files
sfera-new/src/lib/apollo-client.ts

111 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ApolloClient, InMemoryCache, createHttpLink, from } from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { onError } from '@apollo/client/link/error'
// HTTP Link для GraphQL запросов
const httpLink = createHttpLink({
uri: '/api/graphql',
})
// Auth Link для добавления JWT токена в заголовки
const authLink = setContext((operation, { headers }) => {
if (typeof window === 'undefined') {
return { headers }
}
// Проверяем токены администратора и пользователя
const adminToken = localStorage.getItem('adminAuthToken')
const userToken = localStorage.getItem('authToken')
// Приоритет у админского токена
const token = adminToken || userToken
const tokenType = adminToken ? 'admin' : 'user'
console.log(`Apollo Client - Operation: ${operation.operationName}, Token type: ${tokenType}, Token:`, token ? `${token.substring(0, 20)}...` : 'No token')
const authHeaders = {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
console.log('Apollo Client - Auth headers:', { authorization: authHeaders.authorization ? 'Bearer ***' : 'No auth' })
return {
headers: authHeaders
}
})
// Error Link для обработки ошибок - минимальная версия
const errorLink = onError(() => {
// Пустой обработчик - не делаем ничего
// Это предотвращает любые ошибки в error handler
})
// Создаем Apollo Client
export const apolloClient = new ApolloClient({
link: from([
authLink,
httpLink,
]),
cache: new InMemoryCache({
typePolicies: {
User: {
fields: {
organization: {
merge: true,
},
},
},
Organization: {
fields: {
apiKeys: {
merge: false,
},
},
},
},
}),
defaultOptions: {
watchQuery: {
errorPolicy: 'all',
},
query: {
errorPolicy: 'all',
},
},
})
// Утилитарные функции для работы с токеном и пользователем
export const setAuthToken = (token: string) => {
if (typeof window !== 'undefined') {
localStorage.setItem('authToken', token)
}
}
export const removeAuthToken = () => {
if (typeof window !== 'undefined') {
localStorage.removeItem('authToken')
localStorage.removeItem('userData')
}
}
export const getAuthToken = (): string | null => {
if (typeof window !== 'undefined') {
return localStorage.getItem('authToken')
}
return null
}
export const setUserData = (userData: unknown) => {
if (typeof window !== 'undefined') {
localStorage.setItem('userData', JSON.stringify(userData))
}
}
export const getUserData = (): unknown | null => {
if (typeof window !== 'undefined') {
const data = localStorage.getItem('userData')
return data ? JSON.parse(data) : null
}
return null
}