TypeScript backend and /api/v2 foundations (1.51.0)
- tsconfig (allowJs, strict .ts), npm run build -> dist/, typecheck, dev via tsx, ts-jest. - src/index.js is now a launcher (dist build when it matches, else tsx); server moved to app.js. - /api/v2: defineRoute with zod -> request validation, response stripping, OpenAPI 3.1 at /docs/v2; one error shape and one paged-list shape. First endpoints: events, event, me, my registrations. - deploy.sh/install.sh build the backend; rollback to older releases skips the build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
File diff suppressed because it is too large
Load Diff
+26
-1800
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
import type { ErrorRequestHandler, RequestHandler } from 'express';
|
||||
import { ZodError } from 'zod';
|
||||
|
||||
/**
|
||||
* /api/v2 errors all look the same:
|
||||
* { "error": { "code": "VALIDATION_FAILED", "message": "…", "fields": { "limit": "…" } } }
|
||||
* `code` is stable (clients switch on it), `message` is for people, `fields` only on validation.
|
||||
*/
|
||||
export type ErrorCode =
|
||||
| 'VALIDATION_FAILED'
|
||||
| 'UNAUTHENTICATED'
|
||||
| 'FORBIDDEN'
|
||||
| 'NOT_FOUND'
|
||||
| 'CONFLICT'
|
||||
| 'RATE_LIMITED'
|
||||
| 'READ_ONLY'
|
||||
| 'INTERNAL';
|
||||
|
||||
export const ERROR_STATUS: Record<ErrorCode, number> = {
|
||||
VALIDATION_FAILED: 400,
|
||||
UNAUTHENTICATED: 401,
|
||||
FORBIDDEN: 403,
|
||||
NOT_FOUND: 404,
|
||||
CONFLICT: 409,
|
||||
RATE_LIMITED: 429,
|
||||
READ_ONLY: 423,
|
||||
INTERNAL: 500,
|
||||
};
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly code: ErrorCode;
|
||||
readonly status: number;
|
||||
readonly fields?: Record<string, string>;
|
||||
|
||||
constructor(code: ErrorCode, message: string, fields?: Record<string, string>) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.status = ERROR_STATUS[code];
|
||||
this.fields = fields;
|
||||
}
|
||||
}
|
||||
|
||||
export const notFound = (what = 'That'): ApiError => new ApiError('NOT_FOUND', `${what} wasn't found.`);
|
||||
|
||||
/** "limit" or "items.0.quantity" → the first problem with it. */
|
||||
export function zodFields(err: ZodError): Record<string, string> {
|
||||
const fields: Record<string, string> = {};
|
||||
for (const issue of err.issues) {
|
||||
const key = issue.path.length ? issue.path.join('.') : '_';
|
||||
if (!fields[key]) fields[key] = issue.message;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
const STATUS_CODE: Record<number, ErrorCode> = { 400: 'VALIDATION_FAILED', 401: 'UNAUTHENTICATED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 409: 'CONFLICT', 423: 'READ_ONLY', 429: 'RATE_LIMITED' };
|
||||
const PRISMA_CODE: Record<string, ErrorCode> = { P2002: 'CONFLICT', P2025: 'NOT_FOUND', P2003: 'CONFLICT' };
|
||||
|
||||
type LegacyError = Error & { statusCode?: number; status?: number; code?: string };
|
||||
|
||||
/** Turns anything thrown (ApiError, zod, Prisma, the v1 auth middleware's errors) into the v2 shape. */
|
||||
export function toApiError(err: unknown, responseStatus: number): ApiError {
|
||||
if (err instanceof ApiError) return err;
|
||||
if (err instanceof ZodError) return new ApiError('VALIDATION_FAILED', 'Some of what was sent is not valid.', zodFields(err));
|
||||
const e = (err || {}) as LegacyError;
|
||||
if (typeof e.code === 'string' && PRISMA_CODE[e.code]) {
|
||||
return new ApiError(PRISMA_CODE[e.code], e.code === 'P2002' ? 'A record with that value already exists.' : e.code === 'P2025' ? 'Record not found.' : 'A related record prevents this.');
|
||||
}
|
||||
// The shared v1 middleware (protect, staff…) sets res.status() and passes an Error;
|
||||
// utils throw errors with statusCode. Those messages are written for people already.
|
||||
const status = e.statusCode || e.status || (responseStatus >= 400 ? responseStatus : 500);
|
||||
const code = STATUS_CODE[status];
|
||||
if (code) return new ApiError(code, e.message || 'Request failed.');
|
||||
return new ApiError('INTERNAL', 'Something went wrong on the server.');
|
||||
}
|
||||
|
||||
export const errorHandler: ErrorRequestHandler = (err, req, res, _next) => {
|
||||
const apiErr = toApiError(err, res.statusCode);
|
||||
if (apiErr.code === 'INTERNAL') console.error('[api/v2]', req.method, req.originalUrl, err);
|
||||
res.status(apiErr.status).json({ error: { code: apiErr.code, message: apiErr.message, ...(apiErr.fields ? { fields: apiErr.fields } : {}) } });
|
||||
};
|
||||
|
||||
export const notFoundHandler: RequestHandler = (_req, _res, next) => next(new ApiError('NOT_FOUND', 'There is no such API endpoint.'));
|
||||
@@ -0,0 +1,92 @@
|
||||
import express, { Router } from 'express';
|
||||
import path from 'path';
|
||||
import { mount, routes } from './route';
|
||||
import { buildOpenApi } from './openapi';
|
||||
import { errorHandler, notFoundHandler } from './errors';
|
||||
import auth from '../middleware/authMiddleware';
|
||||
// Resources: importing one registers its routes.
|
||||
import './resources/events';
|
||||
import './resources/me';
|
||||
|
||||
const pkg = require('../../package.json') as { version: string };
|
||||
|
||||
/** /api/v2 — see route.ts for how endpoints are declared, openapi.ts for the docs. */
|
||||
export function v2Router(): Router {
|
||||
const router = express.Router();
|
||||
|
||||
// The API description is for the people building on it (admins), like /docs.
|
||||
router.get('/openapi.json', auth.protect, auth.admin, (_req, res) => {
|
||||
res.json(buildOpenApi({ version: pkg.version }));
|
||||
});
|
||||
|
||||
mount(router, routes);
|
||||
router.use(notFoundHandler);
|
||||
router.use(errorHandler);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* /docs/v2: Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
||||
* public; it asks for an admin token and uses it to load openapi.json and to try requests.
|
||||
*/
|
||||
export function v2DocsRouter(): Router {
|
||||
const router = express.Router();
|
||||
const assets = path.dirname(require.resolve('swagger-ui-dist/package.json'));
|
||||
router.use('/assets', express.static(assets, { index: false, maxAge: '1d' }));
|
||||
router.get('/', (_req, res) => {
|
||||
res.type('html').send(DOCS_HTML);
|
||||
});
|
||||
return router;
|
||||
}
|
||||
|
||||
const DOCS_HTML = `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Cross Events API v2</title>
|
||||
<link rel="stylesheet" href="/docs/v2/assets/swagger-ui.css">
|
||||
<style>
|
||||
body { margin: 0; font-family: system-ui, sans-serif; }
|
||||
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
||||
#login input { width: 100%; padding: .5rem; font: inherit; border: 1px solid #9ca3af; border-radius: 6px; box-sizing: border-box; }
|
||||
#login button { margin-top: .75rem; padding: .5rem 1rem; font: inherit; background: #1d4ed8; color: #fff; border: 0; border-radius: 6px; cursor: pointer; }
|
||||
#login .err { color: #b91c1c; margin-top: .5rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="login" hidden>
|
||||
<h1>Cross Events API v2</h1>
|
||||
<p>The API reference is for admins. Paste your admin token (after signing in, it's under <code>hope_events_token</code> in the browser's local storage).</p>
|
||||
<label for="token">Admin token</label>
|
||||
<input id="token" autocomplete="off">
|
||||
<button id="go" type="button">Show the API</button>
|
||||
<p class="err" id="err" role="alert"></p>
|
||||
</main>
|
||||
<div id="ui"></div>
|
||||
<script src="/docs/v2/assets/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
var params = new URLSearchParams(location.search);
|
||||
var token = params.get('token') || sessionStorage.getItem('v2docs_token') || localStorage.getItem('hope_events_token') || '';
|
||||
function show(t) {
|
||||
fetch('/api/v2/openapi.json', { headers: { Authorization: 'Bearer ' + t } }).then(function (r) {
|
||||
if (!r.ok) return r.json().then(function (b) { throw new Error((b.error && b.error.message) || r.statusText); });
|
||||
return r.json();
|
||||
}).then(function (spec) {
|
||||
sessionStorage.setItem('v2docs_token', t);
|
||||
if (params.has('token')) history.replaceState(null, '', location.pathname);
|
||||
document.getElementById('login').hidden = true;
|
||||
var ui = SwaggerUIBundle({ spec: spec, dom_id: '#ui', deepLinking: true, persistAuthorization: false });
|
||||
ui.preauthorizeApiKey('bearerAuth', t);
|
||||
}).catch(function (e) {
|
||||
document.getElementById('login').hidden = false;
|
||||
document.getElementById('err').textContent = t ? 'That token did not work: ' + e.message : '';
|
||||
});
|
||||
}
|
||||
document.getElementById('go').addEventListener('click', function () { show(document.getElementById('token').value.trim()); });
|
||||
show(token);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Typed doors into the JavaScript side of the backend. TypeScript infers loose types from the
|
||||
* .js files (the Prisma client is built by a function, helpers have defaulted options), so v2
|
||||
* code imports them from here instead. When a module is converted to TypeScript, its line here
|
||||
* goes and callers import it directly.
|
||||
*/
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
|
||||
// The client in config/db.js only adds query hooks (webhooks), so its models are PrismaClient's.
|
||||
export const prisma = require('../config/db') as PrismaClient;
|
||||
|
||||
type CampusFilter = '' | 'all' | string;
|
||||
const campuses = require('../utils/campuses') as {
|
||||
campusesEnabled(): Promise<boolean>;
|
||||
resolveCampusFilter(value: string | undefined): Promise<CampusFilter>;
|
||||
campusWhere(filter: CampusFilter, opts: { enabled: boolean; withAllCampuses?: boolean }): object;
|
||||
};
|
||||
export const { campusesEnabled, resolveCampusFilter, campusWhere } = campuses;
|
||||
|
||||
export const { publicEventWhere } = require('../utils/series') as {
|
||||
publicEventWhere(now?: Date): { isActive: true; isHidden: false; goLiveAt: { lte: Date } };
|
||||
};
|
||||
|
||||
type OptionLike = { id: string; price: number; earlyBirdTiers?: unknown[] };
|
||||
export const { publicOptions } = require('../utils/volunteers') as {
|
||||
publicOptions<O extends { id: string }>(event: { eventOptions?: O[]; kidsOptionId?: string | null; volunteerOptionId?: string | null }): O[];
|
||||
};
|
||||
|
||||
export const { getEffectiveUnitPrice, computeRegistrationTotalDue } = require('../utils/pricing') as {
|
||||
getEffectiveUnitPrice(option: OptionLike, referenceTime: Date | null, atTime: Date): number;
|
||||
computeRegistrationTotalDue(registration: object, atTime: Date): number;
|
||||
};
|
||||
@@ -0,0 +1,106 @@
|
||||
import { z } from 'zod';
|
||||
import { routes as allRoutes, type AnyRoute, type Access } from './route';
|
||||
import { ERROR_STATUS } from './errors';
|
||||
|
||||
/**
|
||||
* The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is
|
||||
* always what the code does. Served at /api/v2/openapi.json, shown at /docs/v2.
|
||||
*/
|
||||
|
||||
type JsonSchema = Record<string, unknown>;
|
||||
|
||||
const toSchema = (schema: z.ZodType, io: 'input' | 'output'): JsonSchema => {
|
||||
const { $schema: _drop, ...rest } = z.toJSONSchema(schema, { io, unrepresentable: 'any' }) as JsonSchema;
|
||||
return rest;
|
||||
};
|
||||
|
||||
const ACCESS_TEXT: Record<Access, string> = {
|
||||
public: 'Anyone.',
|
||||
optional: 'Anyone; signed-in staff may see more.',
|
||||
user: 'Any signed-in person.',
|
||||
staff: 'Staff, supervisors and admins.',
|
||||
supervisor: 'Supervisors and admins.',
|
||||
admin: 'Admins only.',
|
||||
};
|
||||
|
||||
const errorSchema = {
|
||||
type: 'object',
|
||||
required: ['error'],
|
||||
properties: {
|
||||
error: {
|
||||
type: 'object',
|
||||
required: ['code', 'message'],
|
||||
properties: {
|
||||
code: { type: 'string', enum: Object.keys(ERROR_STATUS) },
|
||||
message: { type: 'string' },
|
||||
fields: { type: 'object', additionalProperties: { type: 'string' }, description: 'Per-field problems (VALIDATION_FAILED only)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const errorResponse = (description: string) => ({ description, content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } } });
|
||||
|
||||
function parameters(def: AnyRoute) {
|
||||
const out: JsonSchema[] = [];
|
||||
const add = (schema: z.ZodType | undefined, where: 'path' | 'query') => {
|
||||
if (!schema) return;
|
||||
const json = toSchema(schema, 'input') as { properties?: Record<string, JsonSchema>; required?: string[] };
|
||||
for (const [name, prop] of Object.entries(json.properties || {})) {
|
||||
const { description, ...propSchema } = prop as JsonSchema & { description?: string };
|
||||
out.push({ name, in: where, required: where === 'path' || (json.required || []).includes(name), ...(description ? { description } : {}), schema: propSchema });
|
||||
}
|
||||
};
|
||||
add(def.params, 'path');
|
||||
add(def.query, 'query');
|
||||
return out;
|
||||
}
|
||||
|
||||
export function buildOpenApi(opts: { version: string; serverUrl?: string; list?: AnyRoute[] }) {
|
||||
const list = opts.list ?? allRoutes;
|
||||
const paths: Record<string, Record<string, unknown>> = {};
|
||||
for (const def of list) {
|
||||
const path = def.path.replace(/:(\w+)/g, '{$1}');
|
||||
const secured = def.access !== 'public' && def.access !== 'optional';
|
||||
paths[path] ||= {};
|
||||
paths[path][def.method] = {
|
||||
tags: [def.tag],
|
||||
summary: def.summary,
|
||||
description: [def.description, `**Who:** ${ACCESS_TEXT[def.access]}`].filter(Boolean).join('\n\n'),
|
||||
operationId: `${def.method}${path.replace(/[{}]/g, '').split('/').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('')}`,
|
||||
...(secured ? { security: [{ bearerAuth: [] }] } : def.access === 'optional' ? { security: [{}, { bearerAuth: [] }] } : {}),
|
||||
parameters: parameters(def),
|
||||
...(def.body ? { requestBody: { required: true, content: { 'application/json': { schema: toSchema(def.body, 'input') } } } } : {}),
|
||||
responses: {
|
||||
[String(def.status ?? 200)]: { description: 'OK', content: { 'application/json': { schema: toSchema(def.response, 'output') } } },
|
||||
...(def.params || def.query || def.body ? { 400: errorResponse('Validation failed (VALIDATION_FAILED)') } : {}),
|
||||
...(secured ? { 401: errorResponse('Not signed in (UNAUTHENTICATED)') } : {}),
|
||||
...(secured && def.access !== 'user' ? { 403: errorResponse('Not allowed for this role (FORBIDDEN)') } : {}),
|
||||
...(def.params ? { 404: errorResponse('Not found (NOT_FOUND)') } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: 'Cross Events API',
|
||||
version: opts.version,
|
||||
description: [
|
||||
'Version 2 of the Cross Events API. Every response is JSON:',
|
||||
'- a single item is `{ "data": { … } }`;',
|
||||
'- a list is `{ "data": [ … ], "meta": { "page", "limit", "total", "pages" } }`, paged with `?page=` and `?limit=` (at most 100);',
|
||||
'- an error is `{ "error": { "code", "message", "fields"? } }` with a stable `code`.',
|
||||
'',
|
||||
'Dates are ISO 8601 in UTC; amounts are in rand. Sign in through the app and send the token as `Authorization: Bearer <token>`.',
|
||||
'Version 1 (`/api/…`) keeps working while the app moves over; it will be removed in 2.0.',
|
||||
].join('\n'),
|
||||
},
|
||||
servers: [{ url: opts.serverUrl ?? '/api/v2' }],
|
||||
tags: Array.from(new Set(list.map(r => r.tag))).map(name => ({ name })),
|
||||
paths,
|
||||
components: {
|
||||
securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } },
|
||||
schemas: { Error: errorSchema },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/** `?page=2&limit=25` on every v2 list (limit 1–100, default 25). */
|
||||
export const pageQuery = z.object({
|
||||
page: z.coerce.number().int().min(1).default(1).describe('Page number, from 1'),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(25).describe('Items per page (at most 100)'),
|
||||
});
|
||||
export type PageQuery = z.infer<typeof pageQuery>;
|
||||
|
||||
export const pageMeta = z.object({
|
||||
page: z.number().int(),
|
||||
limit: z.number().int(),
|
||||
total: z.number().int().describe('Items across all pages'),
|
||||
pages: z.number().int().describe('Number of pages (at least 1)'),
|
||||
});
|
||||
|
||||
/** The response shape of a v2 list: `{ data: [...], meta: { page, limit, total, pages } }`. */
|
||||
export const paged = <T extends z.ZodType>(item: T) => z.object({ data: z.array(item), meta: pageMeta });
|
||||
|
||||
/** The response shape of a single v2 resource: `{ data: {...} }`. */
|
||||
export const single = <T extends z.ZodType>(item: T) => z.object({ data: item });
|
||||
|
||||
/** Prisma's skip/take for a page. */
|
||||
export const skipTake = ({ page, limit }: PageQuery) => ({ skip: (page - 1) * limit, take: limit });
|
||||
|
||||
export function pageOf<T>(data: T[], total: number, { page, limit }: PageQuery) {
|
||||
return { data, meta: { page, limit, total, pages: Math.max(1, Math.ceil(total / limit)) } };
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { z } from 'zod';
|
||||
import { defineRoute } from '../route';
|
||||
import { notFound } from '../errors';
|
||||
import { pageQuery, paged, single, skipTake, pageOf } from '../paging';
|
||||
import { absoluteUrl, campusRef, id, idParams, iso, isoDate, seriesRef } from '../schemas';
|
||||
import { prisma, campusesEnabled, campusWhere, resolveCampusFilter, publicEventWhere, publicOptions, getEffectiveUnitPrice } from '../legacy';
|
||||
|
||||
const eventSummary = z.object({
|
||||
id,
|
||||
title: z.string(),
|
||||
startDate: isoDate,
|
||||
endDate: isoDate,
|
||||
location: z.string().nullable(),
|
||||
price: z.number().describe('The headline price in rand (0 = free)'),
|
||||
pictureUrl: z.string().nullable(),
|
||||
requiresRegistration: z.boolean(),
|
||||
scheduleType: z.enum(['single', 'sessions']),
|
||||
campus: campusRef.nullable().describe('null = for all campuses (or campuses are off)'),
|
||||
series: seriesRef.nullable(),
|
||||
});
|
||||
|
||||
const ticketOption = z.object({
|
||||
id,
|
||||
name: z.string(),
|
||||
price: z.number().describe('The normal price in rand'),
|
||||
currentPrice: z.number().describe('What it costs now (an early-bird price while one runs)'),
|
||||
isMainTicket: z.boolean(),
|
||||
sessionMode: z.enum(['all', 'pick']).describe('"pick" = the buyer chooses sessions'),
|
||||
});
|
||||
|
||||
const session = z.object({
|
||||
id,
|
||||
label: z.string().nullable(),
|
||||
startsAt: isoDate,
|
||||
endsAt: isoDate,
|
||||
location: z.string().nullable(),
|
||||
cancelled: z.boolean(),
|
||||
});
|
||||
|
||||
const eventDetail = eventSummary.extend({
|
||||
description: z.string().nullable(),
|
||||
registrationDeadline: isoDate.nullable(),
|
||||
ticketOptions: z.array(ticketOption),
|
||||
sessions: z.array(session).describe('Multi-day events only; empty otherwise'),
|
||||
});
|
||||
|
||||
const SUMMARY_SELECT = {
|
||||
id: true, title: true, startDate: true, endDate: true, location: true, price: true, picture: true,
|
||||
requiresRegistration: true, scheduleType: true,
|
||||
campus: { select: { id: true, name: true, slug: true } },
|
||||
series: { select: { id: true, name: true, slug: true } },
|
||||
} as const;
|
||||
|
||||
type SummaryRow = {
|
||||
id: string; title: string; startDate: Date; endDate: Date; location: string | null; price: number; picture: string | null;
|
||||
requiresRegistration: boolean; scheduleType: 'single' | 'sessions';
|
||||
campus: { id: string; name: string; slug: string } | null; series: { id: string; name: string; slug: string } | null;
|
||||
};
|
||||
|
||||
const toSummary = (req: Parameters<typeof absoluteUrl>[0], e: SummaryRow): z.input<typeof eventSummary> => ({
|
||||
id: e.id, title: e.title, startDate: iso(e.startDate), endDate: iso(e.endDate), location: e.location ?? null,
|
||||
price: e.price, pictureUrl: absoluteUrl(req, e.picture), requiresRegistration: e.requiresRegistration,
|
||||
scheduleType: e.scheduleType, campus: e.campus ?? null, series: e.series ?? null,
|
||||
});
|
||||
|
||||
export const listEvents = defineRoute({
|
||||
method: 'get',
|
||||
path: '/events',
|
||||
tag: 'Events',
|
||||
summary: 'Upcoming public events',
|
||||
description: 'Events anyone can see (active, not hidden, live) that have not ended, soonest first.',
|
||||
access: 'public',
|
||||
query: pageQuery.extend({
|
||||
q: z.string().trim().max(100).optional().describe('Search the title'),
|
||||
campus: z.string().max(64).optional().describe("A campus id or slug (its events plus church-wide ones), or 'all' for church-wide events only"),
|
||||
series: z.string().max(120).optional().describe('A series slug'),
|
||||
}),
|
||||
response: paged(eventSummary),
|
||||
async handler({ query, req }) {
|
||||
const now = new Date();
|
||||
const enabled = await campusesEnabled();
|
||||
const and: object[] = [publicEventWhere(now), { endDate: { gte: now } }];
|
||||
if (query.campus) and.push(campusWhere(await resolveCampusFilter(query.campus), { enabled, withAllCampuses: true }));
|
||||
if (query.series) and.push({ series: { slug: query.series } });
|
||||
if (query.q) and.push({ title: { contains: query.q, mode: 'insensitive' } });
|
||||
const where = { AND: and };
|
||||
const [rows, total] = await Promise.all([
|
||||
prisma.event.findMany({ where, select: SUMMARY_SELECT, orderBy: [{ startDate: 'asc' }, { id: 'asc' }], ...skipTake(query) }),
|
||||
prisma.event.count({ where }),
|
||||
]);
|
||||
return pageOf((rows as SummaryRow[]).map(e => toSummary(req, e)), total, query);
|
||||
},
|
||||
});
|
||||
|
||||
export const getEvent = defineRoute({
|
||||
method: 'get',
|
||||
path: '/events/:id',
|
||||
tag: 'Events',
|
||||
summary: 'One public event',
|
||||
description: 'With its ticket options (internal kids check-in and volunteer tickets left out) and sessions. Hidden events can be fetched by id (they are unlisted, not private).',
|
||||
access: 'public',
|
||||
params: idParams,
|
||||
response: single(eventDetail),
|
||||
async handler({ params, req }) {
|
||||
const now = new Date();
|
||||
const { isHidden: _hiddenOk, ...visible } = publicEventWhere(now);
|
||||
const e = await prisma.event.findFirst({
|
||||
where: { id: params.id, ...visible },
|
||||
select: {
|
||||
...SUMMARY_SELECT, description: true, registrationDeadline: true, kidsOptionId: true, volunteerOptionId: true,
|
||||
eventOptions: { include: { earlyBirdTiers: true }, orderBy: [{ isMainTicket: 'desc' }, { name: 'asc' }] },
|
||||
sessions: { orderBy: { startsAt: 'asc' } },
|
||||
},
|
||||
});
|
||||
if (!e) throw notFound('That event');
|
||||
const options = publicOptions(e);
|
||||
return {
|
||||
data: {
|
||||
...toSummary(req, e as unknown as SummaryRow),
|
||||
description: e.description ?? null,
|
||||
registrationDeadline: iso(e.registrationDeadline),
|
||||
ticketOptions: options.map(o => ({
|
||||
id: o.id, name: o.name, price: o.price, currentPrice: getEffectiveUnitPrice(o, null, now),
|
||||
isMainTicket: o.isMainTicket, sessionMode: o.sessionMode,
|
||||
})),
|
||||
sessions: e.sessions.map(s => ({ id: s.id, label: s.label, startsAt: iso(s.startsAt), endsAt: iso(s.endsAt), location: s.location, cancelled: !!s.cancelledAt })),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { z } from 'zod';
|
||||
import { defineRoute } from '../route';
|
||||
import { ApiError } from '../errors';
|
||||
import { pageQuery, paged, single, skipTake, pageOf } from '../paging';
|
||||
import { eventRef, id, iso, isoDate } from '../schemas';
|
||||
import { prisma, computeRegistrationTotalDue } from '../legacy';
|
||||
|
||||
const me = z.object({
|
||||
id,
|
||||
name: z.string(),
|
||||
email: z.string(),
|
||||
phone: z.string().nullable(),
|
||||
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
|
||||
twoFactorEnabled: z.boolean(),
|
||||
createdAt: isoDate,
|
||||
});
|
||||
|
||||
export const getMe = defineRoute({
|
||||
method: 'get',
|
||||
path: '/me',
|
||||
tag: 'Me',
|
||||
summary: 'The signed-in person',
|
||||
access: 'user',
|
||||
response: single(me),
|
||||
async handler({ user }) {
|
||||
const u = await prisma.user.findUnique({
|
||||
where: { id: user!.id },
|
||||
select: { id: true, name: true, email: true, phoneNumber: true, role: true, twoFactorEnabled: true, createdAt: true },
|
||||
});
|
||||
if (!u) throw new ApiError('UNAUTHENTICATED', 'User not found');
|
||||
return { data: { id: u.id, name: u.name, email: u.email, phone: u.phoneNumber ?? null, role: u.role, twoFactorEnabled: !!u.twoFactorEnabled, createdAt: iso(u.createdAt) } };
|
||||
},
|
||||
});
|
||||
|
||||
const STATUSES = ['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled'] as const;
|
||||
|
||||
const myRegistration = z.object({
|
||||
id,
|
||||
status: z.enum(STATUSES),
|
||||
createdAt: isoDate,
|
||||
event: eventRef,
|
||||
items: z.array(z.object({
|
||||
ticket: z.string(),
|
||||
variant: z.string().nullable(),
|
||||
quantity: z.number().int(),
|
||||
unitPrice: z.number(),
|
||||
})),
|
||||
totalDue: z.number().describe('In rand, after discounts'),
|
||||
amountPaid: z.number().describe('In rand (refunds subtracted)'),
|
||||
balance: z.number().describe('totalDue − amountPaid; 0 or less = nothing owing'),
|
||||
});
|
||||
|
||||
const r2 = (n: number) => Math.round(n * 100) / 100;
|
||||
|
||||
export const listMyRegistrations = defineRoute({
|
||||
method: 'get',
|
||||
path: '/me/registrations',
|
||||
tag: 'Me',
|
||||
summary: 'My registrations',
|
||||
description: 'Newest first. By default only ones for events that have not ended, and not cancelled; `past=true` lists everything.',
|
||||
access: 'user',
|
||||
query: pageQuery.extend({
|
||||
past: z.enum(['true', 'false']).default('false').transform(v => v === 'true').describe('Include past and cancelled registrations'),
|
||||
}),
|
||||
response: paged(myRegistration),
|
||||
async handler({ query, user }) {
|
||||
const now = new Date();
|
||||
const where = query.past
|
||||
? { userId: user!.id }
|
||||
: { userId: user!.id, status: { not: 'cancelled' as const }, event: { endDate: { gte: now } } };
|
||||
const [rows, total] = await Promise.all([
|
||||
prisma.registration.findMany({
|
||||
where,
|
||||
include: {
|
||||
event: { select: { id: true, title: true, startDate: true, endDate: true } },
|
||||
registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, variant: { select: { name: true, price: true } }, tranches: true } },
|
||||
payments: { select: { amount: true, createdAt: true } },
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
...skipTake(query),
|
||||
}),
|
||||
prisma.registration.count({ where }),
|
||||
]);
|
||||
return pageOf(rows.map(r => {
|
||||
const totalDue = r2(computeRegistrationTotalDue(r, now));
|
||||
const amountPaid = r2(r.payments.reduce((s, p) => s + p.amount, 0));
|
||||
return {
|
||||
id: r.id,
|
||||
status: r.status,
|
||||
createdAt: iso(r.createdAt),
|
||||
event: { id: r.event.id, title: r.event.title, startDate: iso(r.event.startDate), endDate: iso(r.event.endDate) },
|
||||
items: r.registrationOptions.map(o => ({ ticket: o.eventOption?.name ?? '', variant: o.variant?.name ?? null, quantity: o.quantity, unitPrice: o.priceSnapshot ?? o.eventOption?.price ?? 0 })),
|
||||
totalDue,
|
||||
amountPaid,
|
||||
balance: r2(totalDue - amountPaid),
|
||||
};
|
||||
}), total, query);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
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<P, Q, B> = {
|
||||
params: P;
|
||||
query: Q;
|
||||
body: B;
|
||||
user: ApiUser | null;
|
||||
req: Request;
|
||||
res: Response;
|
||||
};
|
||||
|
||||
type Schema = z.ZodType;
|
||||
type Infer<S> = S extends z.ZodType ? z.infer<S> : undefined;
|
||||
|
||||
export type RouteDef<P extends Schema | undefined, Q extends Schema | undefined, B extends Schema | undefined, R extends Schema> = {
|
||||
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;
|
||||
handler: (ctx: Ctx<Infer<P>, Infer<Q>, Infer<B>>) => Promise<z.input<R>> | z.input<R>;
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export type AnyRoute = RouteDef<any, any, any, any>;
|
||||
|
||||
export const routes: AnyRoute[] = [];
|
||||
|
||||
const ACCESS: Record<Access, RequestHandler[]> = {
|
||||
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<P extends Schema | undefined, Q extends Schema | undefined, B extends Schema | undefined, R extends Schema>(def: RouteDef<P, Q, B, R>): RouteDef<P, Q, B, R> {
|
||||
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 = <S extends Schema | undefined>(schema: S, value: unknown): Infer<S> =>
|
||||
(schema ? schema.parse(value) : undefined) as Infer<S>;
|
||||
|
||||
/** 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], run);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from 'zod';
|
||||
import type { Request } from 'express';
|
||||
|
||||
/** Shared pieces of v2 schemas. Dates go out as ISO 8601 strings (UTC). */
|
||||
|
||||
export const isoDate = z.iso.datetime();
|
||||
export const id = z.string().min(1).max(64);
|
||||
export const idParams = z.object({ id: id.describe('The id') });
|
||||
|
||||
/** A Date (or date string) as ISO 8601, for building responses. */
|
||||
export function iso(d: Date | string): string;
|
||||
export function iso(d: Date | string | null | undefined): string | null;
|
||||
export function iso(d: Date | string | null | undefined): string | null {
|
||||
return d == null ? null : new Date(d).toISOString();
|
||||
}
|
||||
|
||||
/** A stored picture path ("/uploads/…") as an absolute URL on the host the request came to. */
|
||||
export function absoluteUrl(req: Request, url: string | null | undefined): string | null {
|
||||
const raw = String(url || '').trim();
|
||||
if (!raw) return null;
|
||||
if (/^https?:\/\//.test(raw)) return raw;
|
||||
return `${req.protocol}://${req.get('host')}${raw.startsWith('/') ? '' : '/'}${raw}`;
|
||||
}
|
||||
|
||||
export const campusRef = z.object({ id, name: z.string(), slug: z.string() });
|
||||
export const seriesRef = z.object({ id, name: z.string(), slug: z.string() });
|
||||
export const eventRef = z.object({ id, title: z.string(), startDate: isoDate, endDate: isoDate });
|
||||
Reference in New Issue
Block a user