freshyo/tests/web/lib/trpc.ts
2026-10-05 11:46:47 +05:30

35 lines
1.6 KiB
TypeScript

// Minimal tRPC-over-HTTP helper for API-level assertions.
// Backend envelope is `{ "0": input }` (no `json` wrapper); queries go over
// GET with `?batch=1&input=...`, mutations over POST with `?batch=1`.
import { request } from '@playwright/test';
const apiUrl = () => (process.env.API_URL || 'http://127.0.0.1:8787').replace(/\/$/, '');
export async function staffLogin(name: string, password: string): Promise<{ token: string; staff: any }> {
const ctx = await request.newContext();
const res = await ctx.post(`${apiUrl()}/api/trpc/admin.staffUser.login?batch=1`, {
headers: { 'content-type': 'application/json' },
data: { 0: { name, password } },
});
const body = await res.json();
await ctx.dispose();
if (body[0]?.error) throw new Error(`login failed for ${name}: ${body[0].error.message}`);
return { token: body[0].result.data.token, staff: body[0].result.data.staff };
}
export async function trpcCall(token: string | null, path: string, input?: any, method: 'GET' | 'POST' = 'GET') {
const ctx = await request.newContext();
const headers: Record<string, string> = { 'content-type': 'application/json' };
if (token) headers['Authorization'] = `Bearer ${token}`;
let url = `${apiUrl()}/api/trpc/${path}?batch=1`;
let res;
if (method === 'GET') {
if (input !== undefined) url += `&input=${encodeURIComponent(JSON.stringify({ 0: input }))}`;
res = await ctx.get(url, { headers });
} else {
res = await ctx.post(url, { headers, data: { 0: input } });
}
const body = await res.json();
await ctx.dispose();
return body[0];
}