Docs/Controllers
HTTP Method Decorators
Controllers are plain TypeScript classes decorated with HTTP method decorators.
HTTP Method Decorators
import { get, query, post, put, patch, del, head } from 'alado';| Decorator | Method |
|---|---|
@get(path, options?) |
GET |
@query(path, options?) |
QUERY |
@post(path, options?) |
POST |
@put(path, options?) |
PUT |
@patch(path, options?) |
PATCH |
@del(path, options?) |
DELETE |
@head(path, options?) |
HEAD |
Paths are case-sensitive by default (/Users does not match /users); a trailing slash and repeated slashes are ignored. See caseSensitiveRoutes in Security Defaults.
A request whose path matches a route but not its method gets 405 Method Not Allowed with an Allow header listing the methods the path accepts; a path no route matches gets 404.
HEAD is answered by the GET route of the path when there is no HEAD route: the GET handler runs and its status and headers (including Content-Length) are sent without the body. A stream body is closed without being read. Allow lists HEAD wherever GET is. Declare a @head route to answer it differently.
Absolute-form request targets (GET http://example.com/items?x=1 HTTP/1.1, sent by some proxies and older clients, RFC 9112 §3.2.2) are routed like /items?x=1; req.url holds the path and query only.
Path parameters reach the handler URL-decoded: /users/john%20doe gives req.path.id === 'john doe', and an encoded slash stays inside the parameter (a%2Fb gives 'a/b'). Malformed encoding gets 400 Malformed path parameter.
Path parameters need a path DTO.
req.pathholds only the parameters declared with@defineRequest({ path: ... }): on/orders/:idwithout one,req.pathis{}andreq.path.idisundefined, like any other undeclared request field. Declare each parameter the handler reads, with its validator.
A parameter (:id) runs to the end of its path segment, and its name is made of letters, digits, _ and -.
Registration rules
Routes are registered in declaration order. These mistakes stop the application at startup instead of producing a route that silently never runs:
- The same method and path twice. Also when only the parameter names differ (
/users/:idand/users/:userId). ThrowsAladoConfigurationErrorwithcode: 'ROUTE_ALREADY_REGISTERED'. - A
GETorHEADroute on a path the OpenAPI docs serve (the docs page, itsswagger.json, a Swagger UI file). ThrowsAladoConfigurationErrorwithcode: 'ROUTE_RESERVED_FOR_OPEN_API'. - A body on a method without one. A
GET,HEAD,DELETEorOPTIONSroute that declaresbodyorfilesfields,rawBody: true, or readsbody.*in auth or access control. ThrowsAladoConfigurationErrorwithcode: 'BODY_NOT_ALLOWED'. - A path parameter with a malformed or repeated name.
/files/:name.jsonwould declare a parameter calledname.json(matchingreport.xmltoo), and/orgs/:id/users/:idkeeps one value only. ThrowsAladoConfigurationErrorwithcode: 'INVALID_PATH_PARAMETER'. - An access-control rule that is misspelled or checks nothing. See Access Control.
- The same header declared twice in different letter case in one route's DTOs, auth or access rules. Throws
AladoConfigurationErrorwithcode: 'HEADER_DECLARED_TWICE'. - The same decorator twice on one method or DTO property. A second
@withAuth,@accessControl,@defineRequestor@defineResponseon one method (3.9.7), or a second@validateProperty,@transformPropertyor@documentPropertyon one property, or@fileUploadPropertytogether with any of them (3.9.8), would replace the first one's setting: two@accessControlwould keep the rules of one only, two@validatePropertyone of the checks. ThrowsAladoConfigurationErrorwithcode: 'DECORATOR_REPEATED'. Pass every strategy to one@withAuth, every rule to one@accessControland combine checks in one validator. A subclass may decorate an overridden method or an inherited property again. - A route decorator below other decorators. Decorators apply bottom-up, so
@get,@post, ... must be the top-most decorator of the method. When the application already exists, a@withAuth,@accessControl,@defineRequestor@defineResponseplaced above it throws instead of being dropped (a dropped@withAuthwould leave the route without authentication).
One handler can serve several routes: route decorators stacked at the top of one method (@post('/a') above @post('/b/c')) register a route each, and every one of them gets the method's @withAuth, @accessControl, @defineRequest and @defineResponse.
import { AladoConfigurationError } from 'alado';
try {
initializeApplication({ serverOptions, controllers });
} catch (e) {
if (e instanceof AladoConfigurationError && e.code === 'ROUTE_ALREADY_REGISTERED') {
// e.message names both routes
}
throw e;
}Options:
type HttpDecoratorOptions = {
appId?: string;
title?: string;
description?: string;
isHidden?: boolean | undefined;
disable?: boolean; // true: the route is switched off (3.11.0)
tags?: string[];
rawBody?: boolean; // read the body without body/files fields: req.rawBody is set
maxBodySizeBytes?: number; // this route's body limit, instead of the server's; 0 removes it
};maxBodySizeBytes sets the body limit of one route in place of the server's maxBodySizeBytes (0 removes it): raise it on an upload route alone, so every other route keeps the small default. A body nobody reads is still measured against the server's limit. The same option goes in Context.options.maxBodySizeBytes for routes registered without decorators.
rawBody: true is for routes that need the body text but declare no body or files fields, such as a webhook that checks a signature. Without it such a route never reads the body. See @defineRequest.
Switching a route off
disable: true (3.11.0) switches a route off instead of commenting it out: the method and its decorators stay in the code, compiled and type-checked, and the route is not registered.
@post('/user/import', { tags: ['User'], disable: true })
@withAuth(bearerAuth)
@defineRequest({ body: CreateUserDto })
@defineResponse({ statusCode: 201, headers: json, body: exampleUser })
async import(req: Request) {
// ...
}A disabled route has no handler, no auth or access checks and no place in the OpenAPI document. A request to it gets what an undeclared route gets: 404, or 405 when another route serves the same path with another method (POST /user/import above, next to GET /user/:id). Its path is free for another route. The method's decorators are still checked as for any route (one @defineRequest, the HTTP decorator above the others), so a mistake in them shows up before the route is switched back on. Deleting disable: true brings the route back.
isHidden: true is a different thing: the route keeps working and is only left out of the docs.
Example:
@get('/users', { tags: ['User'], title: 'List users' })
async list(req: Request) {
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: [],
};
}