aladov3.13.0

Docs/Controllers

HTTP Method Decorators

Controllers are plain TypeScript classes decorated with HTTP method decorators.

HTTP Method Decorators

TypeScript
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.path holds only the parameters declared with @defineRequest({ path: ... }): on /orders/:id without one, req.path is {} and req.path.id is undefined, 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/:id and /users/:userId). Throws AladoConfigurationError with code: 'ROUTE_ALREADY_REGISTERED'.
  • A GET or HEAD route on a path the OpenAPI docs serve (the docs page, its swagger.json, a Swagger UI file). Throws AladoConfigurationError with code: 'ROUTE_RESERVED_FOR_OPEN_API'.
  • A body on a method without one. A GET, HEAD, DELETE or OPTIONS route that declares body or files fields, rawBody: true, or reads body.* in auth or access control. Throws AladoConfigurationError with code: 'BODY_NOT_ALLOWED'.
  • A path parameter with a malformed or repeated name. /files/:name.json would declare a parameter called name.json (matching report.xml too), and /orgs/:id/users/:id keeps one value only. Throws AladoConfigurationError with code: '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 AladoConfigurationError with code: 'HEADER_DECLARED_TWICE'.
  • The same decorator twice on one method or DTO property. A second @withAuth, @accessControl, @defineRequest or @defineResponse on one method (3.9.7), or a second @validateProperty, @transformProperty or @documentProperty on one property, or @fileUploadProperty together with any of them (3.9.8), would replace the first one's setting: two @accessControl would keep the rules of one only, two @validateProperty one of the checks. Throws AladoConfigurationError with code: 'DECORATOR_REPEATED'. Pass every strategy to one @withAuth, every rule to one @accessControl and 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, @defineRequest or @defineResponse placed above it throws instead of being dropped (a dropped @withAuth would 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.

TypeScript
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:

TypeScript
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.

TypeScript
@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:

TypeScript
@get('/users', { tags: ['User'], title: 'List users' })
async list(req: Request) {
  return {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: [],
  };
}