import type { Request, RequestHandler, Response, Router } from 'express'; import { z } from 'zod'; import { ApiError } from './errors'; import auth from '../middleware/authMiddleware'; /** * Every /api/v2 endpoint is declared with `defineRoute`: method, path, who may call it, and zod * schemas for the params, query, body and response. The same declaration * - validates the request (400 VALIDATION_FAILED with per-field messages), * - checks the response against its schema and strips anything it doesn't list (so a field * can't leak by being added to a Prisma include), and * - becomes the OpenAPI document (openapi.ts) — the docs can't drift from the code. */ export type Access = 'public' | 'optional' | 'user' | 'staff' | 'supervisor' | 'admin'; /** The signed-in person, as the auth middleware puts it on the request. */ export type ApiUser = { id: string; name: string; email: string; role: 'admin' | 'supervisor' | 'staff' | 'user' }; export type Ctx
= {
params: P;
query: Q;
body: B;
user: ApiUser | null;
req: Request;
res: Response;
};
type Schema = z.ZodType;
type Infer = S extends z.ZodType ? z.infer : undefined;
export type RouteDef
= {
method: 'get' | 'post' | 'put' | 'patch' | 'delete';
/** Express-style, relative to /api/v2: "/events/:id". */
path: string;
summary: string;
description?: string;
tag: string;
access: Access;
/**
* Staff and supervisor routes must say how they treat campus-scoped staff (see
* utils/campusScope.js and tests/campusScopeRoutes.test.js) — e.g. "scopeEvent(params.id)".
*/
campusScope?: string;
params?: P;
query?: Q;
body?: B;
response: R;
/** HTTP status on success (default 200). */
status?: number;
/** Runs after the access check, e.g. a rate limiter. */
middleware?: RequestHandler[];
handler: (ctx: Ctx (def: RouteDef ): RouteDef {
if ((def.access === 'staff' || def.access === 'supervisor') && !def.campusScope) {
throw new Error(`${def.method.toUpperCase()} /api/v2${def.path}: staff and supervisor routes must declare campusScope`);
}
routes.push(def as AnyRoute);
return def;
}
const parse = , Infer>) => Promise
(schema: S, value: unknown): Infer =>
(schema ? schema.parse(value) : undefined) as Infer;
/** Adds every defined route to the router. */
export function mount(router: Router, list: AnyRoute[] = routes): void {
for (const def of list) {
const run: RequestHandler = async (req, res, next) => {
try {
const ctx = {
params: parse(def.params, req.params),
query: parse(def.query, req.query),
body: parse(def.body, req.body ?? {}),
user: (req as Request & { user?: ApiUser }).user ?? null,
req,
res,
};
const result = await def.handler(ctx);
const checked = def.response.safeParse(result);
if (!checked.success) {
console.error(`[api/v2] ${def.method.toUpperCase()} ${def.path}: response doesn't match its schema`, checked.error.issues);
throw new ApiError('INTERNAL', 'Something went wrong on the server.');
}
res.status(def.status ?? 200).json(checked.data);
} catch (err) {
next(err);
}
};
router[def.method](def.path, ...ACCESS[def.access], ...(def.middleware ?? []), run);
}
}