Controllers
An app adds REST routes of its own with @routup/decorators controllers, the classes chamvi's own REST API is built from. A module contributes a controller instance; chamvi serves it under basePath behind its own request pipeline: the authenticators (when a method asks for them), the rate limiter, the body limits, the JSON error renderer and the metrics.
npm install @routup/decorators@routup/decorators (^5.3.0) is a peer dependency of @chamvi/http and @chamvi/app: the app's decorators write the metadata chamvi reads, so npm must resolve one copy. npm 7 and later and pnpm 8 and later install it by themselves; a package manager that does not install peers (npm with --legacy-peer-deps, Yarn Berry, pnpm before 8) needs it in the app's package.json, otherwise the app fails at startup with a module-not-found error. Decorators need experimentalDecorators: true in the app's tsconfig.json.
A controller over a service
The controller reads the request (path, query, body, the principal) and calls one service method. It holds no permission check and no validation: its service does, as chamvi's own controllers and services split the work. The service checks with assertGranted(principal, clock, permission, attributes?), which throws 403 when the principal lacks the permission:
// src/core/note/service.ts: the permission checks and the validation live here, never in the controller
import { assertGranted } from '@chamvi/app';
import type { IClock, Principal } from '@chamvi/app';
import { BadRequestError, NotFoundError } from '@ebec/http';
import { isObject } from 'smob';
export type Note = {
id: string;
text: string;
};
// an app's own names: grant them as bindings, `"*"` covers chamvi's names only
export const NOTE_READ = 'note_read';
export const NOTE_WRITE = 'note_write';
export class NoteService {
protected clock: IClock;
// the app's own storage, e.g. a repository over its own TypeORM data source
protected notes = new Map<string, Note>();
constructor(ctx: { clock: IClock }) {
this.clock = ctx.clock;
}
count(): number {
return this.notes.size;
}
async getOne(principal: Principal, id: string): Promise<Note> {
await assertGranted(principal, this.clock, NOTE_READ);
const note = this.notes.get(id);
if (!note) {
throw new NotFoundError({ message: `The note "${id}" does not exist.` });
}
return note;
}
async create(principal: Principal, body: unknown): Promise<Note> {
await assertGranted(principal, this.clock, NOTE_WRITE);
if (!isObject(body) || typeof body.text !== 'string' || body.text.length === 0) {
throw new BadRequestError({ message: 'text must be a non-empty string.' });
}
const note = { id: crypto.randomUUID(), text: body.text };
this.notes.set(note.id, note);
return note;
}
}"*" in TOKENS grants every chamvi permission, not an app's own names: grant note_read and note_write as bindings (a token's list, or authup).
// src/adapters/http/controllers/note.ts: reads the request, calls one service method
import { ForceLoggedInMiddleware, RequiredJsonBodyMiddleware, usePrincipal } from '@chamvi/app';
import {
DBody,
DContext,
DController,
DGet,
DPath,
DPost,
DStatus,
} from '@routup/decorators';
import type { IAppEvent } from 'routup';
import type { Note, NoteService } from '../../../core/note/service.ts';
@DController('/notes')
export class NoteController {
protected service: NoteService;
constructor(ctx: { service: NoteService }) {
this.service = ctx.service;
}
// no middleware and no check in the service: unauthenticated.
// Declared before /:id, which would otherwise answer GET /notes/count
@DGet('/count')
async count(): Promise<{ count: number }> {
return { count: this.service.count() };
}
// 401 without a principal; the service answers 403 without note_read
@DGet('/:id', [ForceLoggedInMiddleware])
async get(@DPath('id') id: string, @DContext() event: IAppEvent): Promise<Note> {
return this.service.getOne(await usePrincipal(event), id);
}
// logged in, a JSON body of at most the app's bodyLimit (400, 413, 415)
@DPost('', [RequiredJsonBodyMiddleware])
@DStatus(201)
async create(@DBody() body: unknown, @DContext() event: IAppEvent): Promise<Note> {
return this.service.create(await usePrincipal(event), body);
}
}The decorators come from @routup/decorators; the request helpers come from @chamvi/app (and @chamvi/http):
| Helper | Does |
|---|---|
usePrincipal(event) | The request's principal; 401 (with WWW-Authenticate: Bearer) without one. The authenticator chain runs once per request |
authorizeRequest(event, permission?, attributes?) | usePrincipal, then 403 unless the principal holds permission: for the resource attributes when given, else for some resource. The same check as an HttpRoute's request.authorize() |
assertGranted(principal, clock, permission, attributes?) | The check without the event, for a service |
toInvoker(principal) | The principal as a run's invoker, e.g. for engine.dispatch() |
ForceLoggedInMiddleware | A method middleware (@DGet('/x', [ForceLoggedInMiddleware])): 401 without a principal |
JsonBodyMiddleware, RequiredJsonBodyMiddleware | Resolve the principal (401), then read a JSON body for @DBody() within the app's bodyLimit: 413 above it, 415 for a missing or another media type (application/json and application/*+json pass), 400 for a malformed Content-Type; the required one also answers 400 without a body. @DBody() needs one of them on the method, otherwise the body is {} |
Authentication is opt-in per method. A method is unauthenticated unless it uses ForceLoggedInMiddleware, a body middleware, or its service authorizes. GET /notes/count above answers anyone.
Contributing it
A module registers a factory on AppToken.HTTP_CONTROLLERS in setup:
// src/app/modules/note.ts: builds the controller from the container's values
import { existsSync, readFileSync } from 'node:fs';
import { AppToken } from '@chamvi/app';
import type { IContainer, IModule } from '@chamvi/app';
import { NoteController } from '../../adapters/http/controllers/note.ts';
import { NoteService } from '../../core/note/service.ts';
// written by `trapi generate` (trapi.config.ts) beside package.json; read relative to the
// working directory, the app's root for `chamvi dev`, `chamvi start` and the image
const OPENAPI_DOCUMENT = 'openapi.json';
export function noteModule(): IModule {
return {
name: 'note',
async setup(container: IContainer) {
// the factory runs once, when the http module resolves the token in onReady
// (start mode and a check), after every module's setup
container.registerMany(AppToken.HTTP_CONTROLLERS, {
useFactory: (c) => {
const service = new NoteService({ clock: c.resolve(AppToken.CLOCK) });
return new NoteController({ service });
},
});
if (existsSync(OPENAPI_DOCUMENT)) {
container.registerMany(AppToken.OPENAPI_DOCUMENTS, { useValue: JSON.parse(readFileSync(OPENAPI_DOCUMENT, 'utf8')) as object });
}
},
};
}The factory runs once, when the http module resolves the token in its onReady, after every module's setup, so it can resolve anything another module registered (CLOCK, ENGINE, LOGGER, your own tokens). It runs only in start mode, a check (chamvi start --check) included; runJob() and migrate() never build a controller. httpModule({ controllers }) takes instances directly and mounts them before the token's; without @chamvi/app, pass them to createHttpApp({ controllers: [new NoteController({ service })] }).
A suggested layout, which follows authup and which chamvi does not enforce: the domain in src/core/<entity>/service.ts, the controller in src/adapters/http/controllers/<entity>.ts and the module in src/app/modules/<entity>.ts. An app keeps its own data source for its own tables (Database); chamvi's store takes no contributed entities.
chamvi build compiles the decorators with the app's tsconfig.json. chamvi dev and chamvi start --entry src/index.ts run a decorated entry from source through the CLI's TypeScript entries hooks: they need "experimentalDecorators": true in the tsconfig.json the build finds (the nearest one at or above the working directory), "type": "module" in the app's package.json, and tsdown installed.
Paths
The app is built at construction, so a breach fails the start and chamvi start --check with InvalidAgentDefinitionError:
- Each
@DControllerbase path (a string or an array) is a static path starting with/(letters, digits,_,.,~,-; no parameters), whose first segment is not a built-in one (agents,authorization,channels,connection-types,connections,docs,healthz,mcp,me,openapi.json,readyz,runs,schedules,ui-pages), and which is neither the metrics path nor above it (with metrics on). Paths compare case-sensitively, as routup matches them:/Notesand/notesare two paths. - A controller lists each base path once; two controllers may share one.
- A method path is
''(the base path itself) or a path that routup joins under the base path with a slash, so:idand/:idboth mean/notes/:id. A method path routup cannot parse is refused. - No extra route (
HttpRoute, such as the dashboard's), of any method, lies at or under a base path, and no base path lies at or under an extra prefix route: controllers are mounted first and would shadow it. So/notesand/notes-archivestay apart, while anHttpRoutePOST /notes/hookbeside a/notescontroller and a/ui/notescontroller beside the prefix route/uiare refused. - The class must be decorated with
@DControllerand contributed as an instance, not as the class.
Routes match in declaration order, as routup answers with the first match: declare a static route (/count) before a parameter route of the same shape (/:id). A route declared twice, in one controller or across several, is answered by the first; a later one runs only when the first hands over with event.next(). Document such a route once: the OpenAPI merge refuses the same operation from two contributed documents.
A class-level middleware (@DController('/notes', [ForceLoggedInMiddleware])) runs for every request under the controller's base path, unmatched paths included: keep ForceLoggedInMiddleware on the methods unless the whole base path is the controller's.
Requests
- Rate limit: contributed routes are always limited by the app's limiter (
rateLimit, 300 per minute per client by default). A caller that must not be limited, a webhook sender that never retries for example, stays anHttpRoutewithrateLimit: false, or becomes a channel. - Errors: throw
@ebec/httperrors (NotFoundError,ConflictError, ...), or classes of your own that extend them with their owncode; they render as{ status, code, message, issues? }with the code lowercased. A validup error renders as 400validation_errorwith its issues, and a core error (ValidationError,RunNotFoundError, ...) as in every other route. Anything else is a 500Internal Server Errorwhose cause goes toonError, never to the client. There is no seam to map other errors: catch and rethrow in the service. - Metrics: the
pathlabel of a contributed route is the pattern of the route that served the request (/notes/:id, withoutbasePath), never the request path; a method the controller does not declare for the path, and anOPTIONSrequest, are labelled/_unmatched.
OpenAPI document
chamvi's /openapi.json and /docs describe its own routes. An app adds its controllers to them with a document of its own, generated with trapi (npm install @trapi/cli --save-dev) and the @routup/decorators/preset, with paths relative to basePath like chamvi's:
// trapi.config.ts, next to package.json: `trapi generate` writes openapi.json beside it,
// outside dist (`chamvi build` refuses an out dir holding files it did not write)
import { defineConfig } from '@trapi/cli';
export default defineConfig({
metadata: {
entryPoint: ['src/adapters/http/controllers/*.ts'],
// reads @DController, @DGet, @DStatus, ... of @routup/decorators
preset: '@routup/decorators/preset',
tsconfig: 'tsconfig.json',
},
swagger: {
version: 'v3.2',
// info and servers stay chamvi's: only paths, tags and components are merged
data: { name: 'notes', version: '1.0.0' },
},
output: { path: 'openapi.json' },
});The document goes to openapi.json beside package.json, never into dist: chamvi build refuses an out dir holding a file it did not write. Run trapi generate in the image build too and copy openapi.json into the final image beside dist (the module reads it relative to the working directory, the app's root). Contribute the parsed document through AppToken.OPENAPI_DOCUMENTS, as the module above does, or through httpModule({ openapi: { documents } }) (createHttpApp({ openapi: { documents } })); the option's documents merge first. With openapi: false both are ignored.
paths,tagsandcomponents(every group:schemas,securitySchemes, ...) are merged into chamvi's document;info,serversand every other top-level key stay chamvi's.- Paths merge per path and method, method keys compared case-insensitively; the methods of OpenAPI 3.2's
additionalOperations(COPY, ...) merge the same way, kept as written, and one that has a fixed field (POST,query) is refused. A method already in chamvi's document or in another contributed one is refused, as is a different path-level field (parameters,summary, ...) for the same path. Paths that differ only in parameter names (/notes/{id},/notes/{noteId}) are refused: use one template, with the same parameter names, for every operation on it. - A contributed document's top-level
securityis not applied: each operation carries its own. - A path, path-level field,
additionalOperationsmethod, component group or component name__proto__,constructororprototypeis refused. - A component name that exists with a different definition is refused; an identical one is kept once. Tags merge by name, and the first description wins.
A refusal is an InvalidAgentDefinitionError at construction, so it also fails chamvi start --check. The contributed documents are checked against each other even when chamvi's own document is missing.
HttpRoute or a controller
HttpRoute (AppToken.HTTP_ROUTES) stays: it suits a small static route without decorators, such as the dashboard's files, and the routes a caller must reach without the rate limit. A controller suits an API with parameters, bodies and services.