41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import { createTRPCReact } from '@trpc/react-query'
|
|
import { createTRPCClient, httpBatchLink } from '@trpc/client'
|
|
import type { AppRouter } from '@backend/trpc/router'
|
|
import { getJWT } from '../hooks/useJWT'
|
|
import { EventBus, FORCE_LOGOUT_EVENT } from './event-bus'
|
|
import { BASE_API_URL as DEFAULT_API_URL } from '@packages/shared'
|
|
|
|
// Same backend as admin-ui; overridable via VITE_API_URL (set it to
|
|
// https://devapi.freshyo.in for dev builds — the shared default is production).
|
|
export const BASE_API_URL =
|
|
(import.meta.env?.VITE_API_URL as string | undefined) || DEFAULT_API_URL
|
|
|
|
export const trpc = createTRPCReact<AppRouter>()
|
|
|
|
export function getTrpcClient() {
|
|
return createTRPCClient<AppRouter>({
|
|
links: [
|
|
httpBatchLink({
|
|
url: `${BASE_API_URL}/api/trpc`,
|
|
headers: async () => {
|
|
const token = await getJWT()
|
|
return token ? { Authorization: `Bearer ${token}` } : {}
|
|
},
|
|
fetch: async (url, options) => {
|
|
const response = await fetch(url, options)
|
|
if (response.status === 401) {
|
|
const data = await response.clone().json().catch(() => ({}))
|
|
let code = ''
|
|
if (data[0]?.error || data?.error) {
|
|
code = data[0]?.error?.message || data?.error?.message
|
|
}
|
|
if (code === 'UNAUTHORIZED') {
|
|
EventBus.emit(FORCE_LOGOUT_EVENT)
|
|
}
|
|
}
|
|
return response
|
|
},
|
|
}),
|
|
],
|
|
})
|
|
}
|