forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

live-client.ts126 lines, 4.9 KiBHistoryRawDownload
1/**
2 * Minimal live-backend client for the contract suite: a cookie jar (fetch keeps
3 * none of its own in bun/node) plus a hard timeout so a dead port fails fast
4 * instead of hanging the run. Boot recipe: see vitest.contract.config.ts.
5 */
6import { expect } from "vitest";
7
8// The app's tsconfig has no node types (browser build), so reach env this way.
9const env: Record<string, string | undefined> =
10 (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {};
11
12export const contractBaseUrl = (env.CONTRACT_BASE_URL ?? "").replace(/\/+$/, "");
13export const isLive = contractBaseUrl !== "";
14
15export const SKIP_MESSAGE =
16 "[contract] CONTRACT_BASE_URL unset — skipping live contract tests. " +
17 "Boot a scratch backend (see vitest.contract.config.ts) and re-run with " +
18 "CONTRACT_BASE_URL=http://127.0.0.1:8081 bun run test:contract";
19
20const TIMEOUT_MS = 10_000;
21const MAX_RATE_LIMIT_RETRIES = 12;
22let cookie = "";
23
24type Init = { method?: string; body?: unknown; headers?: Record<string, string> };
25
26function retryDelayMs(response: Response, attempt: number): number {
27 const retryAfter = Number(response.headers.get("Retry-After"));
28 if (Number.isFinite(retryAfter) && retryAfter > 0) return retryAfter * 1_000;
29 return Math.min(1_000 * 2 ** attempt, 5_000);
30}
31
32/** Raw request — returns the Response so tests can assert on status codes. */
33export async function api(path: string, init: Init = {}): Promise<Response> {
34 const headers: Record<string, string> = { ...init.headers };
35 if (cookie) headers.Cookie = cookie;
36
37 let body: BodyInit | undefined;
38 if (init.body instanceof FormData) {
39 body = init.body;
40 } else if (init.body !== undefined) {
41 headers["Content-Type"] = "application/json";
42 body = JSON.stringify(init.body);
43 }
44
45 let res: Response | undefined;
46 for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt += 1) {
47 res = await fetch(`${contractBaseUrl}${path}`, {
48 method: init.method ?? "GET",
49 headers,
50 body,
51 redirect: "manual",
52 signal: AbortSignal.timeout(TIMEOUT_MS),
53 });
54 // A 429 has not executed the request, so retrying it is safe even for
55 // contract-suite POST/PATCH probes. Production calls remain unchanged.
56 if (res.status !== 429 || attempt === MAX_RATE_LIMIT_RETRIES) break;
57 await new Promise<void>((resolve) => setTimeout(resolve, retryDelayMs(res!, attempt)));
58 }
59
60 const setCookies = res!.headers.getSetCookie?.() ?? [];
61 for (const raw of setCookies) {
62 const pair = raw.split(";")[0];
63 if (pair.startsWith("session=")) cookie = pair;
64 }
65 return res!;
66}
67
68/** Request + JSON body, throwing on a non-2xx so setup failures are loud. */
69export async function json<T>(path: string, init: Init = {}): Promise<T> {
70 const res = await api(path, init);
71 const text = await res.text();
72 if (!res.ok) {
73 throw new Error(`${init.method ?? "GET"} ${path} → ${res.status} ${text}`);
74 }
75 return (text ? JSON.parse(text) : null) as T;
76}
77
78/** Log in as the seeded admin; the session cookie lands in the jar. */
79export async function loginAdmin(): Promise<void> {
80 const result = await json<{ id: string } | { schools: Array<{ slug: string }> }>("/auth/login", {
81 method: "POST",
82 body: {
83 username: env.ADMIN_USERNAME ?? "admin",
84 password: env.ADMIN_PASSWORD ?? "admin123",
85 },
86 });
87 if ("schools" in result) {
88 const school = env.SCHOOL_SLUG ?? result.schools[0]?.slug;
89 if (!school) throw new Error("POST /auth/login returned an empty school choice list");
90 await json("/auth/school", { method: "POST", body: { school } });
91 }
92}
93
94/** Exam kinds are school policy, not a globally fixed enum. */
95export async function configuredExamKind(): Promise<string> {
96 const settings = await json<{ exam_kinds?: Array<{ name?: unknown }> }>("/settings");
97 const kind = settings.exam_kinds?.find((entry) => typeof entry.name === "string" && entry.name.trim())?.name;
98 if (!kind || typeof kind !== "string") throw new Error("GET /settings returned no configured exam kind");
99 return kind;
100}
101
102/** Smallest valid 1x1 PNG, for the image-upload steps. */
103export function pngFile(name: string): File {
104 const bytes = Uint8Array.from(
105 atob(
106 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
107 ),
108 (c) => c.charCodeAt(0),
109 );
110 return new File([bytes], name, { type: "image/png" });
111}
112
113/** Assert the list envelope shared by all paginated REST routes. */
114export function expectPage(data: unknown): asserts data is {
115 items: unknown[];
116 total: number;
117 limit: number | null;
118 offset: number;
119} {
120 expect(data).toMatchObject({});
121 expect(Array.isArray((data as { items?: unknown }).items)).toBe(true);
122 expect(typeof (data as { total?: unknown }).total).toBe("number");
123 const limit = (data as { limit?: unknown }).limit;
124 expect(limit === null || typeof limit === "number").toBe(true);
125 expect(typeof (data as { offset?: unknown }).offset).toBe("number");
126}