webapp/src/graphql/privateGraphQLClient.ts

79 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-12-17 03:27:00 +00:00
import {
ClientOptions,
dedupExchange,
fetchExchange,
Exchange,
subscriptionExchange,
createClient
} from '@urql/core'
2023-01-30 15:10:27 +00:00
// import { createClient as createSubClient } from 'graphql-sse'
2023-02-23 14:07:25 +00:00
import { createClient as createWSClient } from 'graphql-ws'
2022-09-09 11:53:35 +00:00
import { devtoolsExchange } from '@urql/devtools'
2022-10-25 16:25:42 +00:00
import { isDev, apiBaseUrl } from '../utils/config'
2022-11-19 08:53:27 +00:00
// import { cache } from './cache'
2022-09-09 11:53:35 +00:00
const TOKEN_LOCAL_STORAGE_KEY = 'token'
2022-09-22 09:37:49 +00:00
const exchanges: Exchange[] = [dedupExchange, fetchExchange]
2022-09-09 11:53:35 +00:00
if (isDev) {
exchanges.unshift(devtoolsExchange)
}
2022-11-14 01:17:12 +00:00
export const getToken = (): string => {
return localStorage.getItem(TOKEN_LOCAL_STORAGE_KEY)
}
2022-09-09 11:53:35 +00:00
export const setToken = (token: string) => {
if (!token) {
console.error('[privateGraphQLClient] setToken: token is null!')
}
2022-09-09 11:53:35 +00:00
localStorage.setItem(TOKEN_LOCAL_STORAGE_KEY, token)
}
export const resetToken = () => {
localStorage.removeItem(TOKEN_LOCAL_STORAGE_KEY)
}
const options: ClientOptions = {
2023-02-17 09:21:02 +00:00
url: apiBaseUrl,
2022-09-09 11:53:35 +00:00
maskTypename: true,
requestPolicy: 'cache-and-network',
fetchOptions: () => {
// localStorage is the source of truth for now
// to change token call setToken, for example after login
2022-09-09 11:53:35 +00:00
const token = localStorage.getItem(TOKEN_LOCAL_STORAGE_KEY)
if (!token) {
console.error('[privateGraphQLClient] fetchOptions: token is null!')
}
2022-11-22 03:02:11 +00:00
const headers = { Authorization: token }
2022-09-09 11:53:35 +00:00
return { headers }
},
exchanges
}
2022-11-20 18:49:44 +00:00
export const privateGraphQLClient = createClient(options)
2022-12-17 03:27:00 +00:00
2023-02-23 14:07:25 +00:00
export const createSubClient = () => {
const subClient = createWSClient({
2023-02-17 09:21:02 +00:00
url: apiBaseUrl.replace('http', 'ws') // + '/messages'
2022-12-17 03:27:00 +00:00
})
const subExchange = subscriptionExchange({
forwardSubscription(operation) {
return {
subscribe: (sink) => {
const dispose = subClient.subscribe(operation, sink)
return {
unsubscribe: dispose
}
}
}
}
})
options.exchanges.unshift(subExchange)
return createClient(options)
}