webapp/src/graphql/privateGraphQLClient.ts
2022-11-19 11:53:27 +03:00

43 lines
1.4 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 { ClientOptions, dedupExchange, fetchExchange, Exchange } from '@urql/core'
import { devtoolsExchange } from '@urql/devtools'
import { isDev, apiBaseUrl } from '../utils/config'
import { initClient } from './client'
// import { cache } from './cache'
const TOKEN_LOCAL_STORAGE_KEY = 'token'
const exchanges: Exchange[] = [dedupExchange, fetchExchange]
if (isDev) {
exchanges.unshift(devtoolsExchange)
}
export const getToken = (): string => {
return localStorage.getItem(TOKEN_LOCAL_STORAGE_KEY)
}
export const setToken = (token: string) => {
localStorage.setItem(TOKEN_LOCAL_STORAGE_KEY, token)
}
export const resetToken = () => {
localStorage.removeItem(TOKEN_LOCAL_STORAGE_KEY)
}
const options: ClientOptions = {
url: apiBaseUrl,
maskTypename: true,
requestPolicy: 'cache-and-network',
fetchOptions: () => {
// пока источником правды для значения токена будет локальное хранилище
// меняем через setToken, например при получении значения с сервера
// скорее всего придумаем что-нибудь получше со временем
const token = localStorage.getItem(TOKEN_LOCAL_STORAGE_KEY)
const headers = { Auth: token }
return { headers }
},
exchanges
}
export const privateGraphQLClient = initClient(options)