Add Golem to a NestJS API
Add Golem to a NestJS 11 API for a checked body, HTTP 400 for bad input and an OpenAPI document, while NestJS builds the endpoint.
What golem does for an endpoint
Golem marks a rejected value with LibError.causedByInput. The HTTP 400 in this guide is the behavior of the default NestModelInterceptor; an application can write its own interceptor or exception filter with the public API (NestJS requests).
You declare the body once, as a TypeScript type with tags. Golem uses that one type in three places:
| Place | What golem does |
|---|---|
| The request | NestModelInterceptor converts and validates @Body() before the handler runs. Bad input gets HTTP 400. |
| The handler | It receives a valid model, not raw JSON. |
| The OpenAPI document | The docs job reads the controller and the type. It writes the document, and the tags become OpenAPI keywords. |
The steps build POST /api/payments/transactions from examples/payments. For your own POST /orders, use the names OrdersController and TOrderInput.
Step 1: Install the packages
npm install @exprtlabs/golem @exprtlabs/golem-ts-openapi @nestjs/common @nestjs/core @nestjs/platform-express @nestjs/swagger reflect-metadata rxjs
npm install --save-dev @exprtlabs/golem-model typescript@~7.1.0-beta| Package | Why you need it |
|---|---|
@exprtlabs/golem | The golem command, and the runtime of the generated files |
@exprtlabs/golem-model | Generates the files of your models |
@exprtlabs/golem-ts-openapi | Generates the OpenAPI document from your controllers. It also holds NestModelInterceptor, which the app imports at run time, so it goes in dependencies. |
@nestjs/swagger | The Api… decorators that the docs job reads |
typescript | The compiler that the generators and golem build use |
Check the requirements and add "type": "module" to package.json.
Step 2: Set up TypeScript
Use these options in tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"rootDir": ".",
"outDir": ".build"
},
"include": [
"src/**/*.ts"
]
}experimentalDecoratorsandemitDecoratorMetadataare the two options that NestJS needs.outDiris wheregolem buildwrites the JavaScript that Node runs (what the tsconfig needs).- With
NodeNext, relative imports end in.js, also for generated files. - Import
reflect-metadatafirst in the entry file, before any application module. Step 5 shows the line. - To run the TypeScript files with the Node loader, use
experimentalDecoratorsandemitDecoratorMetadata. The loader compiles the decorators (run with the Node loader).
Step 3: Declare the body model
Write the model in src/payment.model.ts. The generator reads files that end in .model.ts.
export type TMerchant = IObject<{ id: string; name: string & MinLength<2> }>;
// Amounts are decimal strings and currencies are ISO 4217 codes; no float carries money.
export type TMoney = IObject<{
amount: string & Pattern<'^[0-9]+(?:\\.[0-9]{1,2})?$'>;
currency: string & Pattern<'^[A-Z]{3}$'>;
}>;
export type TCharge = IObject<{ id: string; status: 'pending' | 'captured'; settlesOn: string }>;
export type TPayment = IModel<{
id: string;
merchant: TMerchant;
billing: Omit<TMerchant, 'id'>;
money: TMoney;
note: string & MaxLength<140>;
charge?: TCharge; // The provider's charge for this payment.
}, { exact: true }>;
export type TPaymentInput = IObject<Omit<TPayment, 'id' | 'charge'>, { exact: true }>;TPaymentInputis anIObject. The handler receives a validated plain object (IObject or IModel).- A tag follows the type with
&.MinLength<2>,Pattern<'…'>andMaxLength<140>are checked on each request and written into the document (validation tags). - A field with no tag still has its type checked, and a missing required field fails.
A named model such as TPaymentInput is exact. A request with an undeclared key gets HTTP 400 before the handler runs. The exact option, golem.yaml and an inline body type change this (Extra properties).
Step 4: Write the controller
Type the @Body() parameter with the model. Write the return type too, because the build reads both annotations.
@Post()
@ApiOperation({ operationId: 'createPayment' })
@ApiBadRequestResponse({ description: 'Invalid payment input.' })
@ApiBadGatewayResponse({ description: 'The payment provider declined or is unavailable.' })
async create(@Body() input: TPaymentInput): Promise<TPayment> {
const id = String(nextPaymentId++);
const charge = await this.provider.charge(input.money, `payment-${id}`);
const payment = { id, ...input, charge };
payments.set(payment.id, payment);
return payment;
}- The route is
payments/transactionswith@Post(). The example builds the path with a route helper. A string such as@Controller('payments/transactions')works too. @Body() input: TPaymentInputmakes the interceptor validate the body. The handler never runs for a body that fails.Promise<TPayment>makes the interceptor write the response with the JSON form ofTPayment.@ApiOperation({ operationId: 'createPayment' })names the client methodcreatePayment().@ApiBadRequestResponsewrites the400response into the document. Golem does not add it for you.
Step 5: Register the interceptor
Register NestModelInterceptor from @exprtlabs/golem-ts-openapi/nest once, for the whole app:
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;
}import 'reflect-metadata'comes first.controllers: [PaymentsController, …]lists the controller in a module, as for any NestJS controller.setGlobalPrefix('api')sets the prefix thatglobalPrefixrepeats in Step 6.useGlobalInterceptors(new NestModelInterceptor())turns on the conversion for every controller. It works with the Express and Fastify adapters.new NestModelInterceptor({ maxDepth })sets how many levels of objects and arrays the body of a recursive model may nest. The default is 512, and deeper input gets HTTP 400 (maxDepth).
The steps for each request and the rules for arrays and query objects are in NestJS requests.
Step 6: Configure golem.yaml
Add golem.yaml at the project root. Start it with version: 1. The excerpts below leave out version: 1 and the other jobs of the example. The ts-openapi block holds a docs job that writes the OpenAPI document, and the nest extension:
ts-openapi:
docs:
- output: ./api/openapi.yaml
info:
title: Payments API
version: '1'
globalPrefix: api
extensions:
nest: {}outputis the path of the document.infoholds thetitleand theversionof the API.globalPrefixmust matchsetGlobalPrefix(). The generator reads controllers, not your bootstrap code (thets-openapiblock).extensions: { nest: {} }turns on the request conversion thatNestModelInterceptorneeds (thenestextension). Without it the interceptor throws an error that tells you to add it.
The models job is required. It writes the generated file of each model that your controllers use, and the build needs it to bind each @Body() model. Without it, the build reports has no unique codec id; run golem generate.
model: {}Step 7: Generate and build
npx golem generate
npx golem buildgolem generatewrites the generated model files and the document. Your editor needs them now.golem buildgenerates first, type-checks, and writes JavaScript with the request conversion in.build/.- Run the compiled entry file under your
outDirwithnode(Build tools). - Ignore or commit the generated files and the document, as you choose (ignore or commit generated files). Ignore
.golem/in both cases.
Send these bodies to the endpoint. The handler runs only for the first:
| Body | Result |
|---|---|
| Every field valid | HTTP 201 and the JSON of the new payment |
money.currency is "usd" | HTTP 400. The issue path is ['money', 'currency'] |
money.amount is the number 12.5 | HTTP 400. The type is a string with a Pattern |
An extra key tracking | HTTP 400 with the issue code unknownKey |
What the frontend gets
The frontend team gets api/openapi.yaml. It holds the operation createPayment with its request schema and its responses (the document for this controller).
- Tags: each validation tag of the model becomes one keyword.
MinLength<2>becomesminLength: 2, andPattern<'…'>becomespattern. The table of all tags is in tag keywords.TSerdeandTValidationwrite no keyword. - The 400 response: the document holds it because of
@ApiBadRequestResponse. Without that decorator the document has no400response, although the interceptor still answers HTTP 400.
The frontend project sets the document as the input of an SDK job. This example reads the document of the server project:
version: 1
validation: true
openapi-ts:
sdks:
- input: ../server/api/openapi.yaml
output: sdk
name: Payments
mode: golem
extensions:
mobx: {}
model: {}Then npx golem generate in the frontend project writes the client (Generate an SDK). How the document reaches another project, and what to run in CI, is in generated files.
Details in the reference
- NestJS requests: parameter types, arrays, one-field parameters, query objects and responses.
- OpenAPI from controllers: the docs job and the document it writes.
- NestJS controllers: route helpers, tag keywords, component names, status codes and Swagger decorators.
- Configuration: every key of a docs job.
- Generated files: ignore or commit them, and how the document reaches other projects.
