This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/lib/apiV2.ts
T

48 lines
2.8 KiB
TypeScript

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<M extends Method> = { [P in keyof paths]: paths[P][M] extends { responses: unknown } ? P : never }[keyof paths];
type Op<P extends keyof paths, M extends Method> = NonNullable<paths[P][M]>;
type Json<T> = T extends { content: { "application/json": infer J } } ? J : never;
type Responses<O> = O extends { responses: infer R } ? R : never;
/** The 2xx answer's JSON. */
export type V2Result<P extends keyof paths, M extends Method> = Json<Responses<Op<P, M>>[Extract<keyof Responses<Op<P, M>>, 200 | 201>]>;
type PathParams<O> = O extends { parameters: { path: infer X } } ? (X extends Record<string, unknown> ? X : never) : never;
type QueryParams<O> = O extends { parameters: { query?: infer X } } ? X : never;
type Body<O> = O extends { requestBody: { content: { "application/json": infer B } } } ? B : never;
type IfAny<T, Then> = [T] extends [never] ? object : Then;
export type V2Options<P extends keyof paths, M extends Method> =
{ authToken?: string | null; nextOptions?: RequestInit }
& IfAny<PathParams<Op<P, M>>, { params: PathParams<Op<P, M>> }>
& IfAny<QueryParams<Op<P, M>>, { query?: QueryParams<Op<P, M>> }>
& IfAny<Body<Op<P, M>>, { body: Body<Op<P, M>> }>;
export function apiV2<M extends Method, P extends PathsWith<M>>(method: M, path: P, ...[options]: object extends V2Options<P, M> ? [V2Options<P, M>?] : [V2Options<P, M>]): Promise<V2Result<P, M>> {
const opts = (options || {}) as { authToken?: string | null; nextOptions?: RequestInit; params?: Record<string, string>; query?: Record<string, unknown>; 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<V2Result<P, M>>(`/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<P extends keyof paths, M extends Method> = Body<Op<P, M>>;