freshyo/apps/web-ui/src/lib/trpc-client.ts
2026-10-25 21:35:38 +05:30

62 lines
2 KiB
TypeScript

import { createTRPCReact } from '@trpc/react-query'
import { createTRPCClient, httpBatchLink } from '@trpc/client'
import type { AppRouter } from '@backend/trpc/router'
import { BASE_API_URL as DEFAULT_API_URL } from '@packages/shared'
// const BASE_API_URL = 'http://192.168.100.111:8787'
export const BASE_API_URL =
(import.meta.env?.VITE_API_URL as string | undefined) || DEFAULT_API_URL
export const trpc = createTRPCReact<AppRouter>()
type UnauthorizedHandler = () => void
let unauthorizedHandler: UnauthorizedHandler | null = null
/** Registered by the auth provider; called when the API answers 401 UNAUTHORIZED. */
export function setUnauthorizedHandler(handler: UnauthorizedHandler | null) {
unauthorizedHandler = handler
}
/**
* Mirrors the user app's FORCE_LOGOUT_EVENT: a token the backend rejects must
* drop the session, even when the failing call was not getSelfData.
*/
async function fetchWithCredentialCheck(input: RequestInfo | URL, init?: RequestInit) {
const response = await fetch(input, init)
if (response.status === 401) {
const data = await response
.clone()
.json()
.catch(() => null)
const entry = Array.isArray(data) ? data[0] : data
// tRPC puts the code on error.data.code; a plain handler may only send a message.
const code = entry?.error?.data?.code ?? entry?.error?.message
if (code === 'UNAUTHORIZED') unauthorizedHandler?.()
}
return response
}
export function getTrpcClient() {
return createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: `${BASE_API_URL}/api/trpc`,
fetch: fetchWithCredentialCheck,
headers: async () => {
try {
const token = localStorage.getItem('auth_token')
const headers: Record<string, string> = {
'caller-interface': 'web',
}
if (token) {
headers.Authorization = `Bearer ${token}`
}
return headers
} catch {}
return { 'caller-interface': 'web' }
},
}),
],
})
}