freshyo/apps/backend/tests/helpers/api.ts
2026-09-26 17:50:33 +05:30

74 lines
2.3 KiB
TypeScript

/**
* HTTP client + small utilities for the backend API tests.
*
* Uses the same wire protocol as the apps (`httpBatchLink`, no transformer):
* POST/GET /api/trpc/<router>.<proc> -> [{ result: { data } }]
*/
import { createTRPCClient, httpBatchLink } from '@trpc/client'
import type { AppRouter } from '@/src/trpc/router'
import { API_BASE_URL, TRPC_URL } from './env'
export type ApiClient = ReturnType<typeof createTRPCClient<AppRouter>>
/** A tRPC client; pass a token to authenticate as that user/staff. */
export function apiClient(token?: string): ApiClient {
return createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: TRPC_URL,
headers: () => (token ? { Authorization: `Bearer ${token}` } : {}),
}),
],
})
}
/** Unique-enough suffix so reruns don't collide on names/emails. */
export function uniqueSuffix(): string {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`
}
/** Run a call that must reject and hand back the error (fails if it resolves). */
export async function captureError(fn: () => Promise<unknown>): Promise<Error> {
let error: Error | null = null
try {
await fn()
} catch (caught) {
error = caught as Error
}
if (!error) {
throw new Error('[api-tests] expected the call to reject, but it resolved')
}
return error
}
/** GET /api/health — the only unauthenticated REST endpoint. */
export async function health(): Promise<{ ok: boolean; status: number; body: unknown }> {
const res = await fetch(`${API_BASE_URL}/api/health`)
let body: unknown = null
try {
body = await res.json()
} catch {
body = null
}
return { ok: res.ok, status: res.status, body }
}
/**
* Fail fast with an actionable message when the local backend isn't running,
* instead of letting every request time out.
*/
export async function assertServerUp(): Promise<void> {
try {
const res = await fetch(`${API_BASE_URL}/api/health`, {
signal: AbortSignal.timeout(5000),
})
if (res.status >= 500) throw new Error(`health returned ${res.status}`)
} catch (error) {
throw new Error(
`[api-tests] Backend not reachable at ${API_BASE_URL}. Start it with ` +
`"cd apps/backend && bun run dev" (wrangler dev, port 8787). ` +
`Cause: ${(error as Error).message}`
)
}
}