NestJS controllers
See how each controller construct becomes OpenAPI.
Route helpers
The generator folds a route path or version to a value at generation time. It does not start your app or run other module code. src/routes.ts:
export const routes = {
// Plain function, not a Nest provider: the OpenAPI generator evaluates it at
// generate time, and `@Controller` calls it again at runtime for the route.
resource(
{ service, resource }: { service: string; resource: string },
): string {
return `${service}/${resource}`;
},
};Use it in your controller:
@Controller(routes.resource({ service: 'payments', resource: 'transactions' }))| Path expression | Result |
|---|---|
'payments/transactions' or an array of string literals | Used as written |
routes.resource({ service: 'payments', resource: 'transactions' }) | Folded to payments/transactions |
| A helper that returns a template, a concatenation, a const string, its own string parameters or another simple helper | Folded |
| A helper whose object argument is destructured in its signature | Folded |
| A static class method or an object-literal method used as a helper | Folded |
| A non-static class method used as a helper | Error |
A helper whose body is more than one return expression (any statement before the return counts) | Error |
A route that the generator cannot fold stops generation with an error that names the expression.
Model schemas
An IModel or IObject contract is authoritative in both request and response directions. When ts-openapi (docs or extensions.nest) is configured beside model, Golem automatically discovers inline IObject and IModel declarations in controller files (*.controller.ts or configured controller sources/suffixes) and emits their codecs into .golem/models/, so you do not need to add .controller.ts to model.suffixes. Swagger metadata can add documentation. A structural override must agree with the TypeScript contract and its validation constraints, or generation stops.
Supported validation tags become OpenAPI keywords, and the client generator reads the same keywords back into model and request validation. The document can come from any OpenAPI producer.
| TypeScript tag | OpenAPI keyword | Generated validation |
|---|---|---|
string & MinLength<3> | type: string, minLength: 3 | Rejects strings shorter than three characters |
number & Minimum<0> | type: number, minimum: 0 | Rejects negative numbers |
string & Pattern<'^[A-Z]+$'> | type: string, pattern: '^[A-Z]+$' | Rejects strings that do not match |
The supported keywords depend on the OpenAPI version and profile (OpenAPI support).
Tag keywords
A docs job writes each validation tag of a model into the document as one OpenAPI keyword:
| TypeScript tag | OpenAPI keyword |
|---|---|
Integer | type: integer |
Minimum<N> or Min<N> | minimum |
Maximum<N> or Max<N> | maximum |
ExclusiveMinimum<N> or ExclusiveMin<N> | exclusiveMinimum |
ExclusiveMaximum<N> or ExclusiveMax<N> | exclusiveMaximum |
MultipleOf<N> | multipleOf |
MinLength<N> | minLength |
MaxLength<N> | maxLength |
Pattern<'…'> | pattern |
Format<'name'> | format |
MinItems<N> | minItems |
MaxItems<N> | maxItems |
UniqueItems | uniqueItems: true |
Contains<T> | contains, with the schema of T |
MinContains<N> | minContains |
MaxContains<N> | maxContains |
MinProperties<N> or MinProps<N> | minProperties |
MaxProperties<N> or MaxProps<N> | maxProperties |
PropertyNames<T> | propertyNames, with the schema of T |
PatternProperties<Map> | patternProperties, one schema for each pattern |
AdditionalProperties<T> | additionalProperties, with the schema of T |
UnevaluatedProperties<T> | unevaluatedProperties, with the schema of T |
DependentRequired<Map> | dependentRequired |
DependentSchemas<Map> | dependentSchemas |
OneOf<Tuple> | oneOf, one schema for each member |
Not<T> | not, with the schema of T |
IfThenElse<Condition, Then, Else> | if, then and else (else only when you give it) |
TSerdeandTValidationwrite no keyword of their own. OpenAPI has no keyword for a function. ATSerdefield still gets the schema of its JSON type, which the deserializer's parameter type sets.- Golem adds no
400response to the document, for any tag. Declare it with@ApiBadRequestResponse()or@ApiResponse({ status: 400 }).
Custom predicates and converters stay in TypeScript functions, because OpenAPI carries no executable code. Sharing them through imports is optional.
Fields with a TSerde pair
For a field with a TSerde pair, the OpenAPI schema describes the JSON value, not the model value. The example stores a number in the model and sends a string in JSON. The converters live in their own module, because generated files import them:
import type { Pattern } from '@exprtlabs/golem/tags';
export type DecimalText = string & Pattern<'^[0-9]+(?:\\.[0-9]{2})$'>;
// The model keeps integer minor units (cents); JSON carries the exact decimal text.
export const writeAmount = (minorUnits: number): DecimalText => `${Math.trunc(minorUnits / 100)}.${String(minorUnits % 100).padStart(2, '0')}`;
export const readAmount = (text: DecimalText): number => Number(text.replace('.', ''));The model references them by type:
import type { IModel } from '@exprtlabs/golem/model';
import type { Integer, Minimum, TSerde } from '@exprtlabs/golem/tags';
import type { readAmount, writeAmount } from './decimal-text.js';
export type TPrice = IModel<{
amount: number & Integer & Minimum<0> & TSerde<typeof writeAmount, typeof readAmount>;
currency: string;
}>;- A controller parameter or return type that uses this model appears in OpenAPI as its JSON value.
amountis a string schema with thePatterndeclared on the decoder's parameter type. - The decoder's parameter type supplies the JSON type. Generation reads that type and never calls a converter.
- A validation constraint on the model value, such as
Minimum<0>on a number, is not copied onto the string JSON field.
Component names
A model's component name comes from the types it was declared with:
| Declaration | Component |
|---|---|
class Payment extends model<TPayment>() {} for type TPayment = IModel<…> | Payment, the class name |
Two or more classes extending model<TPayment>() | TPayment, the exact alias |
type TMerchant = IModel<…> with no class | TMerchant, the exact alias |
type TPaymentInput = IObject<…> | TPaymentInput, the exact alias |
More rules for component names:
- A type derived from a model, such as
Omit<TMerchant, 'id'>, is named from the model's component, as inTMerchantOmitId. - Two models with the same component name and an identical schema share one component.
- A model class named with
@ApiSchema({ name })is the component of that name, in every$refto it. The generated model code keeps the model's name. @ApiSchemarenames a model's component only when the class is the single class linked to the model and is declared in the same file as the alias. Otherwise the component keeps the alias name.- Two models of one file with the same component name stop generation with
RUNM1005. - A plain DTO class stays inline in the document. Its
@ApiSchema({ name })names it only forgetSchemaPath()andrefs()from@nestjs/swagger.
Two models with the same name and different schemas are qualified by where they are declared:
- Each takes the shortest trailing run of its file's directory segments, relative to the project root, that tells the models apart. The segments join with
., as inorders.Paymentandbilling.Payment. - Models in the same directory add the file name without
.model.tsor.ts, as inbilling.payment.Paymentandbilling.refund.Payment. - Characters other than letters, digits and underscores in a segment become
_.
Status codes and media types
| Controller contract | Generated success response |
|---|---|
@Post() | 201 by default |
| Other HTTP verbs | 200 by default |
@HttpCode(204) | 204, including an explicit empty response |
| Object or array return type | JSON by default |
@Res({ passthrough: true }) or @Response({ passthrough: true }) | Inferred from the return type |
| Primitive, file, stream or manual response | Needs an explicit Swagger media type and schema |
- A
voidreturn does not imply204. - Swagger response decorators describe the response, and
@HttpCodecontrols the status Nest sends. A Swagger200,201,202,204or205response that differs from the Nest status stops generation (NEST1311). @ApiProducessets the response media types, and@ApiConsumessets the request body media types.@Header('Content-Type', …)sets the media type of the success response. Acontentoption in a Swagger response sets its own.- Path parameters must match the placeholders of the route, and they are always required.
- A route with several paths or versions gets one operation for each. Their operation IDs end in
__path_1,__version_1and so on, or in__path_1__version_1when a route has several paths and several versions. Two operations with the same ID stop generation (NEST1305).
@Res() and @Res({ passthrough: false }) handle the response manually, so declare a Swagger success response with a type or content and schema. Write the @Res() options as an inline object. The passthrough option and the endpoint-exclusion options must be static booleans.
Swagger decorators and merge order
The generator reads these @nestjs/swagger decorators:
| Decorator | Effect |
|---|---|
@ApiOperation | operationId, summary, description and deprecated |
@ApiTags, @ApiProduces, @ApiConsumes | Tags and media types |
@ApiBody | Request body type, isArray, required, description, content and schema |
@ApiQuery, @ApiParam, @ApiHeader, @ApiHeaders | Parameter metadata, from the method or the class |
@ApiResponse and the named helpers, such as @ApiTooManyRequestsResponse() | Responses by exact status, 1XX through 5XX, or default |
Merge rules for response decorators follow @nestjs/swagger:
- A class-level decorator, such as
@ApiOkResponse(), applies to every route on the class, including inherited routes. - A method-level decorator for the same status replaces the class one.
- Repeated decorators on the same class or method apply from bottom to top. Two decorators for one status join their descriptions.
- A range or
defaultresponse keeps the inferred200or201response. - A route that decorates only other statuses, such as
@ApiNotFoundResponse(), keeps the inferred200or201response, as the Nest Swagger CLI plugin does.
Request validation level
Golem does not set HTTP status codes. It marks a value that it rejects with a LibError whose causedByInput is true. NestModelInterceptor is a default example: it answers HTTP 400 for such an error and lets every other error through. An application usually writes its own interceptor or exception filter with the public API (your own interceptor).
NestModelInterceptor comes from @exprtlabs/golem-ts-openapi/nest and takes an options object. validate sets the level that it checks @Body() and @Query() input at.
validate | Level of the check |
|---|---|
| Not set | The default level of each model |
'sanity' | The shape only (what sanity checks) |
true | Every rule |
new NestModelInterceptor({ validate: 'sanity' });- Input that fails the check answers HTTP 400, at every level.
- A level above the project level is a server error: the request answers HTTP 500, because the fault is in the setup and not in the input.
- The
maxDepthoption is in the runtime reference.
Query compatibility
| Target | Whole-query contract |
|---|---|
| OpenAPI 3.2 | Emits in: querystring with form content and the complete query schema |
| OpenAPI 3.1.2 | Flattens independent fields into named parameters and rejects a contract whose constraints would be lost (NEST1108) |
Named @Query('name') parameters remain ordinary query parameters. A named parameter must be a scalar, an array of scalars, or an IModel or IObject, or generation stops (NEST1107). A named model is one deepObject parameter (filter[status]=paid). A one-field @Body('name') parameter is a property of the request body.
A whole @Query() object follows these rules:
- A type with an index signature, such as a dictionary, stops generation on both versions (
NEST1105). - A property that is not a scalar or an array of scalars stops generation on both versions (
NEST1107). This covers a nested object and a nullable value. - On OpenAPI 3.2, the object becomes one
querystringparameter. It cannot share an operation with named query parameters or a second whole object (NEST1107). - On OpenAPI 3.1.2, an object whose constraints or codecs would be lost in the flat form stops generation (
NEST1108).
Excluded endpoints
@ApiExcludeEndpoint()and@ApiExcludeEndpoint(true)omit a route.@ApiExcludeEndpoint(false)keeps it.- Only
@ApiExcludeEndpoint()hides an individual route;@ApiOperationhas nohiddenoption. @ApiExcludeController()omits every route of a controller.@ApiExcludeController(false)keeps them.- Exclude a route that has no OpenAPI form, such as
@All()or@Sse(), so generation skips it.
