import { apiFetch } from "@/lib/api"; import type { paths } from "@/lib/api-v2/schema"; /** * Typed calls to /api/v2. The types come from the backend's OpenAPI document * (`npm run api:types` in the repo root regenerates src/lib/api-v2/), so a path, its parameters, * its body and its answer are all checked by TypeScript: * * const { data, meta } = await apiV2("get", "/events", { query: { q: "camp", limit: 10 } }); * const { data } = await apiV2("post", "/registrations/{id}/cancel", { params: { id }, authToken }); * * Errors throw ApiError (from apiFetch) with the v2 `code` and `fields` in `.data`. */ type Method = "get" | "post" | "put" | "patch" | "delete"; type PathsWith = { [P in keyof paths]: paths[P][M] extends { responses: unknown } ? P : never }[keyof paths]; type Op

= NonNullable; type Json = T extends { content: { "application/json": infer J } } ? J : never; type Responses = O extends { responses: infer R } ? R : never; /** The 2xx answer's JSON. */ export type V2Result

= Json>[Extract>, 200 | 201>]>; type PathParams = O extends { parameters: { path: infer X } } ? (X extends Record ? X : never) : never; type QueryParams = O extends { parameters: { query?: infer X } } ? X : never; type Body = O extends { requestBody: { content: { "application/json": infer B } } } ? B : never; type IfAny = [T] extends [never] ? object : Then; export type V2Options

= { authToken?: string | null; nextOptions?: RequestInit } & IfAny>, { params: PathParams> }> & IfAny>, { query?: QueryParams> }> & IfAny>, { body: Body> }>; export function apiV2>(method: M, path: P, ...[options]: object extends V2Options ? [V2Options?] : [V2Options]): Promise> { const opts = (options || {}) as { authToken?: string | null; nextOptions?: RequestInit; params?: Record; query?: Record; body?: unknown }; let url = String(path).replace(/\{(\w+)\}/g, (_, name: string) => encodeURIComponent(String(opts.params?.[name] ?? ""))); const qs = new URLSearchParams(); for (const [k, v] of Object.entries(opts.query || {})) { if (v !== undefined && v !== null && v !== "") qs.set(k, String(v)); } if (qs.toString()) url += `?${qs.toString()}`; return apiFetch>(`/api/v2${url}`, { method: method.toUpperCase(), authToken: opts.authToken, body: opts.body, nextOptions: opts.nextOptions }); } /** * An untyped v2 call, for screens whose helpers take the path as a string (`call(path, method)`): * the answer's `data`. Prefer `apiV2`/`apiV2Data` with a literal path where you can. */ export async function apiV2Raw(method: Method, path: string, options: { authToken?: string | null; body?: unknown; query?: Record } = {}): Promise { const qs = new URLSearchParams(); for (const [k, v] of Object.entries(options.query || {})) if (v !== undefined && v !== null && v !== "") qs.set(k, String(v)); const res = await apiFetch<{ data: T }>(`/api/v2${path}${qs.toString() ? `?${qs.toString()}` : ""}`, { method: method.toUpperCase(), authToken: options.authToken, body: options.body }); return res.data; } /** The JSON body a v2 endpoint takes. */ export type V2Body

= Body>; /** * `apiV2` for screens that keep their own record types: the path, parameters and body are still * checked against the API, and the answer's `data` comes back untyped — cast it: * `await (apiV2Data("get", "/coupons", { authToken }) as Promise)`. */ export async function apiV2Data>(method: M, path: P, ...rest: object extends V2Options ? [V2Options?] : [V2Options]): Promise { const res = (await apiV2(method, path, ...(rest as [V2Options]))) as { data?: unknown }; return res.data; }