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 }); } /** The JSON body a v2 endpoint takes. */ export type V2Body

= Body>;