Skip to content

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:

PlaceWhat golem does
The requestNestModelInterceptor converts and validates @Body() before the handler runs. Bad input gets HTTP 400.
The handlerIt receives a valid model, not raw JSON.
The OpenAPI documentThe 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 ​

sh
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
PackageWhy you need it
@exprtlabs/golemThe golem command, and the runtime of the generated files
@exprtlabs/golem-modelGenerates the files of your models
@exprtlabs/golem-ts-openapiGenerates the OpenAPI document from your controllers. It also holds NestModelInterceptor, which the app imports at run time, so it goes in dependencies.
@nestjs/swaggerThe Api… decorators that the docs job reads
typescriptThe 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:

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "rootDir": ".",
    "outDir": ".build"
  },
  "include": [
    "src/**/*.ts"
  ]
}
  • experimentalDecorators and emitDecoratorMetadata are the two options that NestJS needs.
  • outDir is where golem build writes the JavaScript that Node runs (what the tsconfig needs).
  • With NodeNext, relative imports end in .js, also for generated files.
  • Import reflect-metadata first in the entry file, before any application module. Step 5 shows the line.
  • To run the TypeScript files with the Node loader, use experimentalDecorators and emitDecoratorMetadata. 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.

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 }>;
  • TPaymentInput is an IObject. The handler receives a validated plain object (IObject or IModel).
  • A tag follows the type with &. MinLength<2>, Pattern<'…'> and MaxLength<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.

ts
@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/transactions with @Post(). The example builds the path with a route helper. A string such as @Controller('payments/transactions') works too.
  • @Body() input: TPaymentInput makes 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 of TPayment.
  • @ApiOperation({ operationId: 'createPayment' }) names the client method createPayment().
  • @ApiBadRequestResponse writes the 400 response 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:

ts
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 that globalPrefix repeats 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:

yaml
ts-openapi:
  docs:
    - output: ./api/openapi.yaml
      info:
        title: Payments API
        version: '1'
      globalPrefix: api
  extensions:
    nest: {}
  • output is the path of the document.
  • info holds the title and the version of the API.
  • globalPrefix must match setGlobalPrefix(). The generator reads controllers, not your bootstrap code (the ts-openapi block).
  • extensions: { nest: {} } turns on the request conversion that NestModelInterceptor needs (the nest extension). 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.

yaml
model: {}

Step 7: Generate and build ​

sh
npx golem generate
npx golem build
  • golem generate writes the generated model files and the document. Your editor needs them now.
  • golem build generates first, type-checks, and writes JavaScript with the request conversion in .build/.
  • Run the compiled entry file under your outDir with node (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:

BodyResult
Every field validHTTP 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.5HTTP 400. The type is a string with a Pattern
An extra key trackingHTTP 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> becomes minLength: 2, and Pattern<'…'> becomes pattern. The table of all tags is in tag keywords. TSerde and TValidation write no keyword.
  • The 400 response: the document holds it because of @ApiBadRequestResponse. Without that decorator the document has no 400 response, 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:

yaml
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 ​