NestJS requests
Convert and validate the @Body(), @Query() and @Headers() models of your NestJS 11 controllers, and write model responses as JSON.
The types in your controller signatures drive both the OpenAPI schema and the runtime conversion. examples/payments combines the sections below in one app.
Set up TypeScript
Add these options to the tsconfig.json from Quick start:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Import reflect-metadata first in the application entry file, before any application module import.
TypeScript erases the types of @Body(), @Query() and return values. The build rewrite records them for NestModelInterceptor.
Add the nest extension to the ts-openapi block of golem.yaml. It turns on the rewrite and its RUNM1081 checks:
ts-openapi:
docs:
- output: ./api/openapi.yaml
info:
title: Payments API
version: '1'
globalPrefix: api
extensions:
nest: {}- A docs job is not needed for them, and it does not turn them on. The docs job only writes the OpenAPI document. A block with only
extensionsis valid. - Without the extension, the build adds nothing, and
NestModelInterceptorthrows an error that tells you to add it. - Every build tool applies the rewrite (Build tools).
- The rewrite also loads the generated module of each model it records, so the codec exists before the first request.
- Write the parameter type and the return type explicitly, because the rewrite reads the annotation.
Register the interceptor
NestModelInterceptor comes from @exprtlabs/golem-ts-openapi/nest. Install @exprtlabs/golem-ts-openapi in dependencies, because the app imports it at run time. @nestjs/common and rxjs are its optional peers.
NestModelInterceptor runs fromWireFormat on @Body() and @Query() before the handler. It writes an IModel or IObject return with stringify. It works with the Express and Fastify adapters.
import 'reflect-metadata';
import { Module, type DynamicModule } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestModelInterceptor } from '@exprtlabs/golem-ts-openapi/nest';
import { PaymentNotesController } from './payment-notes.controller.js';
import { PaymentsController } from './payments.controller.js';
import { ProviderCharges, type ProviderOptions } from './provider-charges.js';
@Module({
controllers: [PaymentsController, PaymentNotesController],
})
class PaymentsModule {
static with(provider: ProviderOptions): DynamicModule {
return { module: PaymentsModule, providers: [{ provide: ProviderCharges, useValue: new ProviderCharges(provider) }] };
}
}
export async function createApplication(provider: ProviderOptions = {}) {
const application = await NestFactory.create(PaymentsModule.with(provider), { logger: false });
application.setGlobalPrefix('api');
// @Body() and @Query() become the declared model before the handler.
// An IModel or IObject return is written as that type's JSON.
application.useGlobalInterceptors(new NestModelInterceptor());
return application;
}Declare a model and use it as a @Body() type:
import { model, type IModel } from '@exprtlabs/golem/model';
import type { MinLength } from '@exprtlabs/golem/tags';
export type TPaymentDraft = IModel<{ note: string & MinLength<2> }>;
export class PaymentDraft extends model<TPaymentDraft>() {}Add a method to your controller:
@Post('drafts')
createDraft(@Body() input: PaymentDraft): PaymentDraft {
// { note: 'Lunch' } is a PaymentDraft instance.
// The HTTP response is that type's JSON.
// { note: '' } is HTTP 400 before this method runs.
return input;
}What happens to a request
Golem marks a rejected value with a LibError whose causedByInput is true. The status codes below are the behavior of the default NestModelInterceptor, an example. An application usually writes its own interceptor or exception filter with the public API (Union of models shows the imports).
The interceptor converts HTTP handlers. A handler of another context, such as RPC, passes through unchanged.
fromWireFormatruns on each@Body()and@Query()parameter with fail-fast validation. A whole@Headers()model gets the same call withstrip: true(Header models).Input that fails validation or cannot be decoded returns HTTP 400 with
issues(LibError.causedByInput). Examples are a broken constraint, an unknown discriminator tag, an unparsable date and aDeserializefunction that throws.Valid input reaches the handler as a model. A type alias stays a plain object, and your class is constructed.
An
IModelorIObjectreturn is stringified with that type. This includes aPromiseor an array of that type. A return that the rewrite did not mark stays Nest JSON. Examples are a handler with no written return type and a handler that returns a union.A mark needs an explicit return type on the handler. The type must be a model,
Promise<Model>orModel[]. A union, such asModel | undefined, gets no mark.A
Serializefunction that throws, and missing generated metadata, return HTTP 500. A marked return whose generated model did not load fails the request with HTTP 500 before the handler runs.
@Param() and @Headers('name') stay as Nest received them.
Parameter types and arrays
Every @Body() and @Query() parameter needs an IModel or IObject type, or a union of models:
- Accepted types: an
IModel, anIObject, your class that extends a generated model class, or a tagged union of models. @Query(): it needs one object model or a tagged union of models.- Option
nonModelInputs: if your own interceptor handles parameters of other types, setnonModelInputs: warnon thenestextension.golem buildthen reportsRUNM1081as a warning, not an error.
A whole @Body() parameter reads the request body as follows:
| Request body | Declared type | Result |
|---|---|---|
| A JSON object | @Body() payment: TPayment | Converts to the model. Invalid input returns HTTP 400. |
| A JSON array | @Body() items: Item[] | Converts item by item. An invalid item returns HTTP 400. Each issue path starts with the item index, such as [1, 'name']. |
| A value that is not an array | @Body() items: Item[] | Returns HTTP 400 with a type issue. |
A whole @Query() is an object, so declare it as one model and not as an array.
- Give all whole
@Body()parameters of a handler one model type. The same rule holds for whole@Query()parameters. - Name one field with
@Body('payment') payment: TPaymentor@Query('filter') filter: TFilterwhen the model sits under one key. Its type is anIModelorIObject, and the parameter is required: an optionalpayment?: TPaymentmakes the interceptor answer HTTP 400 for a missing value.golem buildreports it underRUNM1081. - A one-field
@Body('items') items: TPayment[]takes an array of models. The interceptor converts it item by item, and an invalid item returns HTTP 400 with the path['items', 1, 'name']. A one-field@Querycannot be an array of models: the docs job reportsNEST1107. - Do not mix a whole
@Body()and a one-field@Body('field')in one handler. The same rule holds for@Query().golem buildreports the mix underRUNM1081. The docs job still documents the handler. - A one-field
@Querymodel has no array field at any depth. OpenAPI does not define arrays in adeepObjectparameter, and the docs job reportsNEST1107. Send an array in a@Body, or in a whole@Query()on OpenAPI 3.2.
The docs job writes the types the handler reads and enforces no limit of NestModelInterceptor:
- One-field
@Bodyparameters: they are the properties of one object request body, whatever their type. An optional parameter is not inrequired. When all parts are optional, the request body is not required. - Several body parts: a second whole
@Body(), or a whole@Body()beside a one-field one, combine withallOf. A part that repeats appears once. Two one-field parameters of one name are one property. - Closed models: an
IModelis closed by default, so it cannot share the body with a part that requires a property it does not declare. An optional property is allowed. The job stops withNEST1107and names both parts. Make the model open with{ exact: false }, or declare the property in it. - A one-field
@Querymodel: it is adeepObjectquery parameter, such as?filter[status]=paid. An optional one is not required. On OpenAPI 3.1.2 a whole@Query()gives flat parameters beside it. A name that both use stops the job withNEST1312.
The app must parse nested query keys:
- Express 5 reads
filter[status]as one flat key by default. Set the parser once:app.set('query parser', 'extended')on the Express instance, which a Nest app gets fromapp.getHttpAdapter().getInstance(). - Fastify has the same default. Pass a parser that reads nested keys, such as
qs.parse, as thequerystringParseroption ofnew FastifyAdapter({ querystringParser }).
Query objects
HTTP query values are strings, and repeated keys arrive as string arrays. Declare the query as an IObject. Before fromWireFormat, NestModelInterceptor decodes each field to the type the model declares:
| Field type | Query text | Decoded value |
|---|---|---|
number or Integer | ?limit=42 | 42 |
boolean | ?active=true | true |
A number or boolean literal, such as 42 or true | ?mode=42 | 42 |
| An array field given one value | ?status=paid | ['paid'] |
- A value that does not fit the declared type stays a string, so validation rejects it with HTTP 400.
- A field that also accepts a string keeps it. For
string | number,'42'stays'42'. - A JSON body keeps its own types and is not decoded.
// Query object: NestModelInterceptor decodes limit to a number before validation;
// repeated status keys arrive as string[]. exact: true rejects undeclared keys
// (e.g. tracking=x) with HTTP 400.
export type TPaymentFilter = IObject<{
limit?: number & Integer & Minimum<1>;
status?: PaymentStatus | PaymentStatus[];
}, { exact: true }>;// The handler reads limit only; status shows how the interceptor decodes a union query field.
@Get()
@ApiOperation({ operationId: 'listPayments' })
@ApiBadRequestResponse({ description: 'Invalid query.' })
list(@Query() filter: TPaymentFilter): TPayment[] {
return [...payments.values()].slice(0, filter.limit ?? 20);
}GET /api/payments/transactions?limit=10&status=paidyields{ limit: 10, status: 'paid' }.- Repeated
status=paid&status=pendingyields{ status: ['paid', 'pending'] }. limit=abc,status=refunded, and undeclared keys (exact: true) return HTTP 400 before the handler.PaymentStatus | PaymentStatus[]is the supported query union.
OpenAPI 3.2 emits the whole query schema, and its SDK calls .execute({ querystring: { limit: 10, status: ['paid'] } }). OpenAPI 3.1.2 flattens a query object into named parameters (query compatibility).
Header models
A request header is text. Declare a whole @Headers() parameter as a model, and the handler gets only the fields that the model declares, decoded to their types. Other headers, such as host and user-agent, do not reach the parameter.
For example, a model with the fields port and 'x-trace', where port is a number that a TSerde tag reads from text, and a handler read(@Headers() target: TTarget):
| Request header | Field of TTarget | Value in target |
|---|---|---|
port: 8080 | port, a number | 8080 |
x-trace: abc | 'x-trace', optional text | 'abc' |
user-agent: curl | none | not in target |
NestModelInterceptor does the work:
- It drops the headers that hold empty text. An empty header counts as not sent.
- It runs
fromWireFormatwithstrip: true, so the headers that the model does not declare are removed and do not make the model fail. - A header that fails validation returns HTTP 400 with
issues. - It stores the result with
setNestHeaders, and the handler gets it.
request.headers stays as the client sent it. request.host, request.protocol and your log and trace code read the same headers as before.
- Lowercase names: Node lowercases the name of each header, and golem matches field names exactly. Write each field in lowercase, such as
'x-trace'. A field with an uppercase letter stops the build withRUNM1092. - Types: the parameter is a whole
@Headers()typed as anIModel, anIObjector a class that extends a generated model class.Record,any,IncomingHttpHeaders, an array, a union and@Headers('name')stay as Nest reads them. They report nothing. - Source and build output: your source keeps
@Headers(). The build output replaces it with a golem decorator that reads the decoded headers. Every build tool does this (Build tools). - OpenAPI document: the document shows the type that a client sends. A
TSerdefield with a text form is astringwith the pattern of that text, such as^[0-9]+$forport, not a number with limits. - No decoded value: a handler with a header model fails with HTTP 500 and a
TypeErrorthat starts withgolem faultwhen no interceptor stored the decoded headers. The handler never gets the raw headers.
To decode the headers in your own interceptor, call nestHeadersCodec with context.getClass() and context.getHandler(). It returns undefined for a handler with no header model, and otherwise an object with decode(headers). decode treats an empty header as not sent, keeps the declared fields only, and returns the model. Pass its result to setNestHeaders. The runtime API shows the call order.
Extra properties
The exact option decides whether a model rejects keys that it does not declare (Objects and exact).
- A named
IObjectorIModelkeeps its ownexact. Without the option, it takes theexactkey ofgolem.yaml, and that key defaults totrue. - A type that you spell out inline in a controller signature is read with
exactset tofalse. Its schema admits extra properties. - The example models set
{ exact: true }, which repeats the default. You can leave it out. Keep it whengolem.yamlsetsexact: falseand the model must stay exact.
Union of models
A whole @Body() or @Query() parameter can be a union of models, such as (TCircle | TRect) & Discriminator<'kind'> or an alias of one. A generic tag wrapper such as type Tagged<U> = U & Discriminator<'kind'> also works: Tagged<TCircle | TRect>. Declare the tag as for a model field: Discriminator<'kind'> on the union, and a required literal kind with a value of its own in each model.
- The interceptor reads the declared key and converts the input with the model that its value picks. A missing or unknown value returns HTTP 400.
- A query string holds the tag as text. The interceptor decodes it to the type that the picked model declares.
- The docs job documents a body as
oneOfwith adiscriminatorthat names the declared key. A query union needs OpenAPI 3.2; OpenAPI 3.1.2 stops withNEST1108. - A union converts only as a whole parameter. An array of a union and a union in
@Body('field')stop withRUNM1081. - A union without the tag stops with
RUNM1081. The message names the tag to add. - A default variant on a parameter union stops with
RUNM1081, because the interceptor picks no default. Remove the default, or bind one model. - A union return stays Nest JSON.
Your own interceptor or pipe converts a model parameter with objectCodecFromMetatype, and a union parameter with nestUnionFromMetatype. Pass either the design:paramtypes entry of the parameter, which Reflect.getMetadata('design:paramtypes', Controller.prototype, 'method') returns, such as nestUnionFromMetatype(type)?.fromWireFormat(request.body, { failFast: true }).
A query holds text. nestQueryDecoder takes the same entry for a model or a union and returns the function that decodes request.query to the numbers, booleans and arrays the model declares. Pass its result to fromWireFormat, as in codec.fromWireFormat(nestQueryDecoder(type)?.(request.query), { failFast: true }). A value that does not fit stays text, and fromWireFormat rejects it as bad input.
Model responses
The interceptor stringifies a return only when its declared type is a model:
| Declared return type | Response |
|---|---|
IModel or IObject, including a Promise of that type | That type's JSON |
| Array of that type | JSON array of those values |
| Primitive, plain object, file, non-model class, or a union | Nest JSON |
Declare a wrapper object as a model when its fields need conversion, because the interceptor does not look inside a plain wrapper.
To write the response in your own interceptor, call nestReturnCodec with context.getClass() and context.getHandler(). It returns { codec, array } for the declared return, or undefined when the handler has no mark.
When array is true, stringify each item of the returned array with codec.stringify. nestReturnCodec throws a TypeError that starts with golem fault when the build marked the handler and the codec of the model is not registered. To write the response with a codec other than the one of the declared return type, use nestModelStringifyInterceptor with a codec that you hold. The imports are in the runtime API.
Run with the Node loader
Node's type stripping rejects the parameter decorators of a NestJS controller. The Node loader compiles each file that has a decorator with your TypeScript, so the app needs no second loader.
- Set
experimentalDecoratorsandemitDecoratorMetadatain the tsconfig thatgolem.yamlnames. - Run the entry file through golem's loader:
node --import @exprtlabs/golem/register src/main.tsThe register entry describes the loader.
Full example: examples/payments.
