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[]; /** A multipart upload (the file in `field`, saved by a multer step in `middleware`). */ upload?: { field: string; description: string }; /** * The answer is a file, not JSON: the handler returns `{ data: { contentType, filename, body } }` * and `response` is `fileResponse`. `contentType` here is what the docs show. */ file?: { contentType: string }; /** * Documentation only (v1Route, 1.52.1): the body and the answer's `data` as the v1 handler takes * and gives them, for the OpenAPI document. Not enforced — the handler gets what was sent and its * answer goes out as it is — but outside production anything that doesn't fit is logged * (`[api/v2] … doesn't match its documented …`), so the docs can't drift unnoticed. */ documented?: { body?: Schema; response?: Schema }; handler: (ctx: Ctx, Infer, Infer>) => Promise> | z.input; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type AnyRoute = RouteDef; export const routes: AnyRoute[] = []; const ACCESS: Record = { public: [], optional: [auth.optionalAuth], user: [auth.protect], staff: [auth.protect, auth.staff], supervisor: [auth.protect, auth.supervisor], admin: [auth.protect, auth.admin], }; export function defineRoute

(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`); } // Two definitions of one route: the first would silently win. if (routes.some(r => r.method === def.method && r.path === def.path)) { throw new Error(`${def.method.toUpperCase()} /api/v2${def.path} is defined twice`); } routes.push(def as AnyRoute); return def; } const parse = (schema: S, value: unknown): Infer => (schema ? schema.parse(value) : undefined) as Infer; /** Outside production: says when a documented-only body or answer doesn't fit its documentation. */ function warnUndocumented(def: AnyRoute, what: string, schema: Schema, value: unknown) { if (process.env.NODE_ENV === 'production') return; const checked = schema.safeParse(value); if (!checked.success) { console.warn(`[api/v2] ${def.method.toUpperCase()} ${def.path}: ${what} doesn't match its documented schema`, JSON.stringify(checked.error.issues.slice(0, 5))); } } /** 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, }; if (def.documented?.body) warnUndocumented(def, 'request body', def.documented.body, req.body ?? {}); const result = await def.handler(ctx); if (def.documented?.response) warnUndocumented(def, 'answer', def.documented.response, (result as { data?: unknown })?.data); 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.'); } if (def.file) { const f = (checked.data as { data: { contentType: string; filename: string; body: string | Buffer } }).data; res.setHeader('Content-Type', f.contentType); res.setHeader('Content-Disposition', `attachment; filename="${f.filename.replace(/"/g, '')}"`); res.status(def.status ?? 200).send(f.body); return; } res.status(def.status ?? 200).json(checked.data); } catch (err) { next(err); } }; router[def.method](def.path, ...ACCESS[def.access], ...(def.middleware ?? []), run); } } /** The `response` of a `file` route: what the handler hands back to be sent as a download. */ export const fileResponse = z.object({ data: z.object({ contentType: z.string(), filename: z.string(), body: z.union([z.string(), z.instanceof(Buffer)]) }) });