2022-12-17 03:27:00 +00:00
|
|
|
import {
|
|
|
|
ClientOptions,
|
|
|
|
dedupExchange,
|
|
|
|
fetchExchange,
|
|
|
|
Exchange,
|
|
|
|
subscriptionExchange,
|
|
|
|
createClient
|
|
|
|
} from '@urql/core'
|
|
|
|
import { createClient as createSubClient } from 'graphql-sse'
|
|
|
|
// import { createClient as createSubClient } 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) => {
|
2022-12-01 18:45:35 +00:00
|
|
|
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 = {
|
2022-12-17 03:27:00 +00:00
|
|
|
url: apiBaseUrl + '/graphql',
|
2022-09-09 11:53:35 +00:00
|
|
|
maskTypename: true,
|
|
|
|
requestPolicy: 'cache-and-network',
|
|
|
|
fetchOptions: () => {
|
2022-12-01 18:45:35 +00:00
|
|
|
// 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)
|
2022-12-01 18:45:35 +00:00
|
|
|
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
|
|
|
|
|
|
|
export const createChatClient = () => {
|
|
|
|
const subClient = createSubClient({
|
|
|
|
url: apiBaseUrl + '/messages' // .replace('http', 'ws')
|
|
|
|
})
|
|
|
|
|
|
|
|
const subExchange = subscriptionExchange({
|
|
|
|
forwardSubscription(operation) {
|
|
|
|
return {
|
|
|
|
subscribe: (sink) => {
|
|
|
|
const dispose = subClient.subscribe(operation, sink)
|
|
|
|
return {
|
|
|
|
unsubscribe: dispose
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
options.exchanges.unshift(subExchange)
|
|
|
|
return createClient(options)
|
|
|
|
}
|