@chimp-labs/keel-nestjs connects @chimp-labs/keel and @chimp-labs/keel-alchemy to NestJS 10 & 11 using standard TypeScript 5.x TC39 Stage 3 decorators.
You do not need "experimentalDecorators": true or "emitDecoratorMetadata": true in tsconfig.json.
Feature matrix
| Capability | API in @chimp-labs/keel-nestjs |
What it does |
|---|---|---|
| Standard Stage 3 NestJS decorators | @Module, @Global, @Injectable, @Controller, @Catch, @Get/@Post/@Put/@Patch/@Delete/@Sse, @HttpCode, @UseGuards/@UsePipes/@UseInterceptors, arg.* |
Bridges TC39 Stage 3 decorators onto NestJS’s native metadata keys (experimentalDecorators: false, emitDecoratorMetadata: false) |
Native Effect v4 & Stream returns |
KeelEffectInterceptor, effectGuard, effectPipe, KEEL_RUNTIME |
Lets controllers return Effect.Effect<A, E, R> and Stream.Stream<A, E, R> directly on Keel’s shared ManagedRuntime with ambient tenant propagation, live @Sse() streaming, and fiber interruption on HTTP client disconnect |
| Compile-time checked DI | @Inject(OrdersTable, ReceiptsBucket, InventoryService) (class or field) |
Accepts raw Keel resources, KEEL_CLIENT/KEEL_RUNTIME, NestJS classes, or symbols; TypeScript verifies constructor parameter order and types at compile time |
| Single-runtime lifecycle | KeelModule.forRoot(...) |
Boots one shared KeelClient + ManagedRuntime, auto-mounts KeelContextMiddleware, registers KeelEffectInterceptor and KeelExceptionFilter, and calls keel.close() on onApplicationShutdown |
| Ambient ACID transactions | @Transactional(), runInKeelTransaction(...) |
Propagates a Keel transaction via AsyncLocalStorage for async Promise methods, or wraps Effect-returning methods natively in withTransaction(...) |
| Multi-tenant context | KeelContextMiddleware, TenantAwareTable<T> |
Bridges x-tenant-id into CurrentTenant (for both SDK and Effect v4) and auto-populates tenantId on .insert(...) |
Unified Cause-aware error mapping |
KeelExceptionFilter, KeelEffectFailure |
Preserves NestJS HttpExceptions (thrown or failed inside Effect) and maps Keel errors, SchemaError (400), [KeelErrorMetaSym], defects (500), and interrupts (503) via reportCause (including Retry-After on rate limits) |
| Single-source unit modules | @KeelUnitModule(...), KeelModule.forFeature(...), KeelModule.forService(...) |
Binds & ensures Keel resources once and stamps bounded-context unit metadata |
Static AppModule → Topology |
nestTopology(AppModule), inspectNestModuleGraph(AppModule), inferNestInfra(AppModule) |
Walks NestJS imports metadata without booting NestJS to infer deployOrder, database & Garage S3 needs, least-privilege envs, Caddyfile, and Alchemy stacks |
Installation & tsconfig.json
pnpm add @chimp-labs/keel @chimp-labs/keel-nestjs @nestjs/common @nestjs/core @nestjs/platform-express reflect-metadata rxjs
Keep standard TypeScript 5.x compiler settings — legacy decorator flags stay off:
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"experimentalDecorators": false,
"emitDecoratorMetadata": false
}
}
Why standard Stage 3 decorators? TC39 Stage 3 does not include parameter decorators (
constructor(@Inject(X) x)fails withTS1206whenexperimentalDecorators: false).@chimp-labs/keel-nestjsreplaces parameter decorators with class-level@Inject(TokenA, TokenB)(compile-time checked against constructor parameters), field-level@Inject(Token), and route arg specs (@Post("/", [arg.body()]),@Get("/:id", [arg.param("id")])).
Defining units, services, and controllers
1. Declare pure Keel resources
// src/inventory/inventory.resources.ts
import { k } from "@chimp-labs/keel/sdk"
export const StockTable = k.table(
"stock",
{
sku: k.text().primaryKey(),
tenantId: k.text(),
title: k.text(),
available: k.integer(),
},
{ tenantScoped: true }
)
export const StockReservedTopic = k.topic(
"inventory.reserved",
k.object({ sku: k.string(), qty: k.int() })
)
2. Inject resources with compile-time type checking
Pass raw Keel descriptors or NestJS provider classes directly to @Inject(...). If you swap two tokens relative to the constructor signature, tsc --noEmit catches it immediately:
// src/inventory/inventory.service.ts
import type { BoundTopic } from "@chimp-labs/keel/sdk"
import { Inject, Injectable, type TenantAwareTable } from "@chimp-labs/keel-nestjs"
import { StockReservedTopic, StockTable } from "./inventory.resources.js"
@Injectable()
@Inject(StockTable, StockReservedTopic)
export class InventoryService {
constructor(
private readonly stock: TenantAwareTable<typeof StockTable>,
private readonly stockReserved: BoundTopic<typeof StockReservedTopic>
) {}
async upsertItem(sku: string, title: string, available: number) {
// `tenantId` is auto-populated from ambient CurrentTenant on tenantScoped tables
return this.stock.insert({ sku, title, available })
}
async reserve(sku: string, qty: number) {
const row = await this.stock.getById(sku)
const updated = await this.stock.updateById(sku, { available: row.available - qty })
await this.stockReserved.enqueueOutbox({ sku, qty })
return updated
}
}
3. Ambient @Transactional() across services + field @Inject
Decorate any async orchestration method with @Transactional(). Every injected Keel table or resource called inside — including across other NestJS services like InventoryService.reserve(...) — automatically participates in the same ACID transaction via AsyncLocalStorage, rolling back completely on error:
// src/orders/orders.service.ts
import { randomUUID } from "node:crypto"
import {
type BoundBucket,
type BoundSecret,
} from "@chimp-labs/keel/sdk"
import {
Inject,
Injectable,
Transactional,
type TenantAwareTable,
} from "@chimp-labs/keel-nestjs"
import { InventoryService } from "../inventory/inventory.service.js"
import { OrdersTable, ReceiptsBucket, StripeKey } from "./orders.resources.js"
@Injectable()
@Inject(OrdersTable, ReceiptsBucket, InventoryService)
export class OrdersService {
// TC39 Stage 3 field-level @Inject (NestJS property injection) is also supported
@Inject(StripeKey)
private readonly stripeKey!: BoundSecret<typeof StripeKey>
constructor(
private readonly orders: TenantAwareTable<typeof OrdersTable>,
private readonly receipts: BoundBucket<typeof ReceiptsBucket>,
private readonly inventory: InventoryService
) {}
@Transactional()
async placeOrder(sku: string, qty: number) {
const id = randomUUID()
const receiptKey = `receipts/${id}.json`
await this.inventory.reserve(sku, qty)
const order = await this.orders.insert({
id,
sku,
qty,
receiptKey,
createdBy: "system",
})
await this.receipts.put(
receiptKey,
new TextEncoder().encode(JSON.stringify({ orderId: order.id })),
{ contentType: "application/json" }
)
return order
}
}
4. Controllers with arg.* route extractors
// src/orders/orders.controller.ts
import { Controller, Get, Inject, Post, arg } from "@chimp-labs/keel-nestjs"
import { OrdersService } from "./orders.service.js"
@Controller("/orders")
@Inject(OrdersService)
export class OrdersController {
constructor(private readonly orders: OrdersService) {}
@Post("/", [arg.body()])
placeOrder(body: { sku: string; qty: number }) {
return this.orders.placeOrder(body.sku, body.qty)
}
@Get("/:id/receipt", [arg.param("id")])
getReceipt(id: string) {
return this.orders.getReceipt(id)
}
}
5. Compose modules with @KeelUnitModule and @KeelTopology
@KeelUnitModule(...) combines @KeelUnit, @Module, and KeelModule.forFeature into one declaration, and KeelModule.forRoot(...) mounts KeelContextMiddleware and KeelExceptionFilter automatically:
// src/inventory/inventory.module.ts
import { KeelUnitModule } from "@chimp-labs/keel-nestjs"
import { InventoryController } from "./inventory.controller.js"
import { StockReservedTopic, StockTable } from "./inventory.resources.js"
import { InventoryService } from "./inventory.service.js"
@KeelUnitModule({
name: "inventory",
resources: [StockTable, StockReservedTopic],
controllers: [InventoryController],
providers: [InventoryService],
exports: [InventoryService],
})
export class InventoryModule {}
// src/orders/orders.module.ts
import { KeelUnitModule } from "@chimp-labs/keel-nestjs"
import { InventoryModule } from "../inventory/inventory.module.js"
import { OrdersController } from "./orders.controller.js"
import {
OrdersTable,
ReceiptsBucket,
ReconcileCron,
StripeKey,
} from "./orders.resources.js"
import { OrdersService } from "./orders.service.js"
@KeelUnitModule({
name: "orders",
public: { domain: "api.example.com" },
imports: [InventoryModule],
resources: [OrdersTable, ReceiptsBucket, StripeKey, ReconcileCron],
controllers: [OrdersController],
providers: [OrdersService],
exports: [OrdersService],
})
export class OrdersModule {}
// src/app.module.ts
import { KeelModule, KeelTopology, Module } from "@chimp-labs/keel-nestjs"
import { InventoryModule } from "./inventory/inventory.module.js"
import { OrdersModule } from "./orders/orders.module.js"
@KeelTopology("commerce-platform", {
isolation: { database: "schema" },
})
@Module({
imports: [
KeelModule.forRoot({
backend: "memory", // or "postgres" / "sqlite" / "surreal"
secrets: { STRIPE_KEY: process.env["STRIPE_KEY"] ?? "sk_test_demo" },
}),
InventoryModule,
OrdersModule,
],
})
export class AppModule {}
Native Effect v4 & Stream returns
KeelModule.forRoot(...) automatically registers KeelEffectInterceptor globally (registerEffectInterceptor: true), so controllers and services can return raw Effect v4 Effect and Stream values directly—without calling keel.runEffect(...) or wrapping in async/await. You can freely mix plain Promise and native Effect handlers in the same NestJS application.
- Zero-boilerplate execution & ambient context: Returned
Effects andStreams run on Keel’s sharedManagedRuntime(also injectable via@Inject(KEEL_RUNTIME)), withCurrentTenantbridged automatically fromKeelContextMiddleware. - Effect-native
@Transactional(): When applied to a method returning anEffect,@Transactional()wraps it directly in Keel’swithTransaction(...)—rolling back atomically on typedEffect.fail(...)errors, defects, or fiber interruption. - Client-disconnect fiber interruption: Premature HTTP disconnects (
res"close"beforewritableEnded) and RxJS unsubscribe teardowns interrupt the running fiber automatically, executingEffect.acquireUseRelease/Stream.ensuringfinalizers cleanly. - Full
Causefidelity inKeelExceptionFilter: Failures carry their intact EffectCause(KeelEffectFailure), so NestJSHttpExceptions insideEffect.fail(...)stay intact, Keel errors /SchemaError(400) / custom[KeelErrorMetaSym]errors map semantically (includingRetry-AfteronRateLimitExceededError), defects map to500, and explicitEffect.interruptmaps to503. - Native
Stream&@Sse()support: Returning aStreamfrom a regular@Getroute collects it into a JSON array; returning aStreamfrom@Sse(...)streams live Server-Sent Events and interrupts the stream fiber when the client disconnects. - Effect-powered Guards & Pipes: Use
effectGuard(...)andeffectPipe(...)with@UseGuards(...)/@UsePipes(...)to run Effect v4 tenant/auth checks orSchema.decodeUnknownEffect(...)validation on the same runtime.
import { randomUUID } from "node:crypto"
import { Effect, Option, Schema, Stream } from "effect"
import {
CurrentTenant,
TenantContextMissingError,
insertRow,
selectRows,
} from "@chimp-labs/keel"
import {
Controller,
Get,
Inject,
Injectable,
Post,
Sse,
Transactional,
UseGuards,
UsePipes,
arg,
effectGuard,
effectPipe,
} from "@chimp-labs/keel-nestjs"
import { OrdersTable } from "./orders.resources.js"
const CreateOrderSchema = Schema.Struct({
sku: Schema.String,
qty: Schema.Number.check(Schema.isGreaterThan(0)),
})
const TenantRequiredGuard = effectGuard(() =>
Effect.gen(function* () {
const tenant = yield* CurrentTenant
if (Option.isNone(tenant)) {
return yield* new TenantContextMissingError({
resource: "orders",
operation: "create",
})
}
return true
})
)
const CreateOrderPipe = effectPipe((value: unknown) =>
Schema.decodeUnknownEffect(CreateOrderSchema)(value)
)
@Injectable()
export class OrdersEffectService {
@Transactional()
create(input: typeof CreateOrderSchema.Type) {
return Effect.gen(function* () {
const tenant = yield* CurrentTenant
return yield* insertRow(OrdersTable, {
id: randomUUID(),
sku: input.sku,
qty: input.qty,
receiptKey: `receipts/${input.sku}.json`,
createdBy: Option.isSome(tenant) ? tenant.value.tenantId : "anonymous",
} as any)
})
}
list() {
return selectRows(OrdersTable)
}
}
@Controller("/fx/orders")
@Inject(OrdersEffectService)
export class OrdersEffectController {
constructor(private readonly orders: OrdersEffectService) {}
@Post("/", [arg.body()])
@UseGuards(TenantRequiredGuard)
@UsePipes(CreateOrderPipe)
create(body: typeof CreateOrderSchema.Type) {
return this.orders.create(body) // returned Effect runs natively!
}
@Get("/")
list() {
return this.orders.list()
}
@Sse("/events")
events() {
// Plain objects auto-wrap as `{ data }`; client disconnect interrupts the fiber
return Stream.fromIterable([
{ status: "queued" },
{ status: "confirmed" },
{ type: "done", data: "complete" },
])
}
}
Static infrastructure & topology inference from AppModule
Import @chimp-labs/keel-nestjs/topology in alchemy.run.ts (or any planning script). nestTopology(AppModule) walks NestJS’s static imports metadata without booting NestJS, synthesizes cross-unit dependency edges straight from imports: [InventoryModule] (or uses explicit k.service(...) contracts if declared via service / KeelModule.forService), and returns a real Keel Topology:
// alchemy.run.ts
import { keelDockerStack } from "@chimp-labs/keel-alchemy/docker"
import { nestTopology } from "@chimp-labs/keel-nestjs/topology"
import { AppModule } from "./src/app.module.js"
export default keelDockerStack(nestTopology(AppModule), {
database: "postgres",
postgres: {
schemaMode: "migrate-and-verify",
},
garage: { configPath: "./docker/garage.toml" },
})
From AppModule above, Keel + Alchemy automatically infer:
- Deploy order:
["inventory", "orders"](fromOrdersModuleimportingInventoryModule). - Database engine:
postgres:17-alpinewith isolatedinventoryandordersPostgreSQL schemas (isolation: { database: "schema" }). - Least-privilege unit env maps:
inventoryreceivesPOSTGRES_URL,KEEL_PG_SCHEMA, andKEEL_EXPOSED_SERVICES(noS3_*, noSTRIPE_KEY).ordersreceivesPOSTGRES_URL,KEEL_PG_SCHEMA,S3_*,STRIPE_KEY, andKEEL_SERVICE_INVENTORY_URL=http://inventory:3000.
- Caddy ingress: exposes
api.example.com -> orders:3000while keepinginventoryprivate.
Subpath exports
| Import path | Purpose |
|---|---|
@chimp-labs/keel-nestjs |
Full adapter: TC39 Stage 3 decorators (@Module, @Controller, @Sse, @UseGuards, @UsePipes, …), KeelModule, @KeelUnitModule, KeelEffectInterceptor, effectGuard, effectPipe, KeelContextMiddleware, KeelExceptionFilter, @Transactional, and topology helpers |
@chimp-labs/keel-nestjs/effect |
Native Effect v4 bridge: KeelEffectInterceptor, KeelEffectFailure, isKeelEffectFailure, effectToObservable, streamToObservable, provideAmbientKeelContext, runKeelEffect, effectGuard, and effectPipe |
@chimp-labs/keel-nestjs/topology |
Static nestTopology, inspectNestModuleGraph, and inferNestInfra (zero runtime NestJS peer imports — safe for IaC scripts) |
@chimp-labs/keel-nestjs/tokens |
KEEL_CLIENT, KEEL_RUNTIME, keelToken, resolveInjectableToken, TenantAwareTable, and token inference utility types |
@chimp-labs/keel-nestjs/tx |
runInKeelTransaction, getActiveKeelTx, and getActiveKeelClient |
See the complete runnable demo project in examples/nestjs-keel/ (pnpm test and pnpm run plan:topology).