Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
69 lines
4.1 KiB
TypeScript
69 lines
4.1 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 });
|
|
}
|
|
|
|
/**
|
|
* 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<T = unknown>(method: Method, path: string, options: { authToken?: string | null; body?: unknown; query?: Record<string, unknown> } = {}): Promise<T> {
|
|
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<P extends keyof paths, M extends Method> = Body<Op<P, M>>;
|
|
|
|
/**
|
|
* `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<Coupon[]>)`.
|
|
*/
|
|
export async function apiV2Data<M extends Method, P extends PathsWith<M>>(method: M, path: P, ...rest: object extends V2Options<P, M> ? [V2Options<P, M>?] : [V2Options<P, M>]): Promise<unknown> {
|
|
const res = (await apiV2(method, path, ...(rest as [V2Options<P, M>]))) as { data?: unknown };
|
|
return res.data;
|
|
}
|