# NestJS head-to-head # NestJS head-to-head What this repository is for is not stated in prose this page can quote, so it cannot be established from this repository alone. - **Terms of use** — MIT [package.json:14]. - **Version** — `11.1.26` [package.json:3]. - **Editions** — whether this repository is the whole product or one edition of it cannot be established from this repository alone. - **Running it** — no run path was found in the parsed corpus, so how to start it cannot be established from this repository alone. ## What is in here Each part names what it holds before how much of it there is. The counts are read from the evidence census computed for this snapshot, one per part at most. - [Common](subsystem-packages-common) — decorators, exceptions, pipes, features; services. A file to open: `class-serializer.interceptor.ts` [packages/common/serializer/class-serializer.interceptor.ts:34]. 353 entities under `packages/common` [census]. - [Core](subsystem-packages-core) — injector, router, errors, inspector; HTTP endpoints and middleware. A file to open: `container.ts` [packages/core/middleware/container.ts:27]. 284 entities under `packages/core` [census]. - [Websockets](subsystem-packages-websockets) — decorators, context, exceptions, hooks; enum and type alia. A file to open: `ws-adapter.ts` [packages/websockets/adapters/ws-adapter.ts:8]. 87 entities under `packages/websockets` [census]. - [Microservices](subsystem-packages-microservices) — external, decorators, events, errors; HTTP endpoints and module. A file to open: `server.ts` [packages/microservices/server/server.ts:150]. 429 entities under `packages/microservices` [census]. - [Platform Express](subsystem-packages-platform-express) — multer, adapters; module. A file to open: `multer.module.ts` [packages/platform-express/multer/multer.module.ts:14]. 52 entities under `packages/platform-express` [census]. - [Platform Fastify](subsystem-packages-platform-fastify) — external, decorators, adapters; type aliases and class. A file to open: `fastify-adapter.ts` [packages/platform-fastify/adapters/fastify-adapter.ts:124]. 44 entities under `packages/platform-fastify` [census]. - [Testing](subsystem-packages-testing) — services; type aliases and classes. A file to open: `mock-factory.ts` [packages/testing/interfaces/mock-factory.ts:3]. 41 entities under `packages/testing` [census]. - [Platform Socket.io](subsystem-packages-platform-socket-io) — adapters; class. A file to open: `io-adapter.ts` [packages/platform-socket.io/adapters/io-adapter.ts:14]. 31 entities under `packages/platform-socket.io` [census]. - [Platform Ws](subsystem-packages-platform-ws) — adapters; class. A file to open: `ws-adapter.ts` [packages/platform-ws/adapters/ws-adapter.ts:39]. 31 entities under `packages/platform-ws` [census]. - **Repository root and unclaimed files** — .github, tools, hooks; constants and functions. A file to open: `PULL_REQUEST_TEMPLATE.md` [.github/PULL_REQUEST_TEMPLATE.md:1]. 168 entities in files no part claims [census]. ## Trust and security, as the code carries it Topics below come from sweeping symbol names and file paths in the parsed corpus. They are not read from a security document: a page that takes its topics from what a document enumerates inherits whatever that document left out. - **Authentication** — `Session` [packages/common/decorators/http/route-params.decorator.ts:164], `OauthbearerProviderResponse` [packages/microservices/external/kafka.interface.ts:85]. - **Authorization** — `GUARDS_METADATA` [packages/common/constants.ts:23], `SCOPE_OPTIONS_METADATA` [packages/common/constants.ts:16], `UseGuards` [packages/common/decorators/core/use-guards.decorator.ts:28]. - **Secrets and configuration** — `InjectionToken` [packages/common/interfaces/modules/injection-token.interface.ts:7], `generateOptionsInjectionToken` [packages/common/module-utils/utils/generate-options-injection-token.util.ts:3], `ENHANCER_TOKEN_TO_SUBTYPE_MAP` [packages/core/constants.ts:17]. - **Transport and browser boundaries** — `HttpStatus` [packages/common/enums/http-status.enum.ts:4], `CorsOptions` [packages/common/interfaces/external/cors-options.interface.ts:23], `CorsOptionsCallback` [packages/common/interfaces/external/cors-options.interface.ts:58]. - **Input validation** — `PIPES_METADATA` [packages/common/constants.ts:22], `UsePipes` [packages/common/decorators/core/use-pipes.decorator.ts:29], `ValidationError` [packages/common/interfaces/external/validation-error.interface.ts:9]. - **Cryptography** — `DeepHashedModuleOpaqueKeyFactory` [packages/core/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.ts:13]. No symbol name or path in the parsed corpus matched rate limiting and abuse and audit and access logging. That is a statement about the names this codebase uses, not a finding about what it does. ## What this repository carries One row per capability lane, scoped to where the evidence for it sits. A lane marked as not found means nothing in the parsed corpus matched it — which is a fact about this parse, and the honest place to start looking rather than the end of the question. | Capability | In this repository | Where | |---|---|---| | Database models | 0 [census] | — | | HTTP endpoints | 9 [census] | `packages/core/middleware/container.ts`, `packages/core/middleware/middleware-module.ts` | | Controllers | 0 [census] | — | | Configuration | not found | — | | Automated tests | yes | — | | Written documentation | yes | `.github/PULL_REQUEST_TEMPLATE.md`, `CODE_OF_CONDUCT.md` | | Licence | yes | `LICENSE` | ## Where next Five ways in. Each one names pages that exist in this documentation, or says what the repository holds instead. - **Deploying it** — no deployment descriptor and no deployment page were found; how this is deployed cannot be established from this repository alone. - **Understanding the architecture** — [System Overview](system-overview), [Common](subsystem-packages-common), [Core](subsystem-packages-core) and [Websockets](subsystem-packages-websockets). - **Contributing a change** — [Documentation health](documentation-health) and [CONTRIBUTING.md:1]. - **Reviewing security** — the topics above, starting at [packages/common/decorators/http/route-params.decorator.ts:164]. - **Extending it** — [Core](subsystem-packages-core) and [Microservices](subsystem-packages-microservices). ## How this page was assembled Every count above is read from the evidence census computed for this snapshot; every other claim points at a file and a line you can open. The census covers 1520 entities and 2691 relationships across 10 parts [census], and it passed its own independent recount [census]. # NestJS head-to-head ## Overview Auto-generated technical documentation for **NestJS head-to-head** — 1520 entities (413 doc comments, 259 interfaces, 259 classs, 183 functions). ## Architecture ```mermaid flowchart LR service_ConsoleLogger_38089336["ConsoleLogger"] service_Logger_56f71189["Logger"] service_ClassSerializerInterceptor_38d66def["ClassSerializerInterceptor"] module_ClientsModule_41eb342d["ClientsModule"] module_MulterModule_1337416c["MulterModule"] ``` ## Modules - **ClientsModule** - **MulterModule** ## Entry Points - `GET /` → moduleKey - `GET /` → moduleName - `ALL /` → handler - `GET /` → metatype - `GET /` → handler - `ALL /` → handler - `GET /` → modulesContainer - `GET /` → normalizedPattern - `GET /` → route ## Key Components _The most-referenced entities — start here._ - **Module** (function) — referenced 181× - **Get** (constant) — referenced 77× - **Scope** (enum) — referenced 69× - **Inject** (function) — referenced 64× - **Type** (interface) — referenced 62× - **Logger** (service) — referenced 52× - **ExecutionContext** (interface) — referenced 48× - **Post** (constant) — referenced 37× - **NestInterceptor** (interface) — referenced 36× - **CallHandler** (interface) — referenced 32× ## Subsystems Ordered by how much of the rest of the system depends on them, not by how much code they contain. A small module many things import shapes this codebase more than a large one nothing imports. | Subsystem | Depended on by | Entities | Starts at | |---|---|---|---| | **Common** | 8 | 353 | `DefaultValuePipe`, `ParseFilePipe` | | **Core** | 5 | 284 | `moduleKey`, `moduleName` | | **Websockets** | 4 | 87 | `Readme.md`, `BaseWsInstance` | | **Microservices** | 1 | 429 | `normalizedPattern`, `route` | | **Platform Express** | 0 | 52 | `MulterModule` | | **Platform Fastify** | 0 | 44 | `Readme.md`, `FastifyAdapter` | | **Testing** | 0 | 41 | `TestingLogger`, `Readme.md` | | **Platform Socket.io** | 0 | 31 | `Readme.md`, `IoAdapter` | | **Platform Ws** | 0 | 31 | `Readme.md`, `WsAdapter` | `Common` depend on no other subsystem here — they are the leaves. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `*.interface.ts` | across the repository | 128 | `type.interface.ts`, `file.interface.ts`, `edge.interface.ts`, `node.interface.ts` | | `*.exception.ts` | across the repository | 55 | `gone.exception.ts`, `http.exception.ts`, `runtime.exception.ts`, `conflict.exception.ts` | | `*.decorator.ts` | across the repository | 39 | `sse.decorator.ts`, `ctx.decorator.ts`, `ack.decorator.ts`, `bind.decorator.ts` | | `*.util.ts` | across the repository | 21 | `cli-colors.util.ts`, `forward-ref.util.ts`, `is-log-level.util.ts`, `load-package.util.ts` | | `*.pipe.ts` | across the repository | 10 | `parse-int.pipe.ts`, `parse-file.pipe.ts`, `parse-bool.pipe.ts`, `parse-date.pipe.ts` | | `*.enum.ts` | across the repository | 10 | `transport.enum.ts`, `http-status.enum.ts`, `version-type.enum.ts`, `ws-paramtype.enum.ts` | # Documentation health 1087 symbols have a reference page in this documentation. This page says how each of them came to be described, because "documented" covers four situations a reader should not have to treat alike. ## Where the descriptions come from | | Symbols | What it means for a reader | |---|---:|---| | Written by the author | 158 of 1087 | A doc comment in the source. Nothing generated improves on this. | | Generated, with citations | 104 of 1087 | Points at specific `file:line` ranges you can open and check. | | Generated, without citations | 293 of 1087 | Often right, but nothing anchors it. Treat as a starting point. | | Not described | 532 of 1087 | The page shows structure only — signature, members, references. | **262 of 1087 descriptions can be checked against source** — 158 because the author wrote them next to the code, 104 because the generator cited the lines it read. The rest are shown, and marked, for what they are. 32 symbols carried a description that is the same sentence repeated across many symbols — a README or manifest description copied per package. Those are not counted as authored: a sentence pasted per package is presence, not authorship. ## Why there is no coverage percentage A percentage counts whether a comment exists, so the cheapest way to raise it is to add empty ones. SonarQube withdrew its comment-density metric over this; studies of "covered" API documentation classify 43–51% of it as carrying no information; and a missing-comment warning has been measured producing 1,774 junk comments in a single codebase. The counts above cannot be moved that way — a doc comment that only restates the symbol name is not counted as one. ## Where the gaps are Undescribed symbols by the part of the system they sit in — worst first, so the next unit of documentation effort has an address. This is the table to bring to planning. | Area | Undescribed | Of | Share | |---|---:|---:|---:| | [`packages/microservices`](subsystem-packages-microservices) | 227 | 399 | 57% | | [`packages/common`](subsystem-packages-common) | 131 | 322 | 41% | | [`packages/core`](subsystem-packages-core) | 120 | 253 | 47% | | [`packages/websockets`](subsystem-packages-websockets) | 23 | 57 | 40% | | [`packages/platform-express`](subsystem-packages-platform-express) | 14 | 22 | 64% | | [`packages/platform-fastify`](subsystem-packages-platform-fastify) | 9 | 14 | 64% | | `tools/gulp` | 5 | 6 | 83% | | [`packages/testing`](subsystem-packages-testing) | 2 | 11 | 18% | | `hooks/mocha-init-hook.ts` | 1 | 1 | 100% | ## What can be checked A claim on these pages is anchored when it points at something a reader can open: a `file:line` range in the source, or a `[census]` tag naming the arithmetic behind a number. Anything else is prose you would have to take on trust. These counts say which is which. They do not say the anchored claims are right — only that they can be checked. | | Count | What it means | |---|---:|---| | Pages read by this audit | 1099 [census] | Every page in the set as it stood before this section was written. This section's own claims are not counted below. | | Pages carrying an anchored claim | 105 of 1099 [census] | The page points at source or at a census at least once. | | Anchored claims | 1081 [census] | One per `file:line` reference and per census tag. Brackets inside code samples are code, and are not counted. | | … pointing at source | 1066 of 1081 [census] | A path and a line you can open. | | … pointing at a census | 15 of 1081 [census] | A number computed before anything was written. | Whether those citations land in files that exist was NOT CHECKED for this build: the audit was given no way to look a path up. The count above is of citations made, not of citations verified — and reporting them as sound on that basis would be the invention this page exists to catch. Every count in this section and the two below is arithmetic over these pages, redone on each build; `[census]` marks a figure read from that arithmetic rather than written by hand. ## Where the docs and the code disagree One lint reads every page for a single pattern: a sentence stating runtime behaviour — what listens, what validates, what retries — whose only evidence is a prose document. A README saying the server listens on a port is testimony ABOUT the code, not the behaviour itself, and a sentence citing it for the behaviour has quietly turned one into the other. The honest forms either cite the source that listens, or keep the attribution in the sentence. No page states runtime behaviour on the authority of a prose document alone. That is an absence of the pattern rather than proof the pages and the code agree: the lint reads verbs and file extensions, and it misses what it was not taught to see. ## What we have not written yet The evidence census lists, for each part of this repository, the reader-topics that part's contents warrant: a part holding database models owes its readers a data model however few models it holds. This section holds that list against the headings the pages for each part actually carry. 1 of 22 reader-topics, across 10 parts of this repository, have no page carrying a heading that answers for them [census]. | Part | Topics no heading answers for | Pages for this part | |---|---|---:| | `overview` | wiring | 7 [census] | A topic counts as written when any page for its part carries a heading naming it — "Fields" answers for a data model, "Endpoint" for an API surface, "Dependencies" for wiring. The match is deliberately loose in that direction: a topic covered under a heading nobody predicted must not be reported as missing, so the error this makes is silence, never a false accusation of absence. 3 pages name no source path [census], so they were matched to no part and can cover no topic above — the pages about this documentation itself are among them. # ClientsModule **Kind:** Module **Source:** [`packages/microservices/module/clients.module.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/clients.module.ts#L17) **Part of:** [Microservices](subsystem-packages-microservices) ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `Module` - IMPORTS → `OnApplicationShutdown` - IMPORTS → `Provider` - IMPORTS → `Type` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ConfigService` — `integration/microservices/src/app.module.ts`:18 - `ConfigService` — `integration/microservices/src/tcp-tls/app.module.ts`:29 - `MathModule` — `sample/03-microservices/src/math/math.module.ts`:6 - `HeroModule` — `sample/04-grpc/src/hero/hero.module.ts`:6 # ClientProxy **Kind:** Class **Source:** [`packages/microservices/client/client-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-proxy.ts#L38) **Part of:** [Microservices](subsystem-packages-microservices) `ClientProxy` is the base abstraction for communicating with NestJS microservices through a configured transport. It manages connection lifecycle, request-response messaging via `send()`, and event-based messaging via `emit()`, while delegating transport-specific publishing and packet handling to implementations. ## Methods | Method | Signature | Returns | |---|---|---| | `connect` | `connect()` | `Promise` | | `close` | `close()` | `any` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | | `send` | `send(pattern: any, data: TInput)` | `Observable` | | `emit` | `emit(pattern: any, data: TInput)` | `Observable` | | `publish` | `publish(packet: ReadPacket, callback: (packet: WritePacket) => void)` | `() => void` | | `dispatchEvent` | `dispatchEvent(packet: ReadPacket)` | `Promise` | | `createObserver` | `createObserver(observer: Observer)` | `(packet: WritePacket) => void` | | `serializeError` | `serializeError(err: any)` | `any` | | `serializeResponse` | `serializeResponse(response: any)` | `any` | | `assignPacketId` | `assignPacketId(packet: ReadPacket)` | `ReadPacket & PacketId` | | `connect$` | `connect$(instance: any, errorEvent: undefined, connectEvent: undefined)` | `Observable` | | `getOptionsProp` | `getOptionsProp(obj: Options, prop: Attribute)` | `Options[Attribute]` | | `getOptionsProp` | `getOptionsProp(obj: Options, prop: Attribute, defaultValue: DefaultValue)` | `Required[Attribute]` | | `getOptionsProp` | `getOptionsProp(obj: Options, prop: Attribute, defaultValue: DefaultValue)` | `void` | | `normalizePattern` | `normalizePattern(pattern: MsPattern)` | `string` | | `initializeSerializer` | `initializeSerializer(options: ClientOptions['options'])` | `void` | | `initializeDeserializer` | `initializeDeserializer(options: ClientOptions['options'])` | `void` | ## Properties | Property | Type | |---|---| | `routingMap` | `any` | | `serializer` | `ProducerSerializer` | | `deserializer` | `ProducerDeserializer` | | `_status$` | `any` | ## Where it refuses work - `ClientProxy` stops the work with an early return when `isNil(pattern) || isNil(data)`, in 2 places. - `ClientProxy` stops the work with an early return when `isDisposed`. ## Diagram ```mermaid graph LR App[Application Service] --> ClientProxy ClientProxy --> Connect[connect()] ClientProxy --> Send[send() request-response] ClientProxy --> Emit[emit() event] Send --> Publish[publish()] Emit --> Dispatch[dispatchEvent()] Publish --> Transport[Configured Transport] Dispatch --> Transport Transport --> Observer[createObserver()] Observer --> App ``` ## Usage ```ts import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices'; import { firstValueFrom } from 'rxjs'; const client: ClientProxy = ClientProxyFactory.create({ transport: Transport.TCP, options: { host: 'localhost', port: 3001, }, }); async function getUser(userId: string) { await client.connect(); const user = await firstValueFrom( client.send({ cmd: 'get_user' }, { userId }), ); return user; } async function notifyUserCreated(user: { id: string; email: string }) { await firstValueFrom( client.emit('user.created', user), ); } async function shutdown() { client.close(); } ``` ## AI Coding Instructions - Use `send()` for request-response patterns and subscribe to or convert its returned `Observable` with `firstValueFrom()`. - Use `emit()` for fire-and-forget events; consumers should register matching event patterns. - Ensure the proxy is connected before sending messages when using manually created clients, and close it during application shutdown. - Keep transport-specific behavior inside concrete `ClientProxy` implementations; use `publish()` and `dispatchEvent()` as extension points rather than duplicating serialization logic. - Preserve error serialization through `serializeError()` so remote exceptions remain consistent across transports. ## Relationships - IMPORTS → `randomStringGenerator` - IMPORTS → `isNil` ## Used by 20 references from 13 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Injected or called by (7) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `AppController` — `integration/microservices/src/tcp-tls/app.controller.ts`:22 - `AppController` — `integration/microservices/src/tcp-tls/app.controller.ts`:22 - `AppController` — `integration/microservices/src/tcp-tls/app.controller.ts`:22 - `MathController` — `sample/03-microservices/src/math/math.controller.ts`:6 ### Imported by (13) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `MqttBroadcastController` — `integration/microservices/src/mqtt/mqtt-broadcast.controller.ts`:11 - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 - `NatsBroadcastController` — `integration/microservices/src/nats/nats-broadcast.controller.ts`:11 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 - `RedisBroadcastController` — `integration/microservices/src/redis/redis-broadcast.controller.ts`:11 - `RedisController` — `integration/microservices/src/redis/redis.controller.ts`:12 - `RMQFanoutExchangeProducerController` — `integration/microservices/src/rmq/fanout-exchange-producer-rmq.controller.ts`:9 …and 5 more. # MessagePattern **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L33) **Part of:** [Microservices](subsystem-packages-microservices) Subscribes to incoming messages which fulfils chosen pattern. `MessagePattern()` marks a controller method as a handler for messages matching a specific request pattern. When a configured NestJS microservice transport receives a matching message, it invokes the decorated method and sends its return value back to the requester. ## Signature ```ts function MessagePattern(metadata: T, transportOrExtras: Transport | symbol | Record, maybeExtras: Record): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `metadata` | `T` | | `transportOrExtras` | `Transport | symbol | Record` | | `maybeExtras` | `Record` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[Microservice Client] -->|send pattern + payload| Transport[Configured Transport] Transport --> Server[NestJS Microservice] Server -->|match pattern| Handler["@MessagePattern() handler"] Handler -->|response| Transport Transport --> Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; @Controller() export class UsersController { @MessagePattern({ cmd: 'get_user' }) async getUser(@Payload() userId: string) { return { id: userId, name: 'Ada Lovelace', }; } } ``` ## AI Coding Instructions - Apply `@MessagePattern()` to methods in controllers registered with a NestJS microservice application. - Use stable, shared pattern names or objects (for example, `{ cmd: 'get_user' }`) that match the patterns sent by clients. - Return a value, `Promise`, or `Observable` when the caller expects a request-response result. - Use `@Payload()` to extract message data and `@Ctx()` when transport-specific context is required. - Use `@EventPattern()` instead for fire-and-forget events that do not require a response. ## Used by 17 references from 17 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (17) - `ExternalSvcController` — `integration/inspector/src/external-svc/external-svc.controller.ts`:7 - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `KafkaMessagesController` — `integration/microservices/src/kafka/kafka.messages.controller.ts`:9 - `KafkaConcurrentMessagesController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.messages.controller.ts`:6 - `MqttBroadcastController` — `integration/microservices/src/mqtt/mqtt-broadcast.controller.ts`:11 - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 - `NatsBroadcastController` — `integration/microservices/src/nats/nats-broadcast.controller.ts`:11 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 …and 9 more. # Transport **Kind:** Enum **Source:** [`packages/microservices/enums/transport.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/enums/transport.enum.ts#L1) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `TCP` - `REDIS` - `NATS` - `MQTT` - `GRPC` - `RMQ` - `KAFKA` ## Used by 21 references from 21 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (21) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `ConfigService` — `integration/microservices/src/app.module.ts`:18 - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 - `AdvancedGrpcController` — `integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`:14 - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 - `MqttBroadcastController` — `integration/microservices/src/mqtt/mqtt-broadcast.controller.ts`:11 - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 …and 13 more. # ClientKafka **Kind:** Class **Source:** [`packages/microservices/client/client-kafka.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-kafka.ts#L58) **Part of:** [Microservices](subsystem-packages-microservices) `ClientKafka` is a NestJS microservices client proxy for producing Kafka messages and consuming response messages for request-response patterns. It manages Kafka producer and consumer lifecycle, topic subscriptions, response callbacks, offset commits, and access to the underlying Kafka client. **Extends:** `ClientProxy` **Implements:** `ClientKafkaProxy` ## Methods | Method | Signature | Returns | |---|---|---| | `subscribeToResponseOf` | `subscribeToResponseOf(pattern: unknown)` | `void` | | `close` | `close()` | `Promise` | | `connect` | `connect()` | `Promise` | | `bindTopics` | `bindTopics()` | `Promise` | | `createClient` | `createClient()` | `T` | | `createResponseCallback` | `createResponseCallback()` | `(payload: EachMessagePayload) => any` | | `getConsumerAssignments` | `getConsumerAssignments()` | `void` | | `emitBatch` | `emitBatch(pattern: any, data: { messages: TInput[] })` | `Observable` | | `commitOffsets` | `commitOffsets(topicPartitions: TopicPartitionOffsetAndMetadata[])` | `Promise` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `registerConsumerEventListeners` | `registerConsumerEventListeners()` | `void` | | `registerProducerEventListeners` | `registerProducerEventListeners()` | `void` | | `dispatchBatchEvent` | `dispatchBatchEvent(packets: ReadPacket<{ messages: TInput[] }>)` | `Promise` | | `dispatchEvent` | `dispatchEvent(packet: OutgoingEvent)` | `Promise` | | `getReplyTopicPartition` | `getReplyTopicPartition(topic: string)` | `string` | | `publish` | `publish(partialPacket: ReadPacket, callback: (packet: WritePacket) => any)` | `() => void` | | `getResponsePatternName` | `getResponsePatternName(pattern: string)` | `string` | | `setConsumerAssignments` | `setConsumerAssignments(data: ConsumerGroupJoinEvent)` | `void` | | `initializeSerializer` | `initializeSerializer(options: KafkaOptions['options'])` | `void` | | `initializeDeserializer` | `initializeDeserializer(options: KafkaOptions['options'])` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `client` | `Kafka | null` | | `parser` | `KafkaParser | null` | | `initialized` | `Promise | null` | | `responsePatterns` | `string[]` | | `consumerAssignments` | `{ [key: string]: number }` | | `brokers` | `string[] | BrokersFunction` | | `clientId` | `string` | | `groupId` | `string` | | `producerOnlyMode` | `boolean` | | `_consumer` | `Consumer | null` | | `_producer` | `Producer | null` | ## Where it refuses work - `ClientKafka` stops the work with `Error` when `!this._consumer` — “No consumer initialized. Please, call the "connect" method first.”. - `ClientKafka` stops the work with `Error` when `!this._producer` — “No producer initialized. Please, call the "connect" method first.”. - `ClientKafka` stops the work with `Error` when `!this.client` — “Not initialized. Please call the "connect" method first.”. - `ClientKafka` stops the work with `InvalidKafkaClientTopicException` when `isUndefined(minimumPartition)`. - `ClientKafka` stops the work with an early return when `this.initialized`. - `ClientKafka` stops the work with an early return when `!this._consumer`. ## When something fails - `ClientKafka` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR A[Application Service] --> B[ClientKafka] B --> C[Kafka Producer] B --> D[Kafka Consumer] C --> E[Request / Event Topics] E --> F[Kafka Brokers] F --> G[Response Topics] G --> D D --> H[Response Callback] H --> A ``` ## AI Coding Instructions - Call `subscribeToResponseOf(pattern)` before `connect()` when using `send()` for Kafka request-response messaging. - Use `send()` for request-response flows and `emit()` or `emitBatch()` for event-driven, fire-and-forget publishing. - Always close the client during application shutdown to disconnect the Kafka producer and consumer cleanly. - Keep Kafka client and consumer settings, especially `clientId`, broker addresses, and consumer `groupId`, consistent with deployment configuration. - Use `unwrap()` only when direct access to the underlying KafkaJS client is required; prefer the `ClientKafka` APIs for normal messaging. ## Relationships - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `isNil` - IMPORTS → `isUndefined` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 # ClientTCP **Kind:** Class **Source:** [`packages/microservices/client/client-tcp.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-tcp.ts#L16) **Part of:** [Microservices](subsystem-packages-microservices) `ClientTCP` is a TCP-based microservice client that establishes and manages a socket connection to a remote NestJS microservice. It handles connection lifecycle events, routes incoming responses to pending requests, and recreates or closes socket resources when errors or disconnects occur. **Extends:** `ClientProxy` ## Methods | Method | Signature | Returns | |---|---|---| | `connect` | `connect()` | `Promise` | | `handleResponse` | `handleResponse(buffer: unknown)` | `Promise` | | `createSocket` | `createSocket()` | `TcpSocket` | | `close` | `close()` | `void` | | `registerConnectListener` | `registerConnectListener(socket: TcpSocket)` | `void` | | `registerErrorListener` | `registerErrorListener(socket: TcpSocket)` | `void` | | `registerCloseListener` | `registerCloseListener(socket: TcpSocket)` | `void` | | `handleError` | `handleError(err: any)` | `void` | | `handleClose` | `handleClose()` | `void` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | | `publish` | `publish(partialPacket: ReadPacket, callback: (packet: WritePacket) => any)` | `() => void` | | `dispatchEvent` | `dispatchEvent(packet: ReadPacket)` | `Promise` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `port` | `number` | | `host` | `string` | | `socketClass` | `Type` | | `tlsOptions` | `ConnectionOptions` | | `maxBufferSize` | `number` | | `socket` | `TcpSocket | null` | | `connectionPromise` | `Promise | null` | | `pendingEventListeners` | `Array<{ event: keyof TcpEvents; callback: TcpEvents[keyof TcpEvents]; }>` | ## Where it refuses work - `ClientTCP` stops the work with `Error` when `!this.socket` — “Not initialized. Please call the "connect" method first.”. - `ClientTCP` stops the work with an early return when `this.connectionPromise`. - `ClientTCP` stops the work with an early return when `err instanceof EmptyError`. - `ClientTCP` stops the work with an early return when `!callback`. - `ClientTCP` stops the work with an early return when `isDisposed || err`. - `ClientTCP` stops the work with an early return when `this.maxBufferSize !== undefined && this.socketClass === JsonSocket`. ## When something fails - `ClientTCP` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR App[Application Service] --> Client[ClientTCP] Client --> Connect[connect()] Connect --> Socket[createSocket()] Socket --> Server[TCP Microservice Server] Server --> Response[Incoming Response] Response --> HandleResponse[handleResponse()] HandleResponse --> Pending[Resolve/Reject Pending Request] Socket --> Error[error Event] Error --> HandleError[handleError()] Socket --> Close[close Event] Close --> HandleClose[handleClose()] ``` ## Usage ```ts import { ClientTCP } from '@nestjs/microservices'; async function requestUser(userId: string) { const client = new ClientTCP({ host: '127.0.0.1', port: 3001, }); try { await client.connect(); const user = await client .send({ cmd: 'get_user' }, { userId }) .toPromise(); return user; } finally { client.close(); } } ``` ## AI Coding Instructions - Call `connect()` before relying on the client for requests when connection readiness must be guaranteed. - Use `send()` for request-response messaging and ensure subscriptions/promises are handled so pending requests can be cleaned up. - Preserve socket lifecycle listener registration when changing `createSocket()` or connection logic; `connect`, `error`, and `close` events are required for reliable recovery. - Route inbound TCP payloads through `handleResponse()` so response correlation and pending callback resolution continue to work. - Always call `close()` during application shutdown or when disposing manually created client instances. ## How it works `ClientTCP` is a public `ClientProxy` implementation for a TCP connection. It maintains a wrapped `TcpSocket`, a cached in-progress connection promise, pending socket-event listeners, and a request-ID-to-callback routing map inherited from `ClientProxy`. [client-tcp.ts:16-28](packages/microservices/client/client-tcp.ts#L16-L28) [client-proxy.ts:38-45](packages/microservices/client/client-proxy.ts#L38-L45) ## Construction and configuration The constructor accepts TCP client options, selecting port `3000`, host `localhost`, and `JsonSocket` when those options are absent; it also reads optional TLS settings, a custom socket class, and `maxBufferSize`. [client-tcp.ts:30-40](packages/microservices/client/client-tcp.ts#L30-L40) [constants.ts:3-4](packages/microservices/constants.ts#L3-L4) [client-metadata.interface.ts:37-51](packages/microservices/interfaces/client-metadata.interface.ts#L37-L51) It initializes the serializer from `options.serializer` or defaults to `IdentitySerializer`, whose `serialize()` returns its input unchanged. It initializes the deserializer from `options.deserializer` or defaults to `IncomingResponseDeserializer`. [client-proxy.ts:208-231](packages/microservices/client/client-proxy.ts#L208-L231) [identity.serializer.ts:3-6](packages/microservices/serializers/identity.serializer.ts#L3-L6) Without a custom socket class, `JsonSocket` writes packets as `#`, parses that framing from received data, and emits each parsed JSON value as a `message` event. [json-socket.ts:26-28](packages/microservices/helpers/json-socket.ts#L26-L28) [json-socket.ts:30-89](packages/microservices/helpers/json-socket.ts#L30-L89) [json-socket.ts:92-97](packages/microservices/helpers/json-socket.ts#L92-L97) `maxBufferSize` is passed only when the selected socket class is exactly `JsonSocket`; custom socket classes receive only the underlying socket. [client-tcp.ts:113-121](packages/microservices/client/client-tcp.ts#L113-L121) `JsonSocket` defaults its buffer limit to `(512 * 1024 * 1024) / 4` characters and throws `MaxPacketLengthExceededException` after clearing its buffer when the accumulated buffer exceeds that limit. [json-socket.ts:7-24](packages/microservices/helpers/json-socket.ts#L7-L24) [json-socket.ts:39-43](packages/microservices/helpers/json-socket.ts#L39-L43) ## Connecting and status `connect()` returns the existing connection promise if one is already stored. Otherwise, it creates a socket, registers connect, close, and error listeners, attaches listeners registered before connection, and clears the pending-listener list. [client-tcp.ts:42-54](packages/microservices/client/client-tcp.ts#L42-L54) For non-TLS configuration, it calls the wrapped socket’s `connect(port, host)` method. With TLS options, `createSocket()` calls `tlsConnect()` with the TLS options plus the selected host and port; therefore `connect()` does not separately call `socket.connect()` in that case. [client-tcp.ts:65-68](packages/microservices/client/client-tcp.ts#L65-L68) [client-tcp.ts:99-121](packages/microservices/client/client-tcp.ts#L99-L121) The returned promise resolves or rejects from the first underlying `connect` or `error` event. An RxJS `EmptyError` is converted into a resolved `undefined` result; other errors are rethrown. After the connection event, it subscribes to wrapped-socket `message` events and forwards their payloads to `handleResponse()`. [client-tcp.ts:56-76](packages/microservices/client/client-tcp.ts#L56-L76) [client-proxy.ts:165-177](packages/microservices/client/client-proxy.ts#L165-L177) On `connect`, the client emits `TcpStatus.CONNECTED` through its inherited status stream. On `close`, it emits `TcpStatus.DISCONNECTED` and runs close handling. On an `error` whose `code` is `ECONNREFUSED`, it emits `DISCONNECTED`; other errors are passed to `handleError()`, which logs them through Nest’s `Logger`. [client-tcp.ts:129-154](packages/microservices/client/client-tcp.ts#L129-L154) The inherited `status` getter exposes that stream and suppresses consecutive duplicate statuses. [client-proxy.ts:47-52](packages/microservices/client/client-proxy.ts#L47-L52) ## Requests, events, and responses Inherited `send(pattern, data)` rejects a `null` or `undefined` pattern or data with `InvalidMessageException`. Otherwise, on subscription, it connects and invokes this class’s `publish()` method. [client-proxy.ts:86-101](packages/microservices/client/client-proxy.ts#L86-L101) `publish()` assigns a generated packet ID, serializes the packet, stores the response callback under that ID, and sends the serialized packet through the current socket. It returns an unsubscription function that removes that callback from the routing map. If ID assignment, serialization, map insertion, or sending throws synchronously, it calls the callback with `{ err }` and returns a no-op cleanup function. [client-tcp.ts:189-205](packages/microservices/client/client-tcp.ts#L189-L205) [client-proxy.ts:160-163](packages/microservices/client/client-proxy.ts#L160-L163) Inherited `emit(pattern, data)` has the same `null`/`undefined` validation, connects, and calls `dispatchEvent()`. [client-proxy.ts:111-126](packages/microservices/client/client-proxy.ts#L111-L126) `dispatchEvent()` normalizes the pattern to a route, serializes the resulting packet, and sends it through the current socket. [client-tcp.ts:207-214](packages/microservices/client/client-tcp.ts#L207-L214) [client-proxy.ts:204-205](packages/microservices/client/client-proxy.ts#L204-L205) For each received `message`, `handleResponse()` deserializes the payload, finds the callback by deserialized ID, and does nothing if no callback exists. When the response has `isDisposed` or `err`, it invokes the callback with `isDisposed: true`; otherwise it invokes it with the error and response values as deserialized. [client-tcp.ts:79-97](packages/microservices/client/client-tcp.ts#L79-L97) The default response deserializer treats packets already containing `err`, `response`, or `isDisposed` as response-shaped values. Other values are mapped to `{ id, response: value, isDisposed: true }`. [incoming-response.deserializer.ts:7-32](packages/microservices/deserializers/incoming-response.deserializer.ts#L7-L32) ## Socket access and lifecycle `on(event, callback)` attaches the listener immediately when a socket exists; before connection, it queues the listener for attachment during `connect()`. Its typed event set includes `error`, `connect`, `end`, `close`, `timeout`, `drain`, and `lookup`. [client-tcp.ts:169-178](packages/microservices/client/client-tcp.ts#L169-L178) [tcp.events.ts:26-39](packages/microservices/events/tcp.events.ts#L26-L39) `unwrap()` returns the underlying Node socket. It throws `Error('Not initialized. Please call the "connect" method first.')` when no wrapped socket currently exists. [client-tcp.ts:180-187](packages/microservices/client/client-tcp.ts#L180-L187) `close()` ends the current wrapped socket when present, runs close handling, and discards queued event listeners. [client-tcp.ts:123-127](packages/microservices/client/client-tcp.ts#L123-L127) Close handling clears the socket and cached connection promise. If request callbacks remain, it calls each with `Error('Connection closed')` and clears the routing map. [client-tcp.ts:156-167](packages/microservices/client/client-tcp.ts#L156-L167) ## Relationships - IMPORTS → `Logger` - IMPORTS → `Type` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ConfigService` — `integration/microservices/src/app.module.ts`:18 - `ConfigService` — `integration/microservices/src/tcp-tls/app.module.ts`:29 # ClientGrpcProxy **Kind:** Class **Source:** [`packages/microservices/client/client-grpc.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-grpc.ts#L31) **Part of:** [Microservices](subsystem-packages-microservices) `ClientGrpcProxy` is the NestJS microservices client implementation for communicating with gRPC services. It loads protobuf definitions, creates gRPC client instances for configured services, and exposes service methods as RxJS `Observable` streams for unary, server-streaming, client-streaming, and bidirectional-streaming RPCs. **Extends:** `ClientProxy` **Implements:** `ClientGrpc` ## Methods | Method | Signature | Returns | |---|---|---| | `getService` | `getService(name: string)` | `T` | | `getClientByServiceName` | `getClientByServiceName(name: string)` | `T` | | `createClientByServiceName` | `createClientByServiceName(name: string)` | `void` | | `getKeepaliveOptions` | `getKeepaliveOptions()` | `void` | | `createServiceMethod` | `createServiceMethod(client: any, methodName: string)` | `(...args: unknown[]) => Observable` | | `createStreamServiceMethod` | `createStreamServiceMethod(client: unknown, methodName: string)` | `(...args: any[]) => Observable` | | `createUnaryServiceMethod` | `createUnaryServiceMethod(client: any, methodName: string)` | `(...args: any[]) => Observable` | | `createClients` | `createClients()` | `any[]` | | `loadProto` | `loadProto()` | `any` | | `lookupPackage` | `lookupPackage(root: any, packageName: string)` | `void` | | `close` | `close()` | `void` | | `connect` | `connect()` | `Promise` | | `send` | `send(pattern: any, data: TInput)` | `Observable` | | `getClient` | `getClient(name: string)` | `any` | | `publish` | `publish(packet: any, callback: (packet: any) => any)` | `any` | | `dispatchEvent` | `dispatchEvent(packet: any)` | `Promise` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `clients` | `any` | | `url` | `string` | | `grpcClients` | `GrpcClient[]` | ## Where it refuses work - `ClientGrpcProxy` stops the work with `InvalidGrpcServiceException` when `!clientRef`, in 2 places. - `ClientGrpcProxy` stops the work with an early return when `isClientCanceled`, in 2 places. - `ClientGrpcProxy` stops the work with an early return when `!isObject(this.options.keepalive)`. - `ClientGrpcProxy` stops the work with an early return when `call.finished`. - `ClientGrpcProxy` stops the work with an early return when `isRequestStream && isUpstreamSubject`. - `ClientGrpcProxy` stops the work with an early return when `error`. ## When something fails - `ClientGrpcProxy` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid graph LR A[Application Service] --> B[ClientGrpcProxy] B --> C[loadProto] C --> D[Proto Definition] B --> E[createClients] E --> F[gRPC Service Client] A --> G[getService serviceName] G --> F F --> H[Unary / Streaming RPC Method] H --> I[Observable Response] ``` ## Usage ```ts import { Injectable, OnModuleInit } from '@nestjs/common'; import { ClientGrpc, ClientProxyFactory, Transport } from '@nestjs/microservices'; import { Observable } from 'rxjs'; interface UsersService { findOne(data: { id: string }): Observable<{ id: string; name: string }>; } @Injectable() export class UsersClient implements OnModuleInit { private usersService: UsersService; private readonly client: ClientGrpc = ClientProxyFactory.create({ transport: Transport.GRPC, options: { package: 'users', protoPath: 'proto/users.proto', url: 'localhost:5000', }, }); onModuleInit() { // ClientGrpcProxy resolves the named gRPC service from the loaded proto. this.usersService = this.client.getService('UsersService'); } findUser(id: string) { return this.usersService.findOne({ id }); } } ``` ## AI Coding Instructions - Use `getService(serviceName)` after application initialization to retrieve a typed gRPC service client. - Configure `package`, `protoPath`, and `url` consistently with the server-side gRPC transport configuration. - Treat RPC method results as RxJS `Observable` values; use operators or `firstValueFrom()` rather than assuming promises. - Preserve protobuf service and method names exactly, including the service name passed to `getService()`. - Use the configured client factory or dependency injection instead of manually calling internal methods such as `loadProto()` or `createClients()`. ## Relationships - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `isFunction` - IMPORTS → `isObject` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 # ClientProxyFactory **Kind:** Class **Source:** [`packages/microservices/client/client-proxy-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-proxy-factory.ts#L32) **Part of:** [Microservices](subsystem-packages-microservices) `ClientProxyFactory` creates microservice client proxies based on the configured transport strategy, such as TCP, Redis, NATS, gRPC, or Kafka. It centralizes transport-specific client selection so application code can interact with a common `ClientProxy` interface for sending messages and emitting events. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(clientOptions: { transport: Transport.GRPC } & ClientOptions)` | `ClientGrpcProxy` | | `create` | `create(clientOptions: { transport: Transport.KAFKA } & ClientOptions)` | `ClientKafkaProxy` | | `create` | `create(clientOptions: ClientOptions)` | `ClientProxy` | | `create` | `create(clientOptions: CustomClientOptions)` | `ClientProxy` | | `create` | `create(clientOptions: ClientOptions | CustomClientOptions)` | `ClientProxy | ClientGrpcProxy | ClientKafkaProxy` | ## Diagram ```mermaid graph LR A[Client Options] --> B[ClientProxyFactory.create] B --> C{Transport Type} C -->|TCP / Redis / NATS / RMQ / MQTT| D[ClientProxy] C -->|gRPC| E[ClientGrpcProxy] C -->|Kafka| F[ClientKafkaProxy] D --> G[Microservice Broker or Server] E --> G F --> G ``` ## Usage ```ts import { ClientProxyFactory, Transport } from '@nestjs/microservices'; const client = ClientProxyFactory.create({ transport: Transport.TCP, options: { host: 'localhost', port: 3001, }, }); // Request-response communication const result = await client.send('users.findOne', { id: '123' }).toPromise(); // Event-based communication client.emit('users.created', { id: '123', email: 'user@example.com', }); ``` ## AI Coding Instructions - Use `ClientProxyFactory.create()` when creating clients dynamically outside of Nest dependency injection. - Match the client `transport` and connection options with the corresponding microservice server configuration. - Use `send()` for request-response patterns and `emit()` for fire-and-forget event patterns. - Call `connect()` explicitly when eager connection validation is required; otherwise, clients connect lazily on first use. - Prefer injected clients registered through `ClientsModule` for application services, reserving this factory for runtime or infrastructure-level client creation. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `DisconnectedClientController` — `integration/microservices/src/disconnected.controller.ts`:12 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 - `RMQFanoutExchangeProducerController` — `integration/microservices/src/rmq/fanout-exchange-producer-rmq.controller.ts`:9 - `RMQBroadcastController` — `integration/microservices/src/rmq/rmq-broadcast.controller.ts`:11 - `RMQController` — `integration/microservices/src/rmq/rmq.controller.ts`:16 - `RMQTopicExchangeController` — `integration/microservices/src/rmq/topic-exchange-rmq.controller.ts`:12 - `HttpController` — `integration/scopes/src/msvc/http.controller.ts`:4 # ClientMqtt **Kind:** Class **Source:** [`packages/microservices/client/client-mqtt.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-mqtt.ts#L28) **Part of:** [Microservices](subsystem-packages-microservices) `ClientMqtt` is a NestJS microservices client transport that communicates with MQTT brokers using publish/subscribe topics. It manages the MQTT connection lifecycle, derives request and response topic patterns, and handles broker events such as errors, reconnects, offline status, and disconnects. **Extends:** `ClientProxy` ## Methods | Method | Signature | Returns | |---|---|---| | `getRequestPattern` | `getRequestPattern(pattern: string)` | `string` | | `getResponsePattern` | `getResponsePattern(pattern: string)` | `string` | | `close` | `close()` | `void` | | `connect` | `connect()` | `Promise` | | `mergeCloseEvent` | `mergeCloseEvent(instance: MqttClient, source$: Observable)` | `Observable` | | `createClient` | `createClient()` | `MqttClient` | | `registerErrorListener` | `registerErrorListener(client: MqttClient)` | `void` | | `registerOfflineListener` | `registerOfflineListener(client: MqttClient)` | `void` | | `registerReconnectListener` | `registerReconnectListener(client: MqttClient)` | `void` | | `registerDisconnectListener` | `registerDisconnectListener(client: MqttClient)` | `void` | | `registerCloseListener` | `registerCloseListener(client: MqttClient)` | `void` | | `registerConnectListener` | `registerConnectListener(client: MqttClient)` | `void` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | | `createResponseCallback` | `createResponseCallback()` | `(channel: string, buffer: Buffer) => any` | | `publish` | `publish(partialPacket: ReadPacket, callback: (packet: WritePacket) => any)` | `() => void` | | `dispatchEvent` | `dispatchEvent(packet: ReadPacket)` | `Promise` | | `unsubscribeFromChannel` | `unsubscribeFromChannel(channel: string)` | `void` | | `initializeSerializer` | `initializeSerializer(options: MqttOptions['options'])` | `void` | | `mergePacketOptions` | `mergePacketOptions(requestOptions: MqttRecordOptions)` | `MqttRecordOptions | undefined` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `subscriptionsCount` | `any` | | `url` | `string` | | `mqttClient` | `MqttClient | null` | | `connectionPromise` | `Promise | null` | | `isInitialConnection` | `any` | | `isReconnecting` | `any` | | `pendingEventListeners` | `Array<{ event: keyof MqttEvents; callback: MqttEvents[keyof MqttEvents]; }>` | ## Where it refuses work - `ClientMqtt` stops the work with `Error` when `!this.mqttClient` — “Not initialized. Please call the "connect" method first.”. - `ClientMqtt` stops the work with an early return when `this.mqttClient`. - `ClientMqtt` stops the work with an early return when `err instanceof EmptyError`. - `ClientMqtt` stops the work with an early return when `err.code === ECONNREFUSED || err.code === ENOTFOUND`. - `ClientMqtt` stops the work with an early return when `!callback`. - `ClientMqtt` stops the work with an early return when `isDisposed || err`. ## When something fails - `ClientMqtt` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR App[Application Service] --> Client[ClientMqtt] Client --> Connect[connect()] Connect --> Broker[MQTT Broker] Client --> Request[getRequestPattern()] Client --> Response[getResponsePattern()] Request --> Broker Broker --> Response Client --> Events[Connection Event Listeners] Events --> Error[error] Events --> Offline[offline] Events --> Reconnect[reconnect] Events --> Disconnect[close] ``` ## AI Coding Instructions - Use `connect()` before sending requests when the client is created manually; Nest-managed clients may connect through application lifecycle handling. - Use `send()` for request/response communication and `emit()` for fire-and-forget MQTT events. - Keep request and response pattern generation consistent; `getRequestPattern()` and `getResponsePattern()` are part of the transport correlation flow. - Do not bypass lifecycle handling: call `close()` during shutdown to release MQTT connections and subscriptions. - Preserve error, offline, reconnect, and disconnect listener registration when extending or modifying connection behavior. ## Relationships - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `isObject` # ClientRedis **Kind:** Class **Source:** [`packages/microservices/client/client-redis.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-redis.ts#L28) **Part of:** [Microservices](subsystem-packages-microservices) `ClientRedis` is a Redis-backed microservice client that publishes request messages and listens for correlated reply messages. It manages the Redis connection lifecycle—including connection, reconnection, readiness, errors, and shutdown—while applying request and reply channel naming conventions. **Extends:** `ClientProxy` ## Methods | Method | Signature | Returns | |---|---|---| | `getRequestPattern` | `getRequestPattern(pattern: string)` | `string` | | `getReplyPattern` | `getReplyPattern(pattern: string)` | `string` | | `close` | `close()` | `void` | | `connect` | `connect()` | `Promise` | | `createClient` | `createClient()` | `Redis` | | `registerErrorListener` | `registerErrorListener(client: Redis)` | `void` | | `registerReconnectListener` | `registerReconnectListener(client: { on: (event: string, fn: () => void) => void; })` | `void` | | `registerReadyListener` | `registerReadyListener(client: { on: (event: string, fn: () => void) => void; })` | `void` | | `registerEndListener` | `registerEndListener(client: { on: (event: string, fn: () => void) => void; })` | `void` | | `handleClose` | `handleClose()` | `void` | | `getClientOptions` | `getClientOptions()` | `Partial` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | | `createRetryStrategy` | `createRetryStrategy(times: number)` | `undefined | number` | | `createResponseCallback` | `createResponseCallback()` | `( channel: string, buffer: string, ) => Promise` | | `publish` | `publish(partialPacket: ReadPacket, callback: (packet: WritePacket) => any)` | `() => void` | | `dispatchEvent` | `dispatchEvent(packet: ReadPacket)` | `Promise` | | `unsubscribeFromChannel` | `unsubscribeFromChannel(channel: string)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `subscriptionsCount` | `any` | | `pubClient` | `Redis` | | `subClient` | `Redis` | | `connectionPromise` | `Promise` | | `isManuallyClosed` | `any` | | `wasInitialConnectionSuccessful` | `any` | | `pendingEventListeners` | `Array<{ event: keyof RedisEvents; callback: RedisEvents[keyof RedisEvents]; }>` | ## Where it refuses work - `ClientRedis` stops the work with `Error` when `!this.pubClient || !this.subClient` — “Not initialized. Please call the "connect" method first.”. - `ClientRedis` stops the work with an early return when `this.isManuallyClosed`, in 3 places. - `ClientRedis` stops the work with an early return when `this.pubClient && this.subClient`. - `ClientRedis` stops the work with an early return when `isDisposed || err`. ## When something fails - `ClientRedis` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR App[Application Service] --> ClientRedis[ClientRedis] ClientRedis -->|publish: pattern_request| Redis[(Redis)] Redis -->|subscribe: pattern_response| ClientRedis ClientRedis -->|response/error| App ClientRedis --> Connection[Redis Client Connection] Connection --> Ready[Ready Listener] Connection --> Reconnect[Reconnect Listener] Connection --> Errors[Error Listener] Connection --> End[End Listener] ``` ## AI Coding Instructions - Use `connect()` before sending messages when the client lifecycle is managed manually; reuse a connected client instead of creating one per request. - Keep request patterns aligned with the receiving Redis microservice transport configuration; `ClientRedis` derives separate request and reply channels from the pattern. - Use `send()` for request-response flows and ensure the downstream service returns a response on the corresponding reply channel. - Call `close()` during application shutdown so Redis subscriptions and connections are released cleanly. - Do not bypass lifecycle listeners when changing connection behavior; error, reconnect, ready, and end handlers are required for reliable Redis transport operation. ## Relationships - IMPORTS → `Logger` - IMPORTS → `loadPackage` # ClientRMQ **Kind:** Class **Source:** [`packages/microservices/client/client-rmq.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-rmq.ts#L57) **Part of:** [Microservices](subsystem-packages-microservices) `ClientRMQ` is the RabbitMQ transport client used by NestJS microservices to establish AMQP connections, create channels, and send or emit messages. It manages connection lifecycle concerns such as channel setup, error handling, disconnect events, and reconnection through `AmqpConnectionManager`. **Extends:** `ClientProxy` ## Methods | Method | Signature | Returns | |---|---|---| | `close` | `close()` | `Promise` | | `connect` | `connect()` | `Promise` | | `createChannel` | `createChannel()` | `Promise` | | `createClient` | `createClient()` | `AmqpConnectionManager` | | `mergeDisconnectEvent` | `mergeDisconnectEvent(instance: any, source$: Observable)` | `Observable` | | `convertConnectionToPromise` | `convertConnectionToPromise()` | `void` | | `setupChannel` | `setupChannel(channel: Channel, resolve: Function)` | `void` | | `consumeChannel` | `consumeChannel(channel: Channel)` | `void` | | `registerErrorListener` | `registerErrorListener(client: AmqpConnectionManager)` | `void` | | `registerDisconnectListener` | `registerDisconnectListener(client: AmqpConnectionManager)` | `void` | | `registerBlockedListener` | `registerBlockedListener(client: AmqpConnectionManager)` | `void` | | `registerUnblockedListener` | `registerUnblockedListener(client: AmqpConnectionManager)` | `void` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | | `handleMessage` | `handleMessage(packet: unknown, callback: (packet: WritePacket) => any)` | `Promise` | | `handleMessage` | `handleMessage(packet: unknown, options: Record, callback: (packet: WritePacket) => any)` | `Promise` | | `handleMessage` | `handleMessage(packet: unknown, options: | Record | ((packet: WritePacket) => any) | undefined, callback: (packet: WritePacket) => any)` | `Promise` | | `publish` | `publish(message: ReadPacket, callback: (packet: WritePacket) => any)` | `() => void` | | `dispatchEvent` | `dispatchEvent(packet: ReadPacket)` | `Promise` | | `initializeSerializer` | `initializeSerializer(options: RmqOptions['options'])` | `void` | | `mergeHeaders` | `mergeHeaders(requestHeaders: Record)` | `Record | undefined` | | `parseMessageContent` | `parseMessageContent(content: Buffer)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `connection$` | `ReplaySubject` | | `connectionPromise` | `Promise` | | `client` | `AmqpConnectionManager | null` | | `channel` | `ChannelWrapper | null` | | `pendingEventListeners` | `Array<{ event: keyof RmqEvents; callback: RmqEvents[keyof RmqEvents]; }>` | | `isInitialConnect` | `any` | | `responseEmitter` | `EventEmitter` | | `queue` | `string` | | `queueOptions` | `Record` | | `replyQueue` | `string` | | `noAssert` | `boolean` | ## Where it refuses work - `ClientRMQ` stops the work with `Error` when `!this.client` — “Not initialized. Please call the "connect" method first.”. - `ClientRMQ` stops the work with an early return when `this.client`. - `ClientRMQ` stops the work with an early return when `urls.indexOf(error.url) >= urls.length - 1`. - `ClientRMQ` stops the work with an early return when `err instanceof EmptyError`. - `ClientRMQ` stops the work with an early return when `isDisposed || err`. - `ClientRMQ` stops the work with an early return when `!requestHeaders && !this.options?.headers`. ## When something fails - `ClientRMQ` handles failure in 3 places: it turns it into a return value in 2, and lets it reach the caller in 1. ## Diagram ```mermaid graph LR A[Application Service] --> B[ClientRMQ] B --> C[createClient()] C --> D[AmqpConnectionManager] D --> E[RabbitMQ Broker] B --> F[createChannel()] F --> G[AMQP Channel] B --> H[registerErrorListener()] B --> I[registerDisconnectListener()] I --> J[mergeDisconnectEvent()] J --> K[Reconnect / Channel Setup] ``` ## AI Coding Instructions - Call `connect()` before publishing messages so the AMQP connection and channel are initialized. - Use `emit()` for event-based messaging and `send()` when a request/response interaction is required. - Preserve the existing disconnect and error listener flow; these listeners support channel recovery after RabbitMQ connection failures. - Configure durable queues and matching queue options consistently between clients and consumers to avoid broker-side queue declaration errors. - Always call `close()` during application shutdown or test cleanup to release RabbitMQ connections and channels. ## How it works `ClientRMQ` is the RabbitMQ client implementation of `ClientProxy`, parameterized with RabbitMQ connection events and statuses. It manages an `amqp-connection-manager` client and channel wrapper, publishes request/reply messages and events, and exposes RabbitMQ connection status through the inherited `status` observable. [packages/microservices/client/client-rmq.ts:57-72](packages/microservices/client/client-rmq.ts#L57-L72) [packages/microservices/client/client-proxy.ts:45-52](packages/microservices/client/client-proxy.ts#L45-L52) ## Relationships - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `randomStringGenerator` - IMPORTS → `isFunction` - IMPORTS → `isString` # NestMicroservice **Kind:** Class **Source:** [`packages/microservices/nest-microservice.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/nest-microservice.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) `NestMicroservice` is the runtime application class used to bootstrap and manage a NestJS microservice transport server. It creates the server, registers modules and message listeners, applies global enhancers, and coordinates the `init()` and `listen()` lifecycle stages. **Extends:** `NestApplicationContext` **Implements:** `INestMicroservice` ## Methods | Method | Signature | Returns | |---|---|---| | `createServer` | `createServer(config: CompleteMicroserviceOptions)` | `void` | | `registerModules` | `registerModules()` | `Promise` | | `registerListeners` | `registerListeners()` | `void` | | `useWebSocketAdapter` | `useWebSocketAdapter(adapter: WebSocketAdapter)` | `this` | | `useGlobalFilters` | `useGlobalFilters(filters: ExceptionFilter[])` | `this` | | `useGlobalPipes` | `useGlobalPipes(pipes: PipeTransform[])` | `this` | | `useGlobalInterceptors` | `useGlobalInterceptors(interceptors: NestInterceptor[])` | `this` | | `useGlobalGuards` | `useGlobalGuards(guards: CanActivate[])` | `this` | | `init` | `init()` | `Promise` | | `listen` | `listen()` | `Promise` | | `close` | `close()` | `Promise` | | `setIsInitialized` | `setIsInitialized(isInitialized: boolean)` | `void` | | `setIsTerminated` | `setIsTerminated(isTerminated: boolean)` | `void` | | `setIsInitHookCalled` | `setIsInitHookCalled(isInitHookCalled: boolean)` | `void` | | `on` | `on(event: string | number | symbol, callback: Function)` | `void` | | `unwrap` | `unwrap()` | `T` | | `closeApplication` | `closeApplication()` | `Promise` | | `dispose` | `dispose()` | `Promise` | | `resolveAsyncOptions` | `resolveAsyncOptions(config: AsyncMicroserviceOptions)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | ## Where it refuses work - `NestMicroservice` stops the work with an early return when `this.isTerminated`, in 2 places. - `NestMicroservice` stops the work with an early return when `this.isInitialized`. - `NestMicroservice` stops the work with an early return when `err`. - `NestMicroservice` stops the work with an early return when `'on' in this.serverInstance`. - `NestMicroservice` stops the work with an early return when `'unwrap' in this.serverInstance`. - `NestMicroservice` stops the work with an early return when `this.appOptions.instrument?.instanceDecorator`. ## When something fails - `NestMicroservice` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid graph LR A[NestFactory.createMicroservice] --> B[NestMicroservice] B --> C[createServer] B --> D[registerModules] D --> E[registerListeners] B --> F[Global Pipes / Guards / Filters / Interceptors] B --> G[init] G --> H[listen] H --> I[Transport Server] I --> J[Message Handlers] ``` ## Usage ```ts import { ValidationPipe } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { Transport } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001, }, }); app.useGlobalPipes( new ValidationPipe({ transform: true, whitelist: true, }), ); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Prefer creating microservices through `NestFactory.createMicroservice()` rather than instantiating `NestMicroservice` directly. - Configure transport options before calling `listen()`, since server creation and listener registration depend on the selected transport. - Register global pipes, guards, interceptors, and filters during application setup, before the microservice begins listening. - Preserve the lifecycle order: create server, register modules and handlers, initialize the application, then start listening. - Ensure controllers use microservice message-pattern decorators such as `@MessagePattern()` so `registerListeners()` can bind handlers to the transport. ## Relationships - IMPORTS → `CanActivate` - IMPORTS → `ExceptionFilter` - IMPORTS → `INestMicroservice` - IMPORTS → `NestInterceptor` - IMPORTS → `PipeTransform` - IMPORTS → `WebSocketAdapter` - IMPORTS → `NestMicroserviceOptions` - IMPORTS → `Logger` - IMPORTS → `ApplicationConfig` - IMPORTS → `MESSAGES` - IMPORTS → `optionalRequire` - IMPORTS → `NestContainer` - IMPORTS → `Injector` - IMPORTS → `GraphInspector` - IMPORTS → `NestApplicationContext` - IMPORTS → `SocketModule` # Server **Kind:** Class **Source:** [`packages/microservices/server/server.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server.ts#L47) **Part of:** [Microservices](subsystem-packages-microservices) `Server` is the base class for microservice transport servers. It manages message-handler registration and lookup, transport identification, and processing lifecycle hooks while allowing concrete transport implementations to provide connection, listening, shutdown, and native-client behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `on` | `on(event: EventKey, callback: EventCallback)` | `any` | | `unwrap` | `unwrap()` | `T` | | `listen` | `listen(callback: (...optionalParams: unknown[]) => any)` | `any` | | `close` | `close()` | `any` | | `setTransportId` | `setTransportId(transportId: Transport | symbol)` | `void` | | `setOnProcessingStartHook` | `setOnProcessingStartHook(hook: ( transportId: Transport | symbol, context: unknown, done: () => Promise, ) => void)` | `void` | | `setOnProcessingEndHook` | `setOnProcessingEndHook(hook: (transportId: Transport | symbol, context: unknown) => void)` | `void` | | `addHandler` | `addHandler(pattern: any, callback: MessageHandler, isEventHandler: undefined, extras: Record)` | `void` | | `getHandlers` | `getHandlers()` | `Map` | | `getHandlerByPattern` | `getHandlerByPattern(pattern: string)` | `MessageHandler | null` | | `send` | `send(stream$: Observable, respond: (data: WritePacket) => Promise | void)` | `Subscription` | | `handleEvent` | `handleEvent(pattern: string, packet: ReadPacket, context: BaseRpcContext)` | `Promise` | | `transformToObservable` | `transformToObservable(resultOrDeferred: Observable | Promise)` | `Observable` | | `transformToObservable` | `transformToObservable(resultOrDeferred: T)` | `never extends Observable> ? Observable : Observable>` | | `transformToObservable` | `transformToObservable(resultOrDeferred: any)` | `void` | | `getOptionsProp` | `getOptionsProp(obj: Options, prop: Attribute)` | `Options[Attribute]` | | `getOptionsProp` | `getOptionsProp(obj: Options, prop: Attribute, defaultValue: DefaultValue)` | `Required[Attribute]` | | `getOptionsProp` | `getOptionsProp(obj: Options, prop: Attribute, defaultValue: DefaultValue)` | `void` | | `handleError` | `handleError(error: string)` | `void` | | `loadPackage` | `loadPackage(name: string, ctx: string, loader: Function)` | `T` | | `initializeSerializer` | `initializeSerializer(options: ClientOptions['options'])` | `void` | | `initializeDeserializer` | `initializeDeserializer(options: ClientOptions['options'])` | `void` | | `getRouteFromPattern` | `getRouteFromPattern(pattern: string)` | `string` | | `normalizePattern` | `normalizePattern(pattern: MsPattern)` | `string` | ## Properties | Property | Type | |---|---| | `transportId` | `Transport | symbol` | | `messageHandlers` | `any` | | `logger` | `LoggerService` | | `serializer` | `ConsumerSerializer` | | `deserializer` | `ConsumerDeserializer` | | `onProcessingStartHook` | `( transportId: Transport | symbol, context: BaseRpcContext, done: () => Promise, ) => void` | | `onProcessingEndHook` | `( transportId: Transport | symbol, context: BaseRpcContext, ) => void` | | `_status$` | `any` | ## Where it refuses work - `Server` stops the work with an early return when `!handler`. - `Server` stops the work with an early return when `resultOrDeferred instanceof Promise`. - `Server` stops the work with an early return when `isObservable(resultOrDeferred)`. ## When something fails - `Server` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR Client[Microservice Client] --> Transport[Concrete Server Transport] Transport --> Server[Server Base Class] Server --> Handlers[Message Handler Map] Server --> StartHook[Processing Start Hook] Server --> EndHook[Processing End Hook] Handlers --> Handler[Message Handler] Handler --> Response[Response or Event Processing] ``` ## Usage ```ts import { Server } from '@nestjs/microservices'; class CustomServer extends Server { async listen(callback: () => void) { // Connect to the underlying transport here. callback(); } async close() { // Close transport connections and release resources. } unwrap() { // Return the underlying transport client/server instance. return {} as T; } } const server = new CustomServer(); server.setTransportId('custom-transport'); server.setOnProcessingStartHook(() => { console.log('Started processing message'); }); server.setOnProcessingEndHook(() => { console.log('Finished processing message'); }); server.addHandler('users.find', async (payload) => { return { id: payload.id, name: 'Ada Lovelace' }; }); await server.listen(() => { console.log('Custom microservice server is listening'); }); const handler = server.getHandlerByPattern('users.find'); if (handler) { const result = await handler({ id: 'user-1' }); console.log(result); } await server.close(); ``` ## AI Coding Instructions - Extend `Server` when implementing a new transport; provide transport-specific `listen()`, `close()`, and `unwrap()` implementations. - Register request and event handlers through `addHandler()` rather than mutating the handler map returned by `getHandlers()`. - Use the same normalized message pattern when registering handlers and retrieving them with `getHandlerByPattern()`. - Set a transport ID with `setTransportId()` when the transport must be identified by framework integrations or diagnostics. - Keep processing hooks lightweight; use `setOnProcessingStartHook()` and `setOnProcessingEndHook()` for instrumentation, tracing, or metrics rather than business logic. # ServerGrpc **Kind:** Class **Source:** [`packages/microservices/server/server-grpc.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-grpc.ts#L59) **Part of:** [Microservices](subsystem-packages-microservices) `ServerGrpc` is the NestJS microservices transport server responsible for exposing message handlers as gRPC service methods. It initializes the gRPC server, binds configured services and RPC handlers, applies keepalive options, and translates incoming gRPC requests into Nest message handler calls. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `start` | `start(callback: () => void)` | `void` | | `bindEvents` | `bindEvents()` | `void` | | `getServiceNames` | `getServiceNames(grpcPkg: any)` | `{ name: string; service: any }[]` | | `getKeepaliveOptions` | `getKeepaliveOptions()` | `void` | | `createService` | `createService(grpcService: any, name: string)` | `void` | | `getMessageHandler` | `getMessageHandler(serviceName: string, methodName: string, streaming: GrpcMethodStreamingType, grpcMethod: { path?: string })` | `MessageHandler` | | `createPattern` | `createPattern(service: string, methodName: string, streaming: GrpcMethodStreamingType)` | `string` | | `createServiceMethod` | `createServiceMethod(methodHandler: Function, protoNativeHandler: any, streamType: GrpcMethodStreamingType)` | `Function` | | `createUnaryServiceMethod` | `createUnaryServiceMethod(methodHandler: Function)` | `Function` | | `createStreamServiceMethod` | `createStreamServiceMethod(methodHandler: Function)` | `Function` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `createRequestStreamMethod` | `createRequestStreamMethod(methodHandler: Function, isResponseStream: boolean)` | `void` | | `createStreamCallMethod` | `createStreamCallMethod(methodHandler: Function, isResponseStream: boolean)` | `void` | | `close` | `close()` | `Promise` | | `deserialize` | `deserialize(obj: any)` | `any` | | `addHandler` | `addHandler(pattern: unknown, callback: MessageHandler, isEventHandler: undefined)` | `void` | | `createClient` | `createClient()` | `void` | | `lookupPackage` | `lookupPackage(root: any, packageName: string)` | `void` | | `loadProto` | `loadProto()` | `any` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `url` | `string` | | `grpcClient` | `GrpcServer` | ## Where it refuses work - `ServerGrpc` stops the work with an early return when `hasDrained`, in 2 places. - `ServerGrpc` stops the work with an early return when `!isObject(this.options.keepalive)`. - `ServerGrpc` stops the work with an early return when `streamType === GrpcMethodStreamingType.PT_STREAMING`. - `ServerGrpc` stops the work with an early return when `!writing`. - `ServerGrpc` stops the work with an early return when `!isObject(grpcDefinition)`. - `ServerGrpc` stops the work with an early return when `name.length === 0`. ## When something fails - `ServerGrpc` handles failure in 3 places: it logs it and continues in 1, turns it into a return value in 1, and lets it reach the caller in 1. ## Diagram ```mermaid graph LR Client[gRPC Client] -->|RPC request| GrpcServer[ServerGrpc] GrpcServer -->|bindEvents| Services[gRPC Service Definitions] Services -->|createServiceMethod| Handlers[Nest Message Handlers] Handlers -->|getMessageHandler| Controllers[Controller Methods] Controllers -->|response / stream| Client ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.createMicroservice( AppModule, { transport: Transport.GRPC, options: { package: 'users', protoPath: 'proto/users.proto', url: '0.0.0.0:50051', }, }, ); // Internally creates and starts a ServerGrpc instance. await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Configure `ServerGrpc` through Nest's `Transport.GRPC` microservice options rather than manually instantiating it in application code. - Ensure `package`, `protoPath`, and service names match the `.proto` definition exactly; mismatches prevent handlers from being bound. - Use controller methods decorated with `@GrpcMethod()` or `@GrpcStreamMethod()` so `bindEvents()` can map RPC methods to Nest message handlers. - Keep unary and streaming RPC implementations distinct; `createUnaryServiceMethod()` handles request/response calls, while streaming methods require stream-aware handlers. - When changing connection behavior, preserve the expected gRPC keepalive option format used by `getKeepaliveOptions()`. ## How it works ## `ServerGrpc` `ServerGrpc` is the gRPC transport implementation of the abstract `Server` base class. It identifies itself as `Transport.GRPC` and stores the bound gRPC server instance in `grpcClient`. [packages/microservices/server/server-grpc.ts:59-63](packages/microservices/server/server-grpc.ts#L59-L63) ## Relationships - IMPORTS → `isObject` - IMPORTS → `isString` - IMPORTS → `isUndefined` # ServerKafka **Kind:** Class **Source:** [`packages/microservices/server/server-kafka.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-kafka.ts#L43) **Part of:** [Microservices](subsystem-packages-microservices) `ServerKafka` is the NestJS microservice transport server responsible for connecting an application to Apache Kafka as both a consumer and producer. It initializes Kafka clients, subscribes to configured message patterns, routes incoming records to registered handlers, and publishes request-response results when required. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `Promise` | | `close` | `close()` | `Promise` | | `start` | `start(callback: () => void)` | `Promise` | | `registerConsumerEventListeners` | `registerConsumerEventListeners()` | `void` | | `registerProducerEventListeners` | `registerProducerEventListeners()` | `void` | | `createClient` | `createClient()` | `T` | | `bindEvents` | `bindEvents(consumer: Consumer)` | `void` | | `getMessageHandler` | `getMessageHandler()` | `void` | | `getPublisher` | `getPublisher(replyTopic: string, replyPartition: string, correlationId: string, context: KafkaContext)` | `(data: any) => Promise` | | `handleMessage` | `handleMessage(payload: EachMessagePayload)` | `void` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `sendMessage` | `sendMessage(message: OutgoingResponse, replyTopic: string, replyPartition: string | undefined | null, correlationId: string, context: KafkaContext)` | `Promise` | | `assignIsDisposedHeader` | `assignIsDisposedHeader(outgoingResponse: OutgoingResponse, outgoingMessage: Message)` | `void` | | `assignErrorHeader` | `assignErrorHeader(outgoingResponse: OutgoingResponse, outgoingMessage: Message)` | `void` | | `assignCorrelationIdHeader` | `assignCorrelationIdHeader(correlationId: string, outgoingMessage: Message)` | `void` | | `assignReplyPartition` | `assignReplyPartition(replyPartition: string | null | undefined, outgoingMessage: Message)` | `void` | | `handleEvent` | `handleEvent(pattern: string, packet: ReadPacket, context: KafkaContext)` | `Promise` | | `initializeSerializer` | `initializeSerializer(options: KafkaOptions['options'])` | `void` | | `initializeDeserializer` | `initializeDeserializer(options: KafkaOptions['options'])` | `void` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `logger` | `any` | | `client` | `Kafka | null` | | `consumer` | `Consumer | null` | | `producer` | `Producer | null` | | `parser` | `KafkaParser | null` | | `brokers` | `string[] | BrokersFunction` | | `clientId` | `string` | | `groupId` | `string` | ## Where it refuses work - `ServerKafka` stops the work with `Error` when `!this.client` — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”. - `ServerKafka` stops the work with an early return when `!handler`, in 2 places. - `ServerKafka` stops the work with an early return when `!this.consumer`. - `ServerKafka` stops the work with an early return when `!this.producer`. - `ServerKafka` stops the work with an early return when `handler?.isEventHandler || !correlationId || !replyTopic`. - `ServerKafka` stops the work with an early return when `!outgoingResponse.isDisposed`. ## When something fails - `ServerKafka` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR A[KafkaOptions] --> B[ServerKafka] B --> C[createClient] C --> D[Kafka Consumer] C --> E[Kafka Producer] D --> F[registerConsumerEventListeners] D --> G[bindEvents] G --> H[Incoming Kafka Record] H --> I[getMessageHandler] I --> J[Registered Message/Event Handler] J --> K[getPublisher] K --> E E --> L[Kafka Response Topic] ``` ## AI Coding Instructions - Configure Kafka connection details through `KafkaOptions`, including stable `clientId`, broker addresses, and a unique consumer `groupId`. - Register message handlers before calling `listen()` so `bindEvents()` can subscribe the consumer to all configured patterns. - Use event handlers for one-way notifications and request handlers only when callers expect a response published through Kafka. - Do not manually manage the internal KafkaJS producer or consumer lifecycle; use `listen()` to start connections and `close()` for graceful shutdown. - Keep handler logic idempotent where possible, since Kafka consumers may receive messages more than once. ## Relationships - IMPORTS → `Logger` - IMPORTS → `isNil` # ServerMqtt **Kind:** Class **Source:** [`packages/microservices/server/server-mqtt.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-mqtt.ts#L38) **Part of:** [Microservices](subsystem-packages-microservices) `ServerMqtt` is NestJS’s MQTT transport server implementation for microservices. It creates and manages an MQTT client connection, subscribes to message patterns, parses incoming packets, and dispatches them to registered message handlers. It also provides publishing support for request-response messaging and manages connection shutdown. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `start` | `start(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `bindEvents` | `bindEvents(mqttClient: MqttClient)` | `void` | | `close` | `close()` | `void` | | `createMqttClient` | `createMqttClient()` | `MqttClient` | | `getMessageHandler` | `getMessageHandler(pub: MqttClient)` | `void` | | `handleMessage` | `handleMessage(channel: string, buffer: Buffer, pub: MqttClient, originalPacket: Record)` | `Promise` | | `getPublisher` | `getPublisher(client: MqttClient, context: MqttContext, id: string)` | `any` | | `parseMessage` | `parseMessage(content: any)` | `ReadPacket & PacketId` | | `matchMqttPattern` | `matchMqttPattern(pattern: string, topic: string)` | `void` | | `getHandlerByPattern` | `getHandlerByPattern(pattern: string)` | `MessageHandler | null` | | `removeHandlerKeySharedPrefix` | `removeHandlerKeySharedPrefix(handlerKey: string)` | `void` | | `getRequestPattern` | `getRequestPattern(pattern: string)` | `string` | | `getReplyPattern` | `getReplyPattern(pattern: string)` | `string` | | `registerErrorListener` | `registerErrorListener(client: MqttClient)` | `void` | | `registerReconnectListener` | `registerReconnectListener(client: MqttClient)` | `void` | | `registerDisconnectListener` | `registerDisconnectListener(client: MqttClient)` | `void` | | `registerCloseListener` | `registerCloseListener(client: MqttClient)` | `void` | | `registerConnectListener` | `registerConnectListener(client: MqttClient)` | `void` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `initializeSerializer` | `initializeSerializer(options: MqttOptions['options'])` | `void` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `url` | `string` | | `mqttClient` | `MqttClient` | | `pendingEventListeners` | `Array<{ event: keyof MqttEvents; callback: MqttEvents[keyof MqttEvents]; }>` | ## Where it refuses work - `ServerMqtt` stops the work with `Error` when `!this.mqttClient` — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”. - `ServerMqtt` stops the work with an early return when `isUndefined((packet as IncomingRequest).id)`. - `ServerMqtt` stops the work with an early return when `!currentTopic && currentPattern !== MQTT_WILDCARD_ALL`. - `ServerMqtt` stops the work with an early return when `patternChar === MQTT_WILDCARD_ALL`. - `ServerMqtt` stops the work with an early return when `patternChar !== MQTT_WILDCARD_SINGLE && currentPattern !== currentTopic`. - `ServerMqtt` stops the work with an early return when `this.messageHandlers.has(route)`. ## When something fails - `ServerMqtt` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR A[MQTT Broker] --> B[ServerMqtt] B --> C[MQTT Client] C --> D[bindEvents] D --> E[Incoming MQTT Packet] E --> F[parseMessage] F --> G[matchMqttPattern] G --> H[getMessageHandler] H --> I[handleMessage] I --> J[getPublisher] J --> A ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { MessagePattern, ServerMqtt, } from '@nestjs/microservices'; import { AppModule } from './app.module'; @Controller() class DeviceController { @MessagePattern('devices/+/temperature') handleTemperature(payload: { value: number; unit: string }) { return { received: true, temperature: payload.value, }; } } async function bootstrap() { const mqttServer = new ServerMqtt({ url: 'mqtt://localhost:1883', }); const app = await NestFactory.createMicroservice(AppModule, { strategy: mqttServer, }); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Keep MQTT topic patterns aligned with `@MessagePattern()` handlers; wildcard topics must be compatible with MQTT matching rules. - Use `ServerMqtt` through NestJS microservice configuration rather than manually calling internal methods such as `bindEvents()` or `handleMessage()`. - Ensure the MQTT broker URL and connection options are supplied through the transport options, including authentication or TLS settings when required. - Preserve packet parsing and publisher behavior when modifying request-response flows, as MQTT responses depend on packet identifiers and reply topics. - Always allow the NestJS application lifecycle to call `close()` so the MQTT client disconnects cleanly. ## Relationships - IMPORTS → `isObject` - IMPORTS → `isUndefined` # ServerNats **Kind:** Class **Source:** [`packages/microservices/server/server-nats.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-nats.ts#L38) **Part of:** [Microservices](subsystem-packages-microservices) `ServerNats` is the NATS transport server implementation for NestJS microservices. It connects to a NATS broker, subscribes registered message handlers to their patterns, routes incoming requests or events to those handlers, and manages connection lifecycle and status updates. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `start` | `start(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `bindEvents` | `bindEvents(client: Client)` | `void` | | `close` | `close()` | `void` | | `createNatsClient` | `createNatsClient()` | `Promise` | | `getMessageHandler` | `getMessageHandler(channel: string)` | `Function` | | `handleMessage` | `handleMessage(channel: string, natsMsg: NatsMsg)` | `void` | | `getPublisher` | `getPublisher(natsMsg: NatsMsg, id: string, ctx: NatsContext)` | `void` | | `handleStatusUpdates` | `handleStatusUpdates(client: Client)` | `void` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `initializeSerializer` | `initializeSerializer(options: NatsOptions['options'])` | `void` | | `initializeDeserializer` | `initializeDeserializer(options: NatsOptions['options'])` | `void` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `statusEventEmitter` | `any` | ## Where it refuses work - `ServerNats` stops the work with `Error` when `!this.natsClient` — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”. - `ServerNats` stops the work with an early return when `!this.natsClient`. - `ServerNats` stops the work with an early return when `error`. - `ServerNats` stops the work with an early return when `isUndefined((message as IncomingRequest).id)`. - `ServerNats` stops the work with an early return when `natsMsg.reply`. ## When something fails - `ServerNats` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR A[Nest Microservice] --> B[ServerNats] B --> C[createNatsClient] C --> D[NATS Broker] B --> E[bindEvents] E --> F[Registered Message Handlers] D --> G[Incoming NATS Message] G --> H[getMessageHandler / handleMessage] H --> F B --> I[getPublisher] I --> D B --> J[close] J --> D ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { ServerNats } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const natsServer = new ServerNats({ servers: ['nats://localhost:4222'], queue: 'orders-service', }); const app = await NestFactory.createMicroservice(AppModule, { strategy: natsServer, }); await app.listen(); // Access the underlying NATS client when transport-specific APIs are needed. const client = natsServer.unwrap(); console.log('Connected to NATS:', Boolean(client)); } bootstrap(); ``` ## AI Coding Instructions - Use `ServerNats` as a custom NestJS microservice transport strategy; let Nest register handlers before calling `listen()`. - Register message patterns through Nest decorators such as `@MessagePattern()` and `@EventPattern()` rather than manually subscribing through the underlying client. - Keep NATS connection settings, queue groups, and serializer/deserializer options in the transport configuration passed to the constructor. - Call `close()` during application shutdown when managing the server lifecycle manually. - Use `unwrap()` only for NATS-client-specific functionality; avoid bypassing Nest message handling for normal request and event processing. ## Relationships - IMPORTS → `isObject` - IMPORTS → `isUndefined` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NatsSubscriber` — `sample/03-microservices/src/common/strategies/nats.strategy.ts`:3 # ServerRedis **Kind:** Class **Source:** [`packages/microservices/server/server-redis.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-redis.ts#L30) **Part of:** [Microservices](subsystem-packages-microservices) `ServerRedis` is the Redis transport server implementation for NestJS microservices. It creates Redis publisher/subscriber clients, subscribes to message patterns, dispatches incoming requests to registered handlers, and publishes responses or events back through Redis. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `start` | `start(callback: () => void)` | `void` | | `bindEvents` | `bindEvents(subClient: Redis, pubClient: Redis)` | `void` | | `close` | `close()` | `void` | | `createRedisClient` | `createRedisClient()` | `Redis` | | `getMessageHandler` | `getMessageHandler(pub: Redis)` | `void` | | `handleMessage` | `handleMessage(channel: string, buffer: string, pub: Redis, pattern: string)` | `void` | | `getPublisher` | `getPublisher(pub: Redis, pattern: any, id: string, ctx: RedisContext)` | `void` | | `parseMessage` | `parseMessage(content: any)` | `Record` | | `getRequestPattern` | `getRequestPattern(pattern: string)` | `string` | | `getReplyPattern` | `getReplyPattern(pattern: string)` | `string` | | `registerErrorListener` | `registerErrorListener(client: any)` | `void` | | `registerReconnectListener` | `registerReconnectListener(client: { on: (event: string, fn: () => void) => void; })` | `void` | | `registerReadyListener` | `registerReadyListener(client: { on: (event: string, fn: () => void) => void; })` | `void` | | `registerEndListener` | `registerEndListener(client: { on: (event: string, fn: () => void) => void; })` | `void` | | `getClientOptions` | `getClientOptions()` | `Partial` | | `createRetryStrategy` | `createRetryStrategy(times: number)` | `undefined | number | void` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `subClient` | `Redis` | | `pubClient` | `Redis` | | `isManuallyClosed` | `any` | | `wasInitialConnectionSuccessful` | `any` | | `pendingEventListeners` | `Array<{ event: keyof RedisEvents; callback: RedisEvents[keyof RedisEvents]; }>` | ## Where it refuses work - `ServerRedis` stops the work with `Error` when `!this.pubClient || !this.subClient` — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”. - `ServerRedis` stops the work with an early return when `this.isManuallyClosed`, in 3 places. - `ServerRedis` stops the work with an early return when `isUndefined((packet as IncomingRequest).id)`. ## When something fails - `ServerRedis` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR Client[Redis Microservice Client] -->|Publish request/event| Redis[(Redis)] Redis -->|Subscribed channel| ServerRedis[ServerRedis] ServerRedis -->|Parse message| Handler[Registered Message Handler] Handler -->|Response| ServerRedis ServerRedis -->|Publish response| Redis Redis --> Client ``` ## AI Coding Instructions - Register message handlers with `addHandler()` before calling `listen()` so Redis subscriptions can route incoming patterns correctly. - Keep request patterns stable and serializable; `getRequestPattern()` uses the pattern to determine the Redis subscription channel. - Ensure Redis connection options match the deployed Redis instance, including authentication, TLS, retry behavior, and database selection where required. - Always call `close()` during application shutdown to disconnect both publisher and subscriber Redis clients cleanly. - Avoid placing long-running synchronous work in handlers; Redis message processing should delegate expensive work to asynchronous services or workers. ## Relationships - IMPORTS → `isUndefined` # ServerRMQ **Kind:** Class **Source:** [`packages/microservices/server/server-rmq.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-rmq.ts#L61) **Part of:** [Microservices](subsystem-packages-microservices) `ServerRMQ` is the RabbitMQ transport server used by the microservices package to consume queue messages and dispatch them to registered message or event handlers. It manages the RabbitMQ connection and channel lifecycle, configures queue consumption, sends replies for request-response patterns, and exposes the underlying channel through `unwrap()` when needed. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `Promise` | | `close` | `close()` | `Promise` | | `start` | `start(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `createClient` | `createClient()` | `T` | | `setupChannel` | `setupChannel(channel: Channel, callback: Function)` | `void` | | `handleMessage` | `handleMessage(message: Record, channel: any)` | `Promise` | | `handleEvent` | `handleEvent(pattern: string, packet: ReadPacket, context: RmqContext)` | `Promise` | | `sendMessage` | `sendMessage(message: T, replyTo: any, correlationId: string, context: RmqContext)` | `void` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `getHandlerByPattern` | `getHandlerByPattern(pattern: string)` | `MessageHandler | null` | | `initializeSerializer` | `initializeSerializer(options: RmqOptions['options'])` | `void` | | `initializeWildcardHandlersIfExist` | `initializeWildcardHandlersIfExist()` | `void` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `server` | `AmqpConnectionManager | null` | | `channel` | `ChannelWrapper | null` | | `connectionAttempts` | `any` | | `urls` | `string[] | RmqUrl[]` | | `queue` | `string` | | `noAck` | `boolean` | | `queueOptions` | `any` | | `wildcardHandlers` | `any` | | `pendingEventListeners` | `Array<{ event: keyof RmqEvents; callback: RmqEvents[keyof RmqEvents]; }>` | ## Where it refuses work - `ServerRMQ` stops the work with `Error` when `!this.server` — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”. - `ServerRMQ` stops the work with an early return when `this.channel`. - `ServerRMQ` stops the work with an early return when `maxConnectionAttempts === INFINITE_CONNECTION_ATTEMPTS || isReconnecting`. - `ServerRMQ` stops the work with an early return when `isNil(message)`. - `ServerRMQ` stops the work with an early return when `isUndefined((packet as IncomingRequest).id)`. - `ServerRMQ` stops the work with an early return when `!this.options.wildcards`. ## When something fails - `ServerRMQ` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR A[RabbitMQ Broker] --> B[ServerRMQ] B --> C[Create Client Connection] C --> D[Setup Channel & Queue] D --> E[Consume Messages] E --> F{Message Type} F -->|Request/Response| G[handleMessage] F -->|Event| H[handleEvent] G --> I[sendMessage Reply] H --> J[Application Event Handler] B --> K[unwrap Channel] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { MessagePattern, NestFactory } from '@nestjs/microservices'; import { AppModule } from './app.module'; import { Transport } from '@nestjs/microservices'; @Controller() class MathController { @MessagePattern({ cmd: 'sum' }) sum(numbers: number[]) { return numbers.reduce((total, value) => total + value, 0); } } async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.RMQ, options: { urls: ['amqp://guest:guest@localhost:5672'], queue: 'math_queue', queueOptions: { durable: true, }, }, }); // Internally starts a ServerRMQ instance. await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Configure RabbitMQ through `Transport.RMQ` options rather than manually managing connections unless implementing a custom transport strategy. - Keep queue names, broker URLs, durability settings, and acknowledgement behavior consistent between producers and consumers. - Use message patterns for request-response communication and event patterns for fire-and-forget events; `ServerRMQ` handles them through separate message flows. - Call `close()` during application shutdown so RabbitMQ channels and connections are released cleanly. - Use `unwrap()` only when direct access to the RabbitMQ channel is required, such as for advanced acknowledgements or broker-specific operations. ## How it works `ServerRMQ` is the RabbitMQ microservice server transport. It extends the generic `Server` base class with RMQ event/status types and identifies itself as `Transport.RMQ`; `ServerFactory` constructs it when the selected transport is RMQ. [packages/microservices/server/server-rmq.ts:61-62](packages/microservices/server/server-rmq.ts#L61-L62) [packages/microservices/server/server-factory.ts:20-40](packages/microservices/server/server-factory.ts#L20-L40) ## Relationships - IMPORTS → `isNil` - IMPORTS → `isString` - IMPORTS → `isUndefined` # ServerTCP **Kind:** Class **Source:** [`packages/microservices/server/server-tcp.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-tcp.ts#L33) **Part of:** [Microservices](subsystem-packages-microservices) `ServerTCP` is the TCP transport server implementation for NestJS microservices. It opens a TCP socket, registers message handlers by pattern, routes incoming packets to those handlers, and manages listening, error, and connection-close lifecycle events. **Extends:** `Server` ## Methods | Method | Signature | Returns | |---|---|---| | `listen` | `listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void)` | `void` | | `close` | `close()` | `void` | | `bindHandler` | `bindHandler(socket: Socket)` | `void` | | `handleMessage` | `handleMessage(socket: TcpSocket, rawMessage: unknown)` | `void` | | `handleClose` | `handleClose()` | `undefined | number | NodeJS.Timer` | | `unwrap` | `unwrap()` | `T` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `init` | `init()` | `void` | | `registerListeningListener` | `registerListeningListener(socket: net.Server)` | `void` | | `registerErrorListener` | `registerErrorListener(socket: net.Server)` | `void` | | `registerCloseListener` | `registerCloseListener(socket: net.Server)` | `void` | | `getSocketInstance` | `getSocketInstance(socket: Socket)` | `TcpSocket` | ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | | `server` | `NetSocket` | | `port` | `number` | | `host` | `string` | | `socketClass` | `Type` | | `maxBufferSize` | `number` | | `isManuallyTerminated` | `any` | | `retryAttemptsCount` | `any` | | `tlsOptions` | `TlsOptions` | | `pendingEventListeners` | `Array<{ event: keyof TcpEvents; callback: TcpEvents[keyof TcpEvents]; }>` | ## Where it refuses work - `ServerTCP` stops the work with `Error` when `!this.server` — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”. - `ServerTCP` stops the work with an early return when `isUndefined((packet as IncomingRequest).id)`. - `ServerTCP` stops the work with an early return when `this.isManuallyTerminated || !this.getOptionsProp(this.options, 'retryAttempts') || this.…`. - `ServerTCP` stops the work with an early return when `this.maxBufferSize !== undefined && this.socketClass === JsonSocket`. ## Diagram ```mermaid graph LR Client[TCP Client] -->|Serialized message| Socket[TCP Socket] Socket --> ServerTCP[ServerTCP] ServerTCP -->|handleMessage| HandlerRegistry[Pattern Handler Registry] HandlerRegistry --> Handler[Message Handler] Handler -->|Response / Error| ServerTCP ServerTCP -->|Serialized response| Client ``` ## Usage ```ts import { ServerTCP } from '@nestjs/microservices'; const server = new ServerTCP({ host: '127.0.0.1', port: 3001, }); server.bindHandler( { cmd: 'sum' }, async (data: number[]) => data.reduce((total, value) => total + value, 0), ); server.listen(() => { console.log('TCP microservice listening on port 3001'); }); // Shut down gracefully when the process stops. process.on('SIGTERM', async () => { await server.close(); }); ``` ## AI Coding Instructions - Register handlers with `bindHandler()` before calling `listen()` so incoming patterns can be resolved immediately. - Keep handler patterns stable and serializable; TCP clients must send a matching pattern for `handleMessage()` to dispatch correctly. - Use `listen()` and `close()` for lifecycle management rather than interacting with the underlying TCP server directly. - Preserve error and listening listener registration during changes; `registerErrorListener()` and `registerListeningListener()` protect startup and connection lifecycle behavior. - Use `unwrap()` only when transport-specific access to the underlying Node.js TCP server is necessary. ## How it works `ServerTCP` is the TCP transport server implementation. It extends the shared `Server` base class, identifies itself as `Transport.TCP`, and creates either a Node TCP server or a TLS server to accept connections. [`packages/microservices/server/server-tcp.ts:33-43`](packages/microservices/server/server-tcp.ts#L33-L43) [`packages/microservices/server/server-tcp.ts:172-185`](packages/microservices/server/server-tcp.ts#L172-L185) ## Relationships - IMPORTS → `Type` - IMPORTS → `isString` - IMPORTS → `isUndefined` # ClientNats **Kind:** Class **Source:** [`packages/microservices/client/client-nats.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-nats.ts#L29) **Part of:** [Microservices](subsystem-packages-microservices) `ClientNats` is a NATS-backed client responsible for establishing and managing a connection to a NATS broker. It initializes serialization, publishes messages and events, manages subscriptions/status updates, and exposes access to the underlying NATS client through `unwrap()`. **Extends:** `ClientProxy` ## Methods | Method | Signature | Returns | |---|---|---| | `close` | `close()` | `void` | | `connect` | `connect()` | `Promise` | | `createClient` | `createClient()` | `Promise` | | `handleStatusUpdates` | `handleStatusUpdates(client: Client)` | `void` | | `on` | `on(event: EventKey, callback: EventCallback)` | `void` | | `unwrap` | `unwrap()` | `T` | | `createSubscriptionHandler` | `createSubscriptionHandler(packet: ReadPacket & PacketId, callback: (packet: WritePacket) => any)` | `void` | | `publish` | `publish(partialPacket: ReadPacket, callback: (packet: WritePacket) => any)` | `() => void` | | `dispatchEvent` | `dispatchEvent(packet: ReadPacket)` | `Promise` | | `initializeSerializer` | `initializeSerializer(options: NatsOptions['options'])` | `void` | | `initializeDeserializer` | `initializeDeserializer(options: NatsOptions['options'])` | `void` | | `mergeHeaders` | `mergeHeaders(requestHeaders: THeaders)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `natsClient` | `Client | null` | | `connectionPromise` | `Promise | null` | | `statusEventEmitter` | `any` | ## Where it refuses work - `ClientNats` stops the work with `Error` when `!this.natsClient` — “Not initialized. Please call the "connect" method first.”. - `ClientNats` stops the work with an early return when `this.connectionPromise`. - `ClientNats` stops the work with an early return when `error`. - `ClientNats` stops the work with an early return when `rawPacket?.length === 0`. - `ClientNats` stops the work with an early return when `message.id && message.id !== packet.id`. - `ClientNats` stops the work with an early return when `isDisposed || err`. ## When something fails - `ClientNats` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR App[Application Code] --> ClientNats[ClientNats] ClientNats --> Serializer[Serializer Initialization] ClientNats --> Connection[createClient / connect] Connection --> NATS[NATS Broker] ClientNats --> Publish[publish / dispatchEvent] ClientNats --> Subscribe[createSubscriptionHandler / on] Connection --> Status[handleStatusUpdates] ClientNats --> RawClient[unwrap] ``` ## Usage ```ts import { ClientNats } from './client-nats'; const client = new ClientNats({ servers: ['nats://localhost:4222'], }); async function start() { await client.connect(); // Register a handler for messages received on a subject. client.on('orders.created', async (message) => { console.log('Received order event:', message); }); // Dispatch an event to NATS. await client.dispatchEvent('orders.created', { orderId: 'order-123', customerId: 'customer-456', }); // Access the underlying NATS client when lower-level APIs are needed. const natsClient = client.unwrap(); console.log('Connected to NATS:', !!natsClient); } start().catch(console.error); // Close the connection during application shutdown. // await client.close(); ``` ## AI Coding Instructions - Call `connect()` before publishing events, registering subscriptions, or accessing the underlying client with `unwrap()`. - Keep message payloads compatible with the configured serializer; initialize or preserve serializer behavior when extending the client. - Use `dispatchEvent()` for event-oriented publishing instead of bypassing the client with raw NATS calls unless lower-level functionality is required. - Ensure `close()` is called during application shutdown to release subscriptions and NATS connection resources. - Preserve status-update handling when changing connection logic so reconnects and broker state changes remain observable. ## Relationships - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `isObject` # EventPattern **Kind:** Function **Source:** [`packages/microservices/decorators/event-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/event-pattern.decorator.ts#L21) **Part of:** [Microservices](subsystem-packages-microservices) Subscribes to incoming events which fulfils chosen pattern. `EventPattern()` marks a controller method as a handler for incoming microservice events that match a specified pattern. Unlike request-response message handlers, event handlers process published events without returning a response to the sender. ## Signature ```ts function EventPattern(metadata: T, transportOrExtras: Transport | symbol | Record, maybeExtras: Record): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `metadata` | `T` | | `transportOrExtras` | `Transport | symbol | Record` | | `maybeExtras` | `Record` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Publisher[Event Publisher] --> Transport[Microservice Transport] Transport --> Pattern{Event Pattern Match} Pattern -->|Matches| Handler["@EventPattern() Method"] Pattern -->|Does not match| Ignore[Ignore Event] Handler --> Process[Process Event Payload] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { EventPattern, Payload } from '@nestjs/microservices'; @Controller() export class OrdersEventsController { @EventPattern('order.created') handleOrderCreated( @Payload() order: { id: string; customerId: string }, ): void { console.log(`Processing order ${order.id} for ${order.customerId}`); } } ``` ## AI Coding Instructions - Apply `@EventPattern()` to microservice controller methods that consume fire-and-forget events. - Keep event patterns consistent with the names used by publishers, such as `order.created` or `user.updated`. - Use `@Payload()` to receive event data and validate or transform it before performing business operations. - Do not rely on a return value from an event handler; publishers do not receive a response for event-based communication. - Ensure the application has a configured microservice transport capable of subscribing to the selected event pattern. ## Relationships - IMPORTS → `isNil` - IMPORTS → `isNumber` - IMPORTS → `isObject` - IMPORTS → `isSymbol` ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `KafkaMessagesController` — `integration/microservices/src/kafka/kafka.messages.controller.ts`:9 - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 - `RedisController` — `integration/microservices/src/redis/redis.controller.ts`:12 - `RMQController` — `integration/microservices/src/rmq/rmq.controller.ts`:16 - `AppController` — `integration/microservices/src/tcp-tls/app.controller.ts`:22 # Client **Kind:** Function **Source:** [`packages/microservices/decorators/client.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/client.decorator.ts#L12) **Part of:** [Microservices](subsystem-packages-microservices) Attaches the `ClientProxy` instance to the given property `Client()` is a property decorator that attaches a `ClientProxy` instance to a class property. It registers the supplied microservice client options so the application can create and use a transport-specific proxy for sending messages or emitting events to another service. ## Signature ```ts function Client(metadata: ClientOptions): PropertyDecorator ``` ## Parameters | Name | Type | |---|---| | `metadata` | `ClientOptions` | **Returns:** `PropertyDecorator` ## Diagram ```mermaid graph LR A[Service class property] --> B["@Client(clientOptions)"] B --> C[ClientProxy configuration metadata] C --> D[ClientProxy instance] D --> E[Remote microservice transport] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { Client, ClientProxy, Transport } from '@nestjs/microservices'; @Injectable() export class OrdersService { @Client({ transport: Transport.TCP, options: { host: 'localhost', port: 3001, }, }) private readonly inventoryClient: ClientProxy; async reserveInventory(productId: string, quantity: number) { return this.inventoryClient.send( { cmd: 'reserve_inventory' }, { productId, quantity }, ); } } ``` ## AI Coding Instructions - Apply `@Client()` only to class properties intended to hold a `ClientProxy`; declare the property type as `ClientProxy`. - Provide transport-specific configuration through the decorator options, including required connection details such as host, port, queue, or broker URLs. - Use `client.send()` for request-response messaging and `client.emit()` for event-based communication. - Ensure the target microservice is configured with the same transport and compatible message patterns. - Avoid manually constructing client proxies when decorator-based property injection is sufficient; keep client configuration close to the consuming service. ## Used by 11 references from 11 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (11) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 - `AdvancedGrpcController` — `integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`:14 - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 - `MqttBroadcastController` — `integration/microservices/src/mqtt/mqtt-broadcast.controller.ts`:11 - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 - `NatsBroadcastController` — `integration/microservices/src/nats/nats-broadcast.controller.ts`:11 …and 3 more. # ListenersController **Kind:** Class **Source:** [`packages/microservices/listeners-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listeners-controller.ts#L45) **Part of:** [Microservices](subsystem-packages-microservices) `ListenersController` is an internal NestJS microservices component that discovers `@MessagePattern()` and `@EventPattern()` handlers on controllers and registers them with a microservice server. It also resolves request-scoped handlers, attaches client proxies to decorated properties, and normalizes handler results into RxJS observables for transport processing. ## Methods | Method | Signature | Returns | |---|---|---| | `registerPatternHandlers` | `registerPatternHandlers(instanceWrapper: InstanceWrapper, serverInstance: Server, moduleKey: string)` | `void` | | `insertEntrypointDefinition` | `insertEntrypointDefinition(instanceWrapper: InstanceWrapper, definition: EventOrMessageListenerDefinition, transportId: Transport | symbol)` | `void` | | `forkJoinHandlersIfAttached` | `forkJoinHandlersIfAttached(currentReturnValue: Promise | Observable, originalArgs: unknown[], handlerRef: MessageHandler)` | `void` | | `assignClientsToProperties` | `assignClientsToProperties(instance: Controller)` | `void` | | `assignClientToInstance` | `assignClientToInstance(instance: Controller, property: string, client: T)` | `void` | | `createRequestScopedHandler` | `createRequestScopedHandler(wrapper: InstanceWrapper, pattern: PatternMetadata, moduleRef: Module, moduleKey: string, methodKey: string, defaultCallMetadata: Record, isEventHandler: undefined)` | `void` | | `transformToObservable` | `transformToObservable(resultOrDeferred: Observable | Promise)` | `Observable` | | `transformToObservable` | `transformToObservable(resultOrDeferred: T)` | `never extends Observable> ? Observable : Observable>` | | `transformToObservable` | `transformToObservable(resultOrDeferred: any)` | `void` | ## Where it refuses work - `ListenersController` stops the work with an early return when `isEventHandler`. - `ListenersController` stops the work with an early return when `resultOrDeferred instanceof Promise`. - `ListenersController` stops the work with an early return when `isObservable(resultOrDeferred)`. ## When something fails - `ListenersController` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR A[Nest application bootstrap] --> B[ListenersController] B --> C[Discover controller methods] C --> D[Read message/event pattern metadata] D --> E[Register handlers on microservice server] E --> F[Request-scoped handler creation] E --> G[Observable response stream] B --> H[Assign @Client() proxies to properties] H --> I[Controller instances] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { ClientProxy, ClientProxyFactory, MessagePattern, Transport, } from '@nestjs/microservices'; import { AppModule } from './app.module'; @Controller() class OrdersController { // In normal applications, ListenersController assigns this proxy // when using Nest's @Client() decorator and module metadata. private readonly billingClient: ClientProxy = ClientProxyFactory.create({ transport: Transport.TCP, }); @MessagePattern({ cmd: 'get-order' }) getOrder(orderId: string) { return { id: orderId, status: 'confirmed', }; } @MessagePattern({ cmd: 'stream-order-events' }) streamOrderEvents() { return this.billingClient.send({ cmd: 'order-events' }, {}); } } async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, }); // During startup, Nest internally uses ListenersController to // discover and register @MessagePattern() handlers. await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Treat `ListenersController` as framework infrastructure; applications should register handlers through `@MessagePattern()` and `@EventPattern()` rather than instantiating this class directly. - Preserve observable normalization when changing handler invocation logic: handlers may return plain values, promises, or RxJS observables. - Keep request-scoped handlers isolated by using the request context and scoped provider resolution path rather than reusing singleton controller instances. - When adding transport integrations, ensure every discovered pattern is registered with the server and that attached event handlers are joined/forked correctly. - Maintain client-property assignment behavior for controller instances using Nest microservice client proxy metadata. ## Relationships - IMPORTS → `Controller` - IMPORTS → `isUndefined` - IMPORTS → `ContextIdFactory` - IMPORTS → `ExecutionContextHost` - IMPORTS → `STATIC_CONTEXT` - IMPORTS → `NestContainer` - IMPORTS → `Injector` - IMPORTS → `ContextId` - IMPORTS → `InstanceWrapper` - IMPORTS → `Module` - IMPORTS → `GraphInspector` - IMPORTS → `MetadataScanner` - IMPORTS → `REQUEST_CONTEXT_ID` # RpcException **Kind:** Class **Source:** [`packages/microservices/exceptions/rpc-exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/exceptions/rpc-exception.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) `RpcException` represents errors that occur during microservice/RPC message handling. It wraps a string or object error payload, provides an `Error`-compatible message for logging, and preserves the original payload for transport-specific exception filters or serializers. **Extends:** `Error` ## Methods | Method | Signature | Returns | |---|---|---| | `initMessage` | `initMessage()` | `void` | | `getError` | `getError()` | `string | object` | ## Diagram ```mermaid graph LR A[Microservice Handler] -->|throws| B[RpcException] B --> C[initMessage()] C --> D[Error.message] B --> E[getError()] E --> F[Original string or object payload] F --> G[RPC Exception Filter / Transport Response] ``` ## Usage ```ts import { RpcException } from '@nestjs/microservices'; @Injectable() export class UsersService { async findOne(id: string) { const user = await this.usersRepository.findById(id); if (!user) { throw new RpcException({ statusCode: 404, message: `User ${id} was not found`, code: 'USER_NOT_FOUND', }); } return user; } } // Exception filters can access the original payload. const exception = new RpcException('Invalid request'); console.log(exception.message); // "Invalid request" console.log(exception.getError()); // "Invalid request" ``` ## AI Coding Instructions - Throw `RpcException` from microservice handlers when an error must be returned through an RPC transport rather than handled as a standard HTTP exception. - Pass either a descriptive string or a structured object; use objects when consumers need fields such as `code`, `statusCode`, or validation details. - Use `getError()` in custom RPC exception filters to retrieve the original payload instead of relying only on `message`. - Avoid exposing internal stack traces, database errors, or sensitive implementation details in the exception payload. - Ensure the selected microservice transport and exception filter serialize structured error objects consistently for downstream clients. ## Relationships - IMPORTS → `isObject` - IMPORTS → `isString` ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `ConfigService` — `integration/microservices/src/app.module.ts`:18 - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 - `AppController` — `integration/microservices/src/tcp-tls/app.controller.ts`:22 - `ConfigService` — `integration/microservices/src/tcp-tls/app.module.ts`:29 - `ExceptionFilter` — `sample/03-microservices/src/common/filters/rpc-exception.filter.ts`:5 # RpcContextCreator **Kind:** Class **Source:** [`packages/microservices/context/rpc-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-context-creator.ts#L41) **Part of:** [Microservices](subsystem-packages-microservices) `RpcContextCreator` builds the executable wrapper for NestJS microservice RPC handlers. It reflects handler parameter metadata, resolves guards, pipes, interceptors, and exception handling, then returns a function that produces an `Observable` for each incoming RPC request. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (...args: unknown[]) => Observable, moduleKey: string, methodName: string, contextId: undefined, inquirerId: string, defaultCallMetadata: Record)` | `(...args: any[]) => Promise>` | | `reflectCallbackParamtypes` | `reflectCallbackParamtypes(instance: Controller, callback: (...args: unknown[]) => unknown)` | `unknown[]` | | `createGuardsFn` | `createGuardsFn(guards: any[], instance: Controller, callback: (...args: unknown[]) => unknown, contextType: TContext)` | `Function | null` | | `getMetadata` | `getMetadata(instance: Controller, methodName: string, defaultCallMetadata: Record, contextType: TContext)` | `RpcHandlerMetadata` | | `exchangeKeysForValues` | `exchangeKeysForValues(keys: string[], metadata: TMetadata, moduleContext: string, paramsFactory: RpcParamsFactory, contextFactory: (args: unknown[]) => ExecutionContextHost)` | `ParamProperties[]` | | `createPipesFn` | `createPipesFn(pipes: PipeTransform[], paramsOptions: (ParamProperties & { metatype?: unknown })[])` | `void` | | `getParamValue` | `getParamValue(value: T, { metatype, type, data }: { metatype: any; type: any; data: any }, pipes: PipeTransform[])` | `Promise` | ## Where it refuses work - `RpcContextCreator` stops the work with `RpcException` when `!canActivate`. - `RpcContextCreator` stops the work with an early return when `cacheMetadata`. ## Diagram ```mermaid graph LR A[Incoming RPC message] --> B[RpcContextCreator.create] B --> C[Reflect handler parameter metadata] C --> D[Create guards, pipes, and interceptors] D --> E[Resolve RPC handler arguments] E --> F[Invoke controller method] F --> G[RpcProxy exception handling] G --> H[Observable response] ``` ## Usage ```ts import { lastValueFrom } from 'rxjs'; import { RpcContextCreator } from '@nestjs/microservices/context/rpc-context-creator'; class CustomTransportAdapter { constructor( private readonly rpcContextCreator: RpcContextCreator, ) {} registerHandler( controller: object, moduleKey: string, methodName: string, ) { const callback = (controller as any)[methodName]; // Nest internally creates this wrapper when binding RPC controller methods. const execute = this.rpcContextCreator.create( controller, callback, moduleKey, methodName, ); return async (payload: unknown, rpcContext: unknown) => { const response$ = await execute(payload, rpcContext); // Convert the handler Observable when the transport needs a Promise. return lastValueFrom(response$); }; } } ``` ## AI Coding Instructions - Use `create()` when binding an RPC controller method; it ensures guards, pipes, interceptors, and exception filters are applied consistently. - Preserve the original controller instance and method name so reflected parameter metadata can be resolved correctly. - Treat the function returned by `create()` as asynchronous and expect it to resolve to an `Observable`. - Do not invoke private metadata, guard, or pipe helper methods directly; extend integration behavior through NestJS guards, pipes, interceptors, and exception filters. - Pass the correct module key and request context when integrating custom transports, especially when request-scoped providers are involved. # KafkaReplyPartitionAssigner **Kind:** Class **Source:** [`packages/microservices/helpers/kafka-reply-partition-assigner.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/kafka-reply-partition-assigner.ts#L14) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaReplyPartitionAssigner` is a Kafka consumer-group partition assigner used by NestJS Kafka clients for reply topics. It creates stable reply-partition assignments based on client identity, helping ensure request/reply responses are consumed by the client instance that initiated the request. ## Methods | Method | Signature | Returns | |---|---|---| | `assign` | `assign(group: { members: GroupMember[]; topics: string[]; })` | `Promise` | | `protocol` | `protocol(subscription: { topics: string[]; userData: Buffer; })` | `GroupState` | | `getPreviousAssignment` | `getPreviousAssignment()` | `void` | | `decodeMember` | `decodeMember(member: GroupMember)` | `void` | ## Properties | Property | Type | |---|---| | `name` | `any` | | `version` | `any` | ## Diagram ```mermaid graph LR Client[Kafka client instance] --> Assigner[KafkaReplyPartitionAssigner] Assigner --> Protocol[protocol()] Assigner --> Decode[decodeMember()] Decode --> Previous[getPreviousAssignment()] Previous --> Assign[assign()] Assign --> Group[Kafka consumer group assignments] Group --> Replies[Reply topic partitions] ``` ## Usage ```ts import { Kafka } from 'kafkajs'; import { KafkaReplyPartitionAssigner } from '@nestjs/microservices/helpers/kafka-reply-partition-assigner'; const kafka = new Kafka({ clientId: 'orders-client', brokers: ['localhost:9092'], }); const replyAssigner = new KafkaReplyPartitionAssigner('orders-client'); const consumer = kafka.consumer({ groupId: 'orders-client-replies', partitionAssigners: [replyAssigner], }); await consumer.connect(); await consumer.subscribe({ topic: 'orders.reply', fromBeginning: false, }); await consumer.run({ eachMessage: async ({ message }) => { console.log('Received reply:', message.value?.toString()); }, }); ``` ## AI Coding Instructions - Configure this assigner on Kafka consumers responsible for request/reply response topics, not ordinary event-consumer groups. - Use a stable, unique client ID for each logical Kafka client; changing it can alter reply partition ownership. - Preserve assignment metadata compatibility when modifying `protocol()` or `decodeMember()`, since group members exchange this data during rebalances. - Keep `assign()` deterministic: members and partitions should be consistently ordered to avoid unnecessary Kafka group rebalances. - Prefer integrating through the NestJS Kafka client configuration rather than manually invoking `assign()` or `getPreviousAssignment()`. ## Relationships - IMPORTS → `loadPackage` - IMPORTS → `isUndefined` # MicroservicesModule **Kind:** Class **Source:** [`packages/microservices/microservices-module.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/microservices-module.ts#L23) **Part of:** [Microservices](subsystem-packages-microservices) `MicroservicesModule` coordinates microservice transport setup within the application. It registers configured listeners and clients, binds them during startup, and closes active connections during shutdown. ## Methods | Method | Signature | Returns | |---|---|---| | `register` | `register(container: NestContainer, graphInspector: GraphInspector, config: ApplicationConfig, options: TAppOptions)` | `void` | | `setupListeners` | `setupListeners(container: NestContainer, serverInstance: Server)` | `void` | | `setupClients` | `setupClients(container: NestContainer)` | `void` | | `bindListeners` | `bindListeners(controllers: Map>, serverInstance: Server, moduleName: string)` | `void` | | `bindClients` | `bindClients(items: Map>)` | `void` | | `close` | `close()` | `void` | ## Where it refuses work - `MicroservicesModule` stops the work with `RuntimeException` when `!this.listenersController`, in 2 places. - `MicroservicesModule` stops the work with an early return when `this.appOptions?.preview`. ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[MicroservicesModule] B --> C[register()] C --> D[setupListeners()] C --> E[setupClients()] D --> F[bindListeners()] E --> G[bindClients()] F --> H[Incoming Microservice Messages] G --> I[Outbound Client Requests] B --> J[close()] J --> K[Close Listeners and Clients] ``` ## Usage ```ts import { MicroservicesModule } from '@your-scope/microservices'; // Create the module with the application's configured microservice // listeners and client connections. const microservices = new MicroservicesModule(/* application dependencies */); // During application startup, register and bind transports. await microservices.register(); // The application can now receive messages through listeners // and send requests through configured clients. // During graceful shutdown, release transport resources. await microservices.close(); ``` ## AI Coding Instructions - Keep listener and client initialization separated: use `setupListeners()` and `setupClients()` for construction, then `bindListeners()` and `bindClients()` for activation. - Ensure `register()` is called during application bootstrap before handling microservice traffic. - Add new transport integrations through the module’s setup and binding flow rather than creating untracked connections elsewhere. - Always invoke `close()` during graceful shutdown to release listeners, client connections, and related resources. - Preserve startup ordering so listeners and clients are fully configured before they are bound. ## Relationships - IMPORTS → `Controller` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `ApplicationConfig` - IMPORTS → `RuntimeException` - IMPORTS → `GuardsConsumer` - IMPORTS → `GuardsContextCreator` - IMPORTS → `NestContainer` - IMPORTS → `Injector` - IMPORTS → `InstanceWrapper` - IMPORTS → `GraphInspector` - IMPORTS → `InterceptorsConsumer` - IMPORTS → `InterceptorsContextCreator` - IMPORTS → `PipesConsumer` - IMPORTS → `PipesContextCreator` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestApplication` — `packages/core/nest-application.ts`:54 # TcpSocket **Kind:** Class **Source:** [`packages/microservices/helpers/tcp-socket.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/tcp-socket.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) `TcpSocket` wraps a Node.js TCP socket for the microservices transport layer. It manages connection lifecycle events, message transmission, stream data handling, and emission of complete incoming messages after TCP packet framing is processed. ## Methods | Method | Signature | Returns | |---|---|---| | `connect` | `connect(port: number, host: string)` | `void` | | `on` | `on(event: string, callback: (err?: any) => void)` | `void` | | `once` | `once(event: string, callback: (err?: any) => void)` | `void` | | `end` | `end()` | `void` | | `sendMessage` | `sendMessage(message: any, callback: (err?: any) => void)` | `void` | | `handleSend` | `handleSend(message: any, callback: (err?: any) => void)` | `any` | | `handleData` | `handleData(data: Buffer | string)` | `any` | | `emitMessage` | `emitMessage(data: string)` | `void` | ## When something fails - `TcpSocket` handles failure in 2 places: it logs it and continues in 1, and lets it reach the caller in 1. ## Diagram ```mermaid graph LR Client[ClientTCP / ServerTCP] --> TcpSocket TcpSocket -->|connect / end| NetSocket[Node.js net.Socket] TcpSocket -->|sendMessage| Outbound[Framed TCP message] Outbound --> NetSocket NetSocket -->|data| HandleData[handleData] HandleData --> EmitMessage[emitMessage] EmitMessage --> MessageListeners[message event listeners] ``` ## Usage ```ts import { Socket } from 'node:net'; import { TcpSocket } from '@nestjs/microservices/helpers/tcp-socket'; const tcpSocket = new TcpSocket(new Socket()); tcpSocket.on('message', (payload: Buffer) => { console.log('Received response:', payload.toString()); }); tcpSocket.once('error', (error: Error) => { console.error('TCP connection failed:', error); }); await tcpSocket.connect(3000, '127.0.0.1'); tcpSocket.sendMessage( JSON.stringify({ pattern: 'health.check', data: {}, }), ); // Close the connection when no further messages are needed. tcpSocket.end(); ``` ## AI Coding Instructions - Use `TcpSocket` rather than interacting with the underlying `net.Socket` directly when implementing TCP microservice transport behavior. - Send protocol-compatible serialized messages; TCP is stream-based, so do not assume one `data` event equals one complete application message. - Register `message`, `error`, and close-related listeners before connecting or sending messages to avoid missing early socket events. - Preserve the existing `handleData()` and `emitMessage()` flow when changing framing logic, since it is responsible for reconstructing complete messages from streamed chunks. - Call `end()` during client or server shutdown to release socket resources cleanly. # MqttRecordBuilder **Kind:** Class **Source:** [`packages/microservices/record-builders/mqtt.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/mqtt.record-builder.ts#L45) **Part of:** [Microservices](subsystem-packages-microservices) `MqttRecordBuilder` constructs `MqttRecord` instances for MQTT message handling within the microservices transport layer. It provides a fluent API for configuring payload data, QoS, retain and duplicate flags, and MQTT v5 properties before creating an immutable record with `build()`. ## Methods | Method | Signature | Returns | |---|---|---| | `setData` | `setData(data: TData)` | `this` | | `setQoS` | `setQoS(qos: MqttRecordOptions['qos'])` | `this` | | `setRetain` | `setRetain(retain: MqttRecordOptions['retain'])` | `this` | | `setDup` | `setDup(dup: MqttRecordOptions['dup'])` | `this` | | `setProperties` | `setProperties(properties: MqttRecordOptions['properties'])` | `this` | | `build` | `build()` | `MqttRecord` | ## Diagram ```mermaid graph LR A[Message Payload] --> B[MqttRecordBuilder] C[QoS / Retain / Dup Flags] --> B D[MQTT Properties] --> B B -->|build()| E[MqttRecord] E --> F[MQTT Transport / Broker] ``` ## Usage ```ts import { MqttRecordBuilder } from './mqtt.record-builder'; const record = new MqttRecordBuilder() .setData(Buffer.from(JSON.stringify({ event: 'order.created', orderId: '123' }))) .setQoS(1) .setRetain(false) .setDup(false) .setProperties({ contentType: 'application/json', }) .build(); // Pass the record to the MQTT publishing or transport layer. ``` ## AI Coding Instructions - Use the fluent setter pattern: configure all required values through `setData()`, `setQoS()`, and optional MQTT flags before calling `build()`. - Validate payload format and QoS values at the integration boundary; MQTT QoS must match the broker and client capabilities. - Use `setRetain(true)` only for messages intended to be stored by the broker and delivered to future subscribers. - Set `dup` only when handling MQTT redelivery behavior; it should not be used as a general retry indicator. - Keep MQTT v5 metadata in `setProperties()` and ensure property names and values are compatible with the MQTT client implementation. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 # KafkaContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/kafka.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/kafka.context.ts#L16) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaContext` provides access to Kafka-specific metadata and clients for a message handled by a NestJS microservice. It lets message handlers inspect the raw message, topic, and partition, while also exposing the consumer, producer, and heartbeat callback for advanced Kafka workflows. **Extends:** `BaseRpcContext` ## Methods | Method | Signature | Returns | |---|---|---| | `getMessage` | `getMessage()` | `void` | | `getPartition` | `getPartition()` | `void` | | `getTopic` | `getTopic()` | `void` | | `getConsumer` | `getConsumer()` | `void` | | `getHeartbeat` | `getHeartbeat()` | `void` | | `getProducer` | `getProducer()` | `void` | ## Diagram ```mermaid graph LR A[Kafka Consumer] --> B[Kafka Message] B --> C[KafkaContext] C --> D[getMessage()] C --> E[getTopic()] C --> F[getPartition()] C --> G[getConsumer()] C --> H[getHeartbeat()] C --> I[getProducer()] C --> J[NestJS Message Handler] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, MessagePattern, Payload } from '@nestjs/microservices'; import { KafkaContext } from '@nestjs/microservices'; @Controller() export class OrdersConsumer { @MessagePattern('orders.created') async handleOrderCreated( @Payload() order: { id: string; customerId: string }, @Ctx() context: KafkaContext, ) { const message = context.getMessage(); const topic = context.getTopic(); const partition = context.getPartition(); console.log(`Received order ${order.id} from ${topic}[${partition}]`); console.log('Kafka message key:', message.key?.toString()); // Use this during long-running processing to keep the consumer session alive. await context.getHeartbeat(); } } ``` ## AI Coding Instructions - Use `KafkaContext` as the `@Ctx()` argument in Kafka message handlers; avoid manually constructing it. - Prefer `getTopic()`, `getPartition()`, and `getMessage()` when logging or diagnosing message processing behavior. - Call `getHeartbeat()` during long-running handler work to prevent consumer-group rebalancing caused by missed heartbeats. - Use `getConsumer()` and `getProducer()` only for Kafka-specific operations that cannot be handled through normal NestJS messaging patterns. - Treat the raw Kafka message returned by `getMessage()` as transport metadata; decode keys, headers, and values defensively. # RmqContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/rmq.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/rmq.context.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `RmqContext` provides access to RabbitMQ-specific metadata during a microservice message handler invocation. It exposes the raw incoming message, the underlying AMQP channel, and the matched message pattern so handlers can inspect payloads and acknowledge or reject deliveries. **Extends:** `BaseRpcContext` ## Methods | Method | Signature | Returns | |---|---|---| | `getMessage` | `getMessage()` | `void` | | `getChannelRef` | `getChannelRef()` | `void` | | `getPattern` | `getPattern()` | `void` | ## Diagram ```mermaid graph LR RabbitMQ[RabbitMQ Queue] --> Handler[Message Handler] Handler --> Context[RmqContext] Context --> Message[getMessage()] Context --> Channel[getChannelRef()] Context --> Pattern[getPattern()] Channel --> Ack[channel.ack(message)] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, MessagePattern, Payload, RmqContext, } from '@nestjs/microservices'; @Controller() export class OrdersController { @MessagePattern('orders.created') handleOrderCreated( @Payload() order: { id: string; total: number }, @Ctx() context: RmqContext, ) { const message = context.getMessage(); const channel = context.getChannelRef(); const pattern = context.getPattern(); console.log(`Received ${pattern} for order ${order.id}`); console.log(`Delivery tag: ${message.fields.deliveryTag}`); channel.ack(message); } } ``` ## AI Coding Instructions - Inject `RmqContext` with `@Ctx()` in RabbitMQ message handlers decorated with `@MessagePattern()` or `@EventPattern()`. - Use `getMessage()` when access to raw AMQP properties, fields, headers, or the delivery tag is required. - Use `getChannelRef()` to manually call `ack()`, `nack()`, or `reject()` when the RabbitMQ transport is configured with `noAck: false`. - Do not acknowledge a message before all required processing succeeds; use rejection or retry handling for recoverable failures. - Use `getPattern()` for logging, tracing, or behavior that depends on the matched routing pattern. ## How it works `RmqContext` is a public, exported RabbitMQ RPC context class that extends `BaseRpcContext` with a three-element argument tuple: a message record, a channel reference, and a string pattern. [packages/microservices/ctx-host/rmq.context.ts:3-10] Its constructor accepts that tuple and passes it to `BaseRpcContext`, which stores it as the protected, read-only `args` value. [packages/microservices/ctx-host/rmq.context.ts:8-10] [packages/microservices/ctx-host/base-rpc.context.ts:4-5] It exposes: - `getMessage()`, which returns tuple element `0`: the original message. [packages/microservices/ctx-host/rmq.context.ts:13-18] - `getChannelRef()`, which returns tuple element `1`: the original RabbitMQ channel reference. [packages/microservices/ctx-host/rmq.context.ts:20-25] - `getPattern()`, which returns tuple element `2`: the pattern string. [packages/microservices/ctx-host/rmq.context.ts:27-32] - The inherited `getArgs()` and `getArgByIndex(index)` methods, which return the full stored tuple or an element selected by index. [packages/microservices/ctx-host/base-rpc.context.ts:7-20] `ServerRMQ.handleMessage()` constructs this context after deserializing an incoming message. It supplies the received message object, the channel passed to the handler, and a pattern that is left unchanged when already a string or is JSON-stringified otherwise. [packages/microservices/server/server-rmq.ts:290-304] The server passes the context to event handling and to matched message handlers. [packages/microservices/server/server-rmq.ts:305-306] [packages/microservices/server/server-rmq.ts:328-345] The class contains no visible argument validation, error throwing, message acknowledgement, channel operation, or mutation beyond storing the supplied tuple through its base-class constructor. [packages/microservices/ctx-host/rmq.context.ts:8-32] [packages/microservices/ctx-host/base-rpc.context.ts:4-20] ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RMQFanoutExchangeConsumerController` — `integration/microservices/src/rmq/fanout-exchange-consumer-rmq.controller.ts`:4 - `RMQController` — `integration/microservices/src/rmq/rmq.controller.ts`:16 - `RMQTopicExchangeController` — `integration/microservices/src/rmq/topic-exchange-rmq.controller.ts`:12 # ListenerMetadataExplorer **Kind:** Class **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) `ListenerMetadataExplorer` discovers microservice listener metadata declared on controller methods, including message patterns and event handlers. It scans controller prototypes, converts decorator metadata into listener definitions, and identifies client hooks used by the microservices runtime during server setup. ## Methods | Method | Signature | Returns | |---|---|---| | `explore` | `explore(instance: Controller)` | `EventOrMessageListenerDefinition[]` | | `exploreMethodMetadata` | `exploreMethodMetadata(instance: Controller, instancePrototype: object, methodKey: string)` | `EventOrMessageListenerDefinition | undefined` | | `scanForClientHooks` | `scanForClientHooks(instance: Controller)` | `IterableIterator` | ## Where it refuses work - `ListenerMetadataExplorer` stops the work with an early return when `isUndefined(handlerType)`. ## Diagram ```mermaid graph LR Controller[Controller instance] --> Explorer[ListenerMetadataExplorer] Explorer --> Scanner[MetadataScanner] Explorer --> Reflector[Reflector] Scanner --> Methods[Controller methods] Reflector --> Metadata[Pattern and client metadata] Metadata --> Definitions[EventOrMessageListenerDefinition[]] Definitions --> Server[Microservice server bindings] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { EventPattern, MessagePattern } from '@nestjs/microservices'; // ListenerMetadataExplorer is typically used internally by Nest's // microservices infrastructure rather than instantiated in application code. @Controller() class OrdersController { @MessagePattern('orders.find') findOrder(data: { id: string }) { return { id: data.id, status: 'pending' }; } @EventPattern('orders.created') handleOrderCreated(data: { id: string }) { console.log(`Order created: ${data.id}`); } } // During microservice initialization, Nest: // 1. Scans OrdersController methods. // 2. Reads @MessagePattern() and @EventPattern() metadata. // 3. Produces listener definitions. // 4. Registers handlers with the configured transport. ``` ## AI Coding Instructions - Preserve metadata-driven discovery: listener definitions must be derived from method decorator metadata rather than manually inferred from method names. - Use the framework `MetadataScanner` and `Reflector` utilities when scanning controller prototypes; avoid scanning only instance-owned properties. - Keep message-pattern handlers and event-pattern handlers distinct, since event handlers do not follow request/response semantics. - Ensure transport-specific metadata is respected when filtering or registering discovered listener definitions. - Treat this class as infrastructure code: changes can affect controller discovery, client hooks, and microservice transport registration globally. # transformPatternToRoute **Kind:** Function **Source:** [`packages/microservices/utils/transform-pattern.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/utils/transform-pattern.utils.ts#L21) **Part of:** [Microservices](subsystem-packages-microservices) Transforms the Pattern to Route safely. `transformPatternToRoute` converts a microservice message pattern into a route-like string that can be used for transport-level routing or identification. String patterns are returned unchanged, while object patterns are flattened into slash-separated key/value segments; unsupported pattern values safely resolve to an empty string. ## Signature ```ts function transformPatternToRoute(pattern: MsPattern, depth, maxDepth, maxKeys): string ``` ## Parameters | Name | Type | |---|---| | `pattern` | `MsPattern` | | `depth` | `any` | | `maxDepth` | `any` | | `maxKeys` | `any` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Microservice Pattern] --> B{Pattern type} B -->|String| C[Return pattern unchanged] B -->|Object| D[Convert each key/value to segment] D --> E[Join segments with /] E --> F[Route string] B -->|Invalid or unsupported| G[Return empty string] ``` ## Usage ```ts import { transformPatternToRoute } from '@nestjs/microservices/utils/transform-pattern.utils'; const stringRoute = transformPatternToRoute('users.create'); // "users.create" const objectRoute = transformPatternToRoute({ service: 'users', action: 'create', }); // "service/users/action/create" const invalidRoute = transformPatternToRoute(null as any); // "" ``` ## AI Coding Instructions - Preserve string patterns exactly; do not normalize, trim, or add route separators to them. - When passing object patterns, use stable and meaningful key ordering because property order determines the generated route. - Handle potentially invalid or non-object pattern values before relying on the returned route in downstream transport logic. - Keep this utility transport-agnostic; transport-specific routing behavior should be implemented by the caller or adapter. ## Relationships - IMPORTS → `isNumber` - IMPORTS → `isObject` - IMPORTS → `isString` # createGrpcMethodMetadata **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L216) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function createGrpcMethodMetadata(target: object, key: string | symbol, service: string | undefined, method: string | undefined, streaming) ``` ## Parameters | Name | Type | |---|---| | `target` | `object` | | `key` | `string | symbol` | | `service` | `string | undefined` | | `method` | `string | undefined` | | `streaming` | `any` | # KafkaParser **Kind:** Class **Source:** [`packages/microservices/helpers/kafka-parser.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/kafka-parser.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaParser` transforms raw Kafka message payloads into application-friendly objects. It preserves Kafka metadata and headers while decoding message values as JSON when possible, falling back to strings, buffers, or `null` when appropriate. ## Methods | Method | Signature | Returns | |---|---|---| | `parse` | `parse(data: any)` | `T` | | `decode` | `decode(value: Buffer)` | `object | string | null | Buffer` | ## Properties | Property | Type | |---|---| | `keepBinary` | `boolean` | ## Where it refuses work - `KafkaParser` stops the work with an early return when `isNil(value)`. - `KafkaParser` stops the work with an early return when `Buffer.isBuffer(value) && value.length > 0 && value.readUInt8(0) === 0`. ## When something fails - `KafkaParser` handles failure in 1 place: it discards it silently in all 1. ## Diagram ```mermaid graph LR A[Raw Kafka Message] --> B[KafkaParser.parse] B --> C[Extract metadata and headers] C --> D[KafkaParser.decode] D --> E{Valid JSON?} E -->|Yes| F[Parsed object] E -->|No| G[String or Buffer value] F --> H[Normalized message object] G --> H ``` ## Usage ```ts import { KafkaParser } from '@nestjs/microservices'; const parser = new KafkaParser(); const rawMessage = { topic: 'orders', partition: 0, offset: '42', headers: { 'correlation-id': Buffer.from('request-123'), }, value: Buffer.from( JSON.stringify({ orderId: 'order-456', status: 'created', }), ), }; const message = parser.parse<{ topic: string; partition: number; offset: string; headers: Record; value: { orderId: string; status: string; }; }>(rawMessage); console.log(message.value.orderId); // "order-456" console.log(message.value.status); // "created" ``` ## AI Coding Instructions - Pass complete Kafka message objects to `parse()` so topic, partition, offset, and headers remain available after parsing. - Expect `decode()` to return a parsed object for JSON payloads, a string for non-JSON text payloads, `null` for empty values, or a `Buffer` when applicable. - Do not assume every Kafka message value is JSON; validate the parsed `value` shape before using object properties. - Preserve Kafka headers and metadata when wrapping or extending parsed messages for downstream handlers. - Use a custom value parser configuration when consumers require specialized serialization formats beyond JSON. ## Relationships - IMPORTS → `isNil` # RequestContextHost **Kind:** Class **Source:** [`packages/microservices/context/request-context-host.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/request-context-host.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) `RequestContextHost` is a lightweight implementation of the microservices `RequestContext` interface. It stores a message pattern, payload data, and transport-specific context, exposing them through typed getter methods for use in message handlers and interceptors. **Implements:** `RequestContext` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(pattern: string | Record, data: TData, context: TContext)` | `RequestContext` | | `getData` | `getData()` | `TData` | | `getPattern` | `getPattern()` | `string | Record` | | `getContext` | `getContext()` | `TContext` | ## Diagram ```mermaid graph LR A[Incoming microservice message] --> B[RequestContextHost] B --> C[getPattern()] B --> D[getData()] B --> E[getContext()] C --> F[Message routing metadata] D --> G[Payload] E --> H[Transport-specific context] ``` ## Usage ```ts import { RequestContextHost } from '@nestjs/microservices'; interface CreateUserPayload { email: string; name: string; } const context = RequestContextHost.create( { cmd: 'create_user' }, { email: 'ada@example.com', name: 'Ada Lovelace', }, { requestId: 'req_123', }, ); console.log(context.getPattern()); // { cmd: 'create_user' } console.log(context.getData().email); // ada@example.com console.log(context.getContext().requestId); // req_123 ``` ## AI Coding Instructions - Preserve the generic `TData` and `TContext` types so payload and transport context remain type-safe. - Use `RequestContextHost.create()` when constructing a context outside the normal microservice request pipeline. - Treat the context as a read-only request snapshot; access values through `getData()`, `getPattern()`, and `getContext()`. - Support both string and object message patterns when consuming the value returned by `getPattern()`. - Keep transport-specific metadata in `TContext`; do not mix it into the message payload data. ## How it works `RequestContextHost` is an exported public class that implements the `RequestContext` shape and represents a request as a pattern, data payload, and RPC context. Its context type is constrained to `BaseRpcContext`; both generic types default to `any`. [packages/microservices/context/request-context-host.ts:4-10] - Its constructor requires `pattern`, `data`, and `context`, then exposes each as a `public readonly` property. `pattern` may be a string or record; `data` has type `TData`; `context` has type `TContext`. [packages/microservices/context/request-context-host.ts:11-15] - `getData()`, `getPattern()`, and `getContext()` return those stored properties directly. [packages/microservices/context/request-context-host.ts:26-36] - `create()` constructs a new host from the same three inputs and returns it typed as `RequestContext`. [packages/microservices/context/request-context-host.ts:17-24] - The class contains no runtime input validation, transformation, explicit error handling, or mutation after construction. [packages/microservices/context/request-context-host.ts:11-36] The stored context can expose its handler arguments through `BaseRpcContext.getArgs()` and a single indexed argument through `getArgByIndex()`. [packages/microservices/ctx-host/base-rpc.context.ts:4-20] In microservice listener dispatch, request-scoped handlers recognize a `RequestContextHost` passed as their first argument, derive a context ID from it, and remove it before invoking the handler proxy. [packages/microservices/listeners-controller.ts:238-245] When no host is first, the listener creates one from the matched pattern, incoming data, and RPC context before deriving the context ID. [packages/microservices/listeners-controller.ts:246-255] During that context-ID derivation, the listener may attach a non-enumerable request-context ID property to the host and register a request-provider value with the container. [packages/microservices/listeners-controller.ts:302-320] # JsonSocket **Kind:** Class **Source:** [`packages/microservices/helpers/json-socket.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/json-socket.ts#L13) **Part of:** [Microservices](subsystem-packages-microservices) `JsonSocket` wraps a TCP socket with length-prefixed JSON message framing for the microservices transport layer. It serializes outgoing payloads in `handleSend()` and incrementally buffers, reconstructs, and parses incoming TCP chunks in `handleData()` before delivering complete messages to registered listeners. **Extends:** `TcpSocket` ## Methods | Method | Signature | Returns | |---|---|---| | `handleSend` | `handleSend(message: any, callback: (err?: any) => void)` | `void` | | `handleData` | `handleData(dataRaw: Buffer | string)` | `void` | ## Diagram ```mermaid graph LR A[Application message] --> B[JsonSocket.handleSend] B --> C[Serialize JSON and add length prefix] C --> D[TCP socket] D --> E[Incoming TCP chunks] E --> F[JsonSocket.handleData] F --> G[Buffer and resolve frame length] G --> H[Parse complete JSON message] H --> I[Message listener] ``` ## AI Coding Instructions - Preserve the length-prefixed framing format when changing `handleSend()` or `handleData()`; TCP data may arrive split across multiple chunks or contain multiple messages in one chunk. - Use `handleSend()` for outgoing serialization rather than writing raw JSON directly to the underlying socket. - Keep buffering logic resilient to partial payloads and reset parser state only after a complete frame has been processed. - Treat malformed frame lengths and invalid JSON as transport-level errors; avoid silently emitting incomplete or corrupted messages. - Prefer the inherited `send()`, `onMessage()`, `connect()`, and `close()` APIs at integration points instead of calling the internal handlers directly. # NatsRecordBuilder **Kind:** Class **Source:** [`packages/microservices/record-builders/nats.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/nats.record-builder.ts#L14) **Part of:** [Microservices](subsystem-packages-microservices) `NatsRecordBuilder` creates a `NatsRecord` for NATS-based microservice messages. Use it to attach message data and optional NATS headers before building the record passed to a NATS client. ## Methods | Method | Signature | Returns | |---|---|---| | `setHeaders` | `setHeaders(headers: THeaders)` | `this` | | `setData` | `setData(data: TData)` | `this` | | `build` | `build()` | `NatsRecord` | ## Diagram ```mermaid graph LR A[Application Data] --> B[NatsRecordBuilder] C[NATS Headers] --> B B -->|setData / setHeaders| D[build()] D --> E[NatsRecord] E --> F[NATS Client Message] ``` ## Usage ```ts import { NatsRecordBuilder } from '@nestjs/microservices'; import { headers } from 'nats'; const messageHeaders = headers(); messageHeaders.set('x-request-id', 'request-123'); messageHeaders.set('x-source', 'orders-service'); const record = new NatsRecordBuilder() .setData({ orderId: 'order-456', status: 'created', }) .setHeaders(messageHeaders) .build(); // Example: pass the record to a NATS client client.emit('orders.created', record); ``` ## AI Coding Instructions - Use `setData()` to provide the payload that NATS consumers should receive. - Use `setHeaders()` only with valid NATS header objects, not plain JavaScript objects. - Call `build()` after configuring the builder; send the resulting `NatsRecord` through the NATS client. - Preserve correlation, tracing, and request metadata in headers when integrating with distributed services. - Avoid mutating the payload or headers after building when the record may be reused or sent asynchronously. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 # RmqRecordBuilder **Kind:** Class **Source:** [`packages/microservices/record-builders/rmq.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/rmq.record-builder.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) `RmqRecordBuilder` constructs `RmqRecord` instances for RabbitMQ-based microservice messages. It provides a fluent API for attaching message data and RabbitMQ publishing options before producing the final record with `build()`. ## Methods | Method | Signature | Returns | |---|---|---| | `setOptions` | `setOptions(options: RmqRecordOptions)` | `this` | | `setData` | `setData(data: TData)` | `this` | | `build` | `build()` | `RmqRecord` | ## Diagram ```mermaid graph LR A[Application message data] --> B[RmqRecordBuilder] C[RabbitMQ publish options] --> B B -->|setData() / setOptions()| D[Configured builder] D -->|build()| E[RmqRecord] E --> F[RMQ client transport] ``` ## Usage ```ts import { RmqRecordBuilder } from '@nestjs/microservices'; const record = new RmqRecordBuilder() .setData({ event: 'order.created', orderId: 'order-123', }) .setOptions({ persistent: true, headers: { 'x-correlation-id': 'request-456', }, }) .build(); // Example: publish through an injected NestJS ClientProxy client.emit('orders.events', record); ``` ## AI Coding Instructions - Use the fluent chain `setData(...).setOptions(...).build()` when creating RabbitMQ records. - Call `build()` only after providing the payload required by the receiving consumer. - Keep transport-specific settings, such as `persistent` and message headers, in `setOptions()` rather than mixing them into the data payload. - Pass the built `RmqRecord` to RMQ-enabled `ClientProxy` methods such as `emit()` or `send()`. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RMQController` — `integration/microservices/src/rmq/rmq.controller.ts`:16 # BaseRpcExceptionFilter **Kind:** Class **Source:** [`packages/microservices/exceptions/base-rpc-exception-filter.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/exceptions/base-rpc-exception-filter.ts#L15) **Part of:** [Microservices](subsystem-packages-microservices) `BaseRpcExceptionFilter` is the default foundation for handling exceptions thrown by NestJS microservice RPC handlers. It converts known `RpcException` instances into error observables and safely maps unknown errors to a standardized internal-error response while logging unexpected failures. **Implements:** `RpcExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: T, host: ArgumentsHost)` | `Observable` | | `handleUnknownError` | `handleUnknownError(exception: T, status: string)` | `void` | | `isError` | `isError(exception: any)` | `exception is Error` | ## Where it refuses work - `BaseRpcExceptionFilter` stops the work with an early return when `!(exception instanceof RpcException)`. ## Diagram ```mermaid graph LR A[RPC Handler throws exception] --> B[BaseRpcExceptionFilter.catch] B --> C{Is RpcException?} C -- Yes --> D[Extract exception error payload] D --> E[Return error Observable] C -- No --> F[handleUnknownError] F --> G{Is Error instance?} G -- Yes --> H[Log unexpected error] G -- No --> I[Create unknown error response] H --> I I --> E ``` ## Usage ```ts import { Catch, ArgumentsHost } from '@nestjs/common'; import { BaseRpcExceptionFilter, RpcException, } from '@nestjs/microservices'; import { Observable } from 'rxjs'; @Catch() export class RpcExceptionFilter extends BaseRpcExceptionFilter { catch(exception: unknown, host: ArgumentsHost): Observable { // Add custom logging, metrics, or error normalization here. return super.catch(exception, host); } } // In an RPC controller: throw new RpcException({ status: 'VALIDATION_ERROR', message: 'The provided email address is invalid.', }); ``` ## AI Coding Instructions - Extend this class when custom RPC exception behavior is needed; delegate to `super.catch()` unless intentionally replacing the default mapping. - Throw `RpcException` for expected, client-safe microservice errors so its payload is preserved in the RPC response. - Do not expose raw unknown error messages or stack traces to RPC consumers; use `handleUnknownError()` for safe fallback responses. - Use `isError()` before relying on `message` or `stack` properties when handling values that may not be native `Error` instances. - Ensure custom filters are registered with the relevant microservice/controller context so they run for RPC transport requests. ## Relationships - IMPORTS → `ArgumentsHost` - IMPORTS → `IntrinsicException` - IMPORTS → `Logger` - IMPORTS → `RpcExceptionFilter` - IMPORTS → `isObject` - IMPORTS → `MESSAGES` # IncomingRequestDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/incoming-request.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/incoming-request.deserializer.ts#L11) **Part of:** [Microservices](subsystem-packages-microservices) `IncomingRequestDeserializer` converts raw inbound microservice payloads into normalized `IncomingRequest` or `IncomingEvent` domain objects. It determines whether an incoming payload is external and maps its fields to the schema consumed by downstream request and event handling code. **Implements:** `ConsumerDeserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `deserialize` | `deserialize(value: any, options: Record)` | `IncomingRequest | IncomingEvent` | | `isExternal` | `isExternal(value: any)` | `boolean` | | `mapToSchema` | `mapToSchema(value: any, options: Record)` | `IncomingRequest | IncomingEvent` | ## Where it refuses work - `IncomingRequestDeserializer` stops the work with an early return when `!value`. - `IncomingRequestDeserializer` stops the work with an early return when `!isUndefined((value as IncomingRequest).pattern) || !isUndefined((value as IncomingReques…`. - `IncomingRequestDeserializer` stops the work with an early return when `!options`. ## Diagram ```mermaid graph LR A[Raw incoming payload] --> B[IncomingRequestDeserializer] B --> C{isExternal()} C -->|External request| D[mapToSchema()] C -->|Internal event| D D --> E[IncomingRequest] D --> F[IncomingEvent] E --> G[Request processing pipeline] F --> H[Event processing pipeline] ``` ## Usage ```ts import { IncomingRequestDeserializer } from "./deserializers/incoming-request.deserializer"; const rawPayload = { method: "POST", url: "/orders", headers: { "content-type": "application/json", }, body: { orderId: "order_123", }, }; const deserializer = new IncomingRequestDeserializer(rawPayload); const incomingMessage = deserializer.deserialize(); if (deserializer.isExternal()) { // Handle a normalized external IncomingRequest. console.log("Received an external request", incomingMessage); } else { // Handle a normalized internal IncomingEvent. console.log("Received an internal event", incomingMessage); } ``` ## AI Coding Instructions - Use `deserialize()` as the public entry point; avoid calling `mapToSchema()` directly unless extending the deserialization flow. - Keep request/event normalization logic centralized in this class so downstream handlers only consume `IncomingRequest` or `IncomingEvent`. - Update `isExternal()` when adding new transport metadata or payload types that affect external-versus-internal classification. - Preserve the expected schema shape in `mapToSchema()` and validate optional headers, body fields, and transport-specific metadata defensively. ## Relationships - IMPORTS → `isUndefined` # RpcExceptionsHandler **Kind:** Class **Source:** [`packages/microservices/exceptions/rpc-exceptions-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/exceptions/rpc-exceptions-handler.ts#L13) **Part of:** [Microservices](subsystem-packages-microservices) `RpcExceptionsHandler` handles exceptions raised while processing microservice RPC requests. It first attempts to delegate errors to registered custom RPC exception filters, then falls back to the framework's default RPC exception handling behavior when no filter applies. **Extends:** `BaseRpcExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `handle` | `handle(exception: Error | RpcException, host: ArgumentsHost)` | `Observable` | | `setCustomFilters` | `setCustomFilters(filters: RpcExceptionFilterMetadata[])` | `void` | | `invokeCustomFilters` | `invokeCustomFilters(exception: T, host: ArgumentsHost)` | `Observable | null` | ## Where it refuses work - `RpcExceptionsHandler` stops the work with `InvalidExceptionFilterException` when `!Array.isArray(filters)`. - `RpcExceptionsHandler` stops the work with an early return when `filterResult$`. - `RpcExceptionsHandler` stops the work with an early return when `isEmpty(this.filters)`. ## Diagram ```mermaid graph LR A[RPC handler throws exception] --> B[RpcExceptionsHandler.handle] B --> C[invokeCustomFilters] C -->|Matching filter found| D[Custom RPC exception filter] C -->|No matching filter| E[BaseRpcExceptionFilter.catch] D --> F[Observable RPC error response] E --> F ``` ## Usage ```ts import { RpcExceptionsHandler } from '@nestjs/microservices'; import { RpcException } from '@nestjs/microservices'; import { Observable, throwError } from 'rxjs'; const exceptionsHandler = new RpcExceptionsHandler(); exceptionsHandler.setCustomFilters([ { catch(exception: Error): Observable { console.error('RPC error:', exception.message); return throwError( () => new RpcException('A service-specific error occurred'), ); }, }, ]); const response$ = exceptionsHandler.handle( new Error('Unable to process payment'), ); response$.subscribe({ error: error => console.error(error), }); ``` ## AI Coding Instructions - Register custom filters through `setCustomFilters()` when a microservice needs transport- or domain-specific error responses. - Ensure custom filters return an `Observable`; RPC exception handling is asynchronous and must preserve the observable contract. - Let `handle()` remain the main entry point so custom filters are evaluated before default exception serialization. - Make custom filters target specific exception types where possible to avoid unintentionally handling unrelated RPC errors. - Keep fallback behavior intact: if `invokeCustomFilters()` returns `null`, delegate to the base RPC exception handler. ## How it works - `RpcExceptionsHandler` is an exported public class that extends `BaseRpcExceptionFilter`. It maintains a private array of RPC exception-filter metadata, initially empty. [packages/microservices/exceptions/rpc-exceptions-handler.ts:10-14] - `handle(exception, host)` first calls `invokeCustomFilters`. If that call returns a truthy observable, `handle` returns it; otherwise it delegates to the inherited `catch(exception, host)` method. Its declared inputs are an `Error` or `RpcException` and an `ArgumentsHost`, and its declared return type is `Observable`. [packages/microservices/exceptions/rpc-exceptions-handler.ts:16-25] - A configured filter is selected only when its `exceptionMetatypes` array is empty or the thrown value is an `instanceof` at least one listed metatype. Selection uses `find`, so only the first matching metadata entry is invoked. The selected entry’s `func` is called with `(exception, host)` and its observable is returned. [packages/microservices/exceptions/rpc-exceptions-handler.ts:34-44] [packages/common/utils/select-exception-filter-metadata.util.ts:3-13] The metadata contract consists of a filter `catch` function and an array of exception metatypes; that function returns an observable. [packages/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts:4-7] [packages/common/interfaces/exceptions/rpc-exception-filter.interface.ts:11-19] - If no filters have been set, or the stored array has no items, `invokeCustomFilters` returns `null`. It also returns `null` when no configured filter matches, causing `handle` to use inherited handling. [packages/microservices/exceptions/rpc-exceptions-handler.ts:38-43] [packages/common/utils/shared.utils.ts:48-50] - `setCustomFilters(filters)` requires its runtime argument to be an array. A non-array throws `InvalidExceptionFilterException`; an array replaces the handler’s stored filter array. [packages/microservices/exceptions/rpc-exceptions-handler.ts:27-32] That exception extends `RuntimeException` and is initialized with the message `Invalid exception filters (@UseFilters()).`. [packages/core/errors/exceptions/invalid-exception-filter.exception.ts:4-7] [packages/core/errors/messages.ts:260-263] - In the inherited fallback, a `RpcException` produces an RxJS error observable: if `getError()` returns an object, that object is emitted as the error; otherwise the emitted error is `{ status: 'error', message: }`. [packages/microservices/exceptions/base-rpc-exception-filter.ts:21-29] An exception that is not a `RpcException` produces an error observable with `{ status: 'error', message: 'Internal server error' }`; it is logged unless it is an `IntrinsicException`. [packages/microservices/exceptions/base-rpc-exception-filter.ts:31-40] [packages/core/constants.ts:5-8] - In the microservices execution path, `ExceptionFiltersContext.create` instantiates this handler, builds filter metadata for a controller callback, and, when that set is non-empty, stores the reversed array through `setCustomFilters`. [packages/microservices/context/exception-filters-context.ts:24-45] `RpcProxy` sends both rejected observables and thrown callback errors to `handle`, creating an `ExecutionContextHost` from the call arguments and marking its type as `rpc`. [packages/microservices/context/rpc-proxy.ts:11-23] [packages/microservices/context/rpc-proxy.ts:27-35] ## Relationships - IMPORTS → `RpcExceptionFilterMetadata` - IMPORTS → `ArgumentsHost` - IMPORTS → `selectExceptionFilterMetadata` - IMPORTS → `isEmpty` - IMPORTS → `InvalidExceptionFilterException` # ExceptionFiltersContext **Kind:** Class **Source:** [`packages/microservices/context/exception-filters-context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/exception-filters-context.ts#L16) **Part of:** [Microservices](subsystem-packages-microservices) `ExceptionFiltersContext` builds the `RpcExceptionsHandler` used to process exceptions thrown by microservice RPC handlers. It collects exception filters declared on controllers and handlers, combines them with global filter metadata, and configures the handler with the correct execution order. **Extends:** `BaseExceptionFilterContext` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (data: T) => Observable, module: string, contextId: undefined, inquirerId: string)` | `RpcExceptionsHandler` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: undefined, inquirerId: string)` | `T` | ## Where it refuses work - `ExceptionFiltersContext` stops the work with an early return when `isEmpty(filters)`. - `ExceptionFiltersContext` stops the work with an early return when `contextId === STATIC_CONTEXT && !inquirerId`. ## Diagram ```mermaid graph LR A[RPC request] --> B[Microservice handler] B -->|throws exception| C[RpcExceptionsHandler] D[ExceptionFiltersContext] -->|creates| C D -->|collects| E[Controller and method filters] D -->|gets| F[Global exception filters] E --> C F --> C C --> G[Custom exception response] ``` ## Usage ```ts import { Catch, ArgumentsHost } from '@nestjs/common'; import { RpcExceptionFilter } from '@nestjs/microservices'; @Catch() class RpcErrorFilter implements RpcExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { return { status: 'error', message: exception instanceof Error ? exception.message : 'Unknown RPC error', }; } } // ExceptionFiltersContext is created internally by Nest's microservice runtime. // Registering filters through the application configuration makes them available // when it creates the RpcExceptionsHandler for each RPC handler. async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, }); app.useGlobalFilters(new RpcErrorFilter()); await app.listen(); } ``` ## AI Coding Instructions - Treat `ExceptionFiltersContext` as framework infrastructure; register filters through decorators or `app.useGlobalFilters()` rather than constructing it in application code. - Ensure custom RPC filters implement `RpcExceptionFilter` and return a value compatible with the active microservice transport. - Preserve filter ordering when changing context creation logic; method- and controller-level filters must be applied consistently with global filters. - Use `getGlobalMetadata()` when extending context behavior so request-scoped global filters are included alongside static global filters. ## How it works `ExceptionFiltersContext` is a public microservices context creator that extends `BaseExceptionFilterContext`. It receives a `NestContainer` for resolving filter classes and an `ApplicationConfig` for global filter registrations. [packages/microservices/context/exception-filters-context.ts:16-22] ## Relationships - IMPORTS → `EXCEPTION_FILTERS_METADATA` - IMPORTS → `Controller` - IMPORTS → `isEmpty` - IMPORTS → `ApplicationConfig` - IMPORTS → `BaseExceptionFilterContext` - IMPORTS → `STATIC_CONTEXT` - IMPORTS → `NestContainer` - IMPORTS → `InstanceWrapper` # GrpcStreamMethod **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L132) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcStreamMethod` decorates a controller method as a gRPC streaming RPC handler. It registers the method with NestJS using the gRPC service and RPC method name so incoming stream requests are routed to an RxJS-based handler. ## Signature ```ts function GrpcStreamMethod(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client Stream] --> Server[gRPC Microservice Server] Server --> Decorator["@GrpcStreamMethod(service, method)"] Decorator --> Handler[Controller Handler] Handler --> Observable[RxJS Observable Response Stream] Observable --> Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Observable, map } from 'rxjs'; import { GrpcStreamMethod } from '@nestjs/microservices'; interface HeroRequest { id: number; } interface Hero { id: number; name: string; } @Controller() export class HeroesController { @GrpcStreamMethod('HeroesService', 'FindMany') findMany(request$: Observable): Observable { return request$.pipe( map(({ id }) => ({ id, name: `Hero ${id}`, })), ); } } ``` ## AI Coding Instructions - Use `@GrpcStreamMethod(serviceName, methodName)` on controller methods that handle gRPC streaming RPCs. - Return an `Observable` when implementing streaming responses; process incoming request streams with RxJS operators. - Ensure the service and method names match the corresponding definitions in the loaded `.proto` file. - Omit the method name only when the controller method name matches the gRPC RPC method name. - Configure the application with the `Transport.GRPC` microservice transport before expecting decorated handlers to receive requests. # GrpcStreamMethod **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L132) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcStreamMethod` decorates a controller method as a gRPC streaming RPC handler. It registers the method with NestJS using the gRPC service and RPC method name so incoming stream requests are routed to an RxJS-based handler. ## Signature ```ts function GrpcStreamMethod(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client Stream] --> Server[gRPC Microservice Server] Server --> Decorator["@GrpcStreamMethod(service, method)"] Decorator --> Handler[Controller Handler] Handler --> Observable[RxJS Observable Response Stream] Observable --> Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Observable, map } from 'rxjs'; import { GrpcStreamMethod } from '@nestjs/microservices'; interface HeroRequest { id: number; } interface Hero { id: number; name: string; } @Controller() export class HeroesController { @GrpcStreamMethod('HeroesService', 'FindMany') findMany(request$: Observable): Observable { return request$.pipe( map(({ id }) => ({ id, name: `Hero ${id}`, })), ); } } ``` ## AI Coding Instructions - Use `@GrpcStreamMethod(serviceName, methodName)` on controller methods that handle gRPC streaming RPCs. - Return an `Observable` when implementing streaming responses; process incoming request streams with RxJS operators. - Ensure the service and method names match the corresponding definitions in the loaded `.proto` file. - Omit the method name only when the controller method name matches the gRPC RPC method name. - Configure the application with the `Transport.GRPC` microservice transport before expecting decorated handlers to receive requests. # GrpcStreamMethod **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L132) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcStreamMethod` decorates a controller method as a gRPC streaming RPC handler. It registers the method with NestJS using the gRPC service and RPC method name so incoming stream requests are routed to an RxJS-based handler. ## Signature ```ts function GrpcStreamMethod(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client Stream] --> Server[gRPC Microservice Server] Server --> Decorator["@GrpcStreamMethod(service, method)"] Decorator --> Handler[Controller Handler] Handler --> Observable[RxJS Observable Response Stream] Observable --> Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Observable, map } from 'rxjs'; import { GrpcStreamMethod } from '@nestjs/microservices'; interface HeroRequest { id: number; } interface Hero { id: number; name: string; } @Controller() export class HeroesController { @GrpcStreamMethod('HeroesService', 'FindMany') findMany(request$: Observable): Observable { return request$.pipe( map(({ id }) => ({ id, name: `Hero ${id}`, })), ); } } ``` ## AI Coding Instructions - Use `@GrpcStreamMethod(serviceName, methodName)` on controller methods that handle gRPC streaming RPCs. - Return an `Observable` when implementing streaming responses; process incoming request streams with RxJS operators. - Ensure the service and method names match the corresponding definitions in the loaded `.proto` file. - Omit the method name only when the controller method name matches the gRPC RPC method name. - Configure the application with the `Transport.GRPC` microservice transport before expecting decorated handlers to receive requests. # IncomingResponseDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/incoming-response.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/incoming-response.deserializer.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) `IncomingResponseDeserializer` normalizes responses received by microservice transports into the internal `IncomingResponse` schema. It detects whether a value is already in the expected envelope format and wraps external/raw responses when necessary, allowing downstream response handling to use a consistent structure. **Implements:** `ProducerDeserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `deserialize` | `deserialize(value: any, options: Record)` | `IncomingResponse` | | `isExternal` | `isExternal(value: any)` | `boolean` | | `mapToSchema` | `mapToSchema(value: any)` | `IncomingResponse` | ## Where it refuses work - `IncomingResponseDeserializer` stops the work with an early return when `!value`. - `IncomingResponseDeserializer` stops the work with an early return when `!isUndefined((value as IncomingResponse).err) || !isUndefined((value as IncomingResponse)…`. ## Diagram ```mermaid graph LR A[Raw transport response] --> B[deserialize] B --> C{isExternal?} C -- No --> D[Return existing IncomingResponse] C -- Yes --> E[mapToSchema] E --> F[Normalized IncomingResponse] ``` ## Usage ```ts import { IncomingResponseDeserializer } from '@nestjs/microservices'; const deserializer = new IncomingResponseDeserializer(); const rawResponse = { id: 'request-42', data: { status: 'ok' }, }; const response = deserializer.deserialize(rawResponse); console.log(response.id); // "request-42" console.log(response.response); // original raw response payload console.log(response.isDisposed); // true ``` ## AI Coding Instructions - Use `deserialize()` as the public entry point; do not call `mapToSchema()` directly unless extending the deserialization behavior. - Preserve already-normalized `IncomingResponse` objects instead of wrapping them again. - Keep `isExternal()` aligned with the response envelope contract used by the active microservice transport. - When changing the mapped schema, verify compatibility with downstream client response handling and request correlation via `id`. ## Relationships - IMPORTS → `isUndefined` # KafkaJSError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1144) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `Error` ## Properties | Property | Type | |---|---| | `message` | `Error['message']` | | `name` | `string` | | `retriable` | `boolean` | | `helpUrl` | `string` | | `cause` | `Error` | # KafkaJSRequestTimeoutError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1185) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `broker` | `string` | | `correlationId` | `number` | | `createdAt` | `number` | | `sentAt` | `number` | | `pendingDuration` | `number` | # KafkaRequestSerializer **Kind:** Class **Source:** [`packages/microservices/serializers/kafka-request.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/kafka-request.serializer.ts#L19) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaRequestSerializer` prepares outbound Kafka messages for transport by normalizing payloads into Kafka-compatible message objects. It JSON-encodes object and array values while preserving strings, `Buffer` instances, and `null`, and applies the same encoding rules to message keys and headers. **Implements:** `Serializer` ## Methods | Method | Signature | Returns | |---|---|---| | `serialize` | `serialize(value: any)` | `void` | | `encode` | `encode(value: any)` | `Buffer | string | null` | ## Where it refuses work - `KafkaRequestSerializer` stops the work with an early return when `isUndefined(value)`. ## Diagram ```mermaid graph LR A[Application payload] --> B[KafkaRequestSerializer.serialize] B --> C{Kafka message shape?} C -- No --> D[Wrap as { value: payload }] C -- Yes --> E[Use key, value, and headers] D --> F[encode value] E --> F E --> G[encode key] E --> H[encode headers] F --> I[Kafka-compatible message] G --> I H --> I ``` ## Usage ```ts import { KafkaRequestSerializer } from '@nestjs/microservices'; const serializer = new KafkaRequestSerializer(); const message = serializer.serialize({ key: { tenantId: 'tenant-42' }, value: { event: 'order.created', orderId: 'order-123', }, headers: { correlationId: 'request-abc', metadata: { source: 'checkout' }, }, }); console.log(message); // { // key: '{"tenantId":"tenant-42"}', // value: '{"event":"order.created","orderId":"order-123"}', // headers: { // correlationId: 'request-abc', // metadata: '{"source":"checkout"}' // } // } ``` ## AI Coding Instructions - Pass plain payloads or Kafka message-shaped objects containing `value`, optionally with `key` and `headers`. - Keep string values and `Buffer` values as-is; objects and arrays are automatically serialized with `JSON.stringify`. - Ensure objects placed in `key`, `value`, or `headers` are JSON-serializable to avoid runtime serialization failures. - Use `Buffer` explicitly when producing binary Kafka payloads rather than relying on JSON encoding. - Preserve Kafka message fields when extending this serializer, especially `key`, `value`, and `headers`. # MqttContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/mqtt.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/mqtt.context.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `MqttContext` provides metadata for an incoming MQTT message handled by a NestJS microservice. It exposes the MQTT topic and the raw MQTT packet so message handlers can inspect routing information, QoS, headers, and other transport-level details. **Extends:** `BaseRpcContext` ## Methods | Method | Signature | Returns | |---|---|---| | `getTopic` | `getTopic()` | `void` | | `getPacket` | `getPacket()` | `void` | ## Diagram ```mermaid graph LR Client[MQTT Client] --> Broker[MQTT Broker] Broker --> Server[NestJS MQTT Server] Server --> Handler[Message Handler] Server --> Context[MqttContext] Context --> Topic[getTopic()] Context --> Packet[getPacket()] Handler --> Context ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, MessagePattern, MqttContext } from '@nestjs/microservices'; @Controller() export class DeviceController { @MessagePattern('devices/+/status') handleStatusUpdate( payload: { online: boolean }, @Ctx() context: MqttContext, ) { const topic = context.getTopic(); const packet = context.getPacket(); console.log(`Received message on topic: ${topic}`); console.log(`QoS level: ${packet.qos}`); return { received: true, online: payload.online }; } } ``` ## AI Coding Instructions - Use `@Ctx() context: MqttContext` in MQTT `@MessagePattern()` handlers when transport metadata is required. - Call `getTopic()` to inspect the original MQTT topic, especially when using wildcard topic patterns. - Call `getPacket()` for MQTT-specific metadata such as QoS, retain flags, duplicate delivery status, and packet properties. - Treat the packet as transport metadata; keep business logic focused on the message payload whenever possible. - Ensure handlers are configured under a NestJS microservice using the MQTT transport before relying on `MqttContext`. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 # NatsContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/nats.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/nats.context.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `NatsContext` provides access to NATS-specific metadata for an incoming microservice message. Use it in NATS message handlers to inspect the message subject and any associated headers without coupling application logic directly to the transport layer. **Extends:** `BaseRpcContext` ## Methods | Method | Signature | Returns | |---|---|---| | `getSubject` | `getSubject()` | `void` | | `getHeaders` | `getHeaders()` | `void` | ## Diagram ```mermaid graph LR Publisher[NATS Publisher] -->|subject + headers + payload| Server[NATS Server] Server --> Handler[Message Handler] Handler --> Context[NatsContext] Context --> Subject[getSubject()] Context --> Headers[getHeaders()] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, MessagePattern, Payload } from '@nestjs/microservices'; import { NatsContext } from '@nestjs/microservices'; @Controller() export class OrdersController { @MessagePattern('orders.created') handleOrderCreated( @Payload() order: { id: string }, @Ctx() context: NatsContext, ) { const subject = context.getSubject(); const headers = context.getHeaders(); console.log(`Received order ${order.id} on ${subject}`); console.log('Request headers:', headers); return { received: true }; } } ``` ## AI Coding Instructions - Inject `NatsContext` with `@Ctx()` only in handlers executed through the NATS transport. - Use `getSubject()` when behavior depends on the NATS subject that routed the message. - Use `getHeaders()` for transport metadata such as tracing, correlation IDs, or custom message attributes. - Do not assume headers are always present; handle missing or undefined header values safely. - Keep business logic transport-agnostic where possible, and isolate NATS-specific metadata handling at the message-handler boundary. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 # ClientsContainer **Kind:** Class **Source:** [`packages/microservices/container.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/container.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) `ClientsContainer` manages a collection of `ClientProxy` instances used by the microservices layer. It provides a central place to register clients, retrieve all registered clients, and clear the collection during cleanup or lifecycle transitions. ## Methods | Method | Signature | Returns | |---|---|---| | `getAllClients` | `getAllClients()` | `ClientProxy[]` | | `addClient` | `addClient(client: ClientProxy)` | `void` | | `clear` | `clear()` | `void` | ## Diagram ```mermaid graph LR A[ClientProxy] -->|addClient()| B[ClientsContainer] B -->|getAllClients()| C[ClientProxy[]] B -->|clear()| D[Empty client collection] ``` ## Usage ```ts import { ClientProxyFactory, ClientsContainer, Transport, } from '@nestjs/microservices'; const clientsContainer = new ClientsContainer(); const ordersClient = ClientProxyFactory.create({ transport: Transport.TCP, options: { host: 'localhost', port: 3001, }, }); clientsContainer.addClient(ordersClient); const clients = clientsContainer.getAllClients(); for (const client of clients) { await client.connect(); } // Remove registered client references during cleanup. clientsContainer.clear(); ``` ## AI Coding Instructions - Register each `ClientProxy` with `addClient()` before expecting it to be available through `getAllClients()`. - Treat `getAllClients()` as the source of registered clients when implementing bulk connection, shutdown, or health-check behavior. - Ensure client lifecycle cleanup is handled explicitly; clearing the container removes registrations but may not close active client connections. - Avoid creating duplicate client registrations for the same logical service without first considering the intended replacement or cleanup behavior. - Keep `ClientsContainer` focused on client registration and lookup rather than transport-specific messaging logic. # RpcProxy **Kind:** Class **Source:** [`packages/microservices/context/rpc-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-proxy.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) `RpcProxy` wraps RPC handler callbacks with consistent asynchronous execution and error handling. It converts thrown errors and observable stream errors into RPC-compatible error responses, including unwrapping `RpcException` payloads for microservice transports. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(targetCallback: (...args: unknown[]) => Promise>, exceptionsHandler: RpcExceptionsHandler)` | `(...args: unknown[]) => Promise>` | | `handleError` | `handleError(exceptionsHandler: RpcExceptionsHandler, args: unknown[], error: T)` | `Observable` | ## When something fails - `RpcProxy` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR A[Microservice transport] --> B[RpcProxy.create] B --> C[RPC handler callback] C --> D{Returns or throws} D -->|Observable result| E[Attach catchError] D -->|Thrown error| F[handleError] E --> G[RPC response Observable] F --> G ``` ## Usage ```ts import { Observable, of } from 'rxjs'; import { RpcException } from '@nestjs/microservices'; import { RpcProxy } from '@nestjs/microservices/context/rpc-proxy'; const rpcProxy = new RpcProxy(); const handler = async (id: string): Promise> => { if (!id) { throw new RpcException('A user id is required'); } return of({ id, name: 'Ada Lovelace' }); }; const proxiedHandler = rpcProxy.create(handler); const response$ = await proxiedHandler('user-123'); response$.subscribe({ next: response => console.log(response), error: error => console.error('RPC error:', error), }); ``` ## AI Coding Instructions - Wrap microservice request handlers with `RpcProxy.create()` when adding transport-level execution paths that need standardized RPC error behavior. - Return `Observable` values from wrapped handlers; errors emitted by the observable are routed through `handleError()`. - Use `RpcException` for expected client-facing RPC failures so its payload can be sent through the configured transport. - Do not manually duplicate `try/catch` and RxJS `catchError` logic around handlers when `RpcProxy` is already responsible for error normalization. - Preserve the asynchronous callback signature when integrating with new transports or context creators. ## How it works ## `RpcProxy` `RpcProxy` is a class that wraps an RPC callback with exception handling. Its `create()` method accepts a callback and an `RpcExceptionsHandler`, then returns an asynchronous function that accepts and forwards arbitrary arguments. [packages/microservices/context/rpc-proxy.ts:6-10] ## Relationships - IMPORTS → `ExecutionContextHost` # Kafka **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L19) **Part of:** [Microservices](subsystem-packages-microservices) `Kafka` provides access to the Kafka client components used by the microservices layer: producers, consumers, administrative operations, and logging. It acts as a central integration point for publishing messages, subscribing to topics, managing Kafka resources, and reporting Kafka-related activity. ## Methods | Method | Signature | Returns | |---|---|---| | `producer` | `producer(config: ProducerConfig)` | `Producer` | | `consumer` | `consumer(config: ConsumerConfig)` | `Consumer` | | `admin` | `admin(config: AdminConfig)` | `Admin` | | `logger` | `logger()` | `Logger` | ## Diagram ```mermaid graph LR App[Microservice] --> Kafka[Kafka] Kafka --> Producer[Producer] Kafka --> Consumer[Consumer] Kafka --> Admin[Admin] Kafka --> Logger[Logger] Producer --> Broker[Kafka Broker] Consumer --> Broker Admin --> Broker Logger --> Logs[Application Logs] ``` ## Usage ```ts import type { Kafka } from './kafka.interface'; async function publishUserCreated(kafka: Kafka) { const producer = kafka.producer(); await producer.connect(); await producer.send({ topic: 'users.created', messages: [ { key: 'user-123', value: JSON.stringify({ id: 'user-123', email: 'user@example.com', }), }, ], }); kafka.logger().info('Published users.created event', { userId: 'user-123', }); await producer.disconnect(); } ``` ## AI Coding Instructions - Access Kafka clients through `producer()`, `consumer()`, and `admin()` instead of creating KafkaJS clients directly. - Connect and disconnect producers or consumers according to the surrounding application lifecycle; avoid creating a new connection for every message when a shared client is available. - Serialize message payloads consistently, typically with `JSON.stringify`, and use stable message keys when partition ordering matters. - Use `logger()` for Kafka-related errors, retries, and lifecycle events rather than writing directly to console output. - Use `admin()` only for broker or topic management operations, not for normal message publishing or consumption. # BaseRpcContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/base-rpc.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/base-rpc.context.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) `BaseRpcContext` is a base context holder for RPC-style microservice handlers. It stores the arguments supplied to a request and provides access to the complete argument collection or an individual argument by index. Transport-specific context implementations can extend this class to expose consistent handler metadata. ## Methods | Method | Signature | Returns | |---|---|---| | `getArgs` | `getArgs()` | `T` | | `getArgByIndex` | `getArgByIndex(index: number)` | `void` | ## Diagram ```mermaid graph LR Request[Incoming RPC request] --> Context[BaseRpcContext] Context --> Args[getArgs(): T] Context --> ArgIndex[getArgByIndex(index)] Args --> Handler[Microservice handler] ArgIndex --> Handler ``` ## Usage ```ts import { BaseRpcContext } from '@nestjs/microservices'; class CustomRpcContext extends BaseRpcContext<[string, number]> {} const context = new CustomRpcContext(['user-123', 42]); const args = context.getArgs(); // ['user-123', 42] const userId = context.getArgByIndex(0); // 'user-123' const retryCount = context.getArgByIndex(1); // 42 ``` ## AI Coding Instructions - Extend `BaseRpcContext` when implementing a transport-specific RPC context that needs to expose request arguments. - Use `getArgs()` when consumers need the complete, typed argument tuple or array. - Use `getArgByIndex(index)` only when the argument position is stable and documented by the transport contract. - Preserve argument ordering when constructing or forwarding contexts; index-based access depends on it. - Prefer strongly typed tuple generics for `T` so handler code receives accurate argument types. # getGrpcPackageDefinition **Kind:** Function **Source:** [`packages/microservices/helpers/grpc-helpers.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/grpc-helpers.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function getGrpcPackageDefinition(options: GrpcOptions['options'], grpcProtoLoaderPackage: any) ``` ## Parameters | Name | Type | |---|---| | `options` | `GrpcOptions['options']` | | `grpcProtoLoaderPackage` | `any` | # GrpcStreamCall **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L196) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcStreamCall` decorates a controller method as a gRPC streaming call handler. It registers the target service and method as a gRPC message pattern, allowing the microservice runtime to route a bidirectional stream request to the decorated handler. ## Signature ```ts function GrpcStreamCall(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client] -->|stream request| Server[gRPC Microservice Server] Server -->|match service + method| Metadata[GrpcStreamCall Metadata] Metadata --> Handler[Decorated Controller Handler] Handler -->|response stream| Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { GrpcStreamCall } from '@nestjs/microservices'; import { Observable, map } from 'rxjs'; interface HeroById { id: number; } interface Hero { id: number; name: string; } @Controller() export class HeroesController { @GrpcStreamCall('HeroesService', 'FindMany') findMany(requests$: Observable): Observable { return requests$.pipe( map(({ id }) => ({ id, name: `Hero ${id}`, })), ); } } ``` ## AI Coding Instructions - Use `GrpcStreamCall` for gRPC methods that receive and return streams; use the matching service and RPC method names defined in the `.proto` file. - Keep the decorated handler signature compatible with streaming RPCs, typically accepting and returning `Observable` values. - Ensure the controller is registered in the microservice module and that the application is configured with the `Transport.GRPC` transport. - Avoid changing service or method names independently from the protobuf contract, as routing depends on exact metadata matches. # GrpcStreamCall **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L196) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcStreamCall` decorates a controller method as a gRPC streaming call handler. It registers the target service and method as a gRPC message pattern, allowing the microservice runtime to route a bidirectional stream request to the decorated handler. ## Signature ```ts function GrpcStreamCall(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client] -->|stream request| Server[gRPC Microservice Server] Server -->|match service + method| Metadata[GrpcStreamCall Metadata] Metadata --> Handler[Decorated Controller Handler] Handler -->|response stream| Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { GrpcStreamCall } from '@nestjs/microservices'; import { Observable, map } from 'rxjs'; interface HeroById { id: number; } interface Hero { id: number; name: string; } @Controller() export class HeroesController { @GrpcStreamCall('HeroesService', 'FindMany') findMany(requests$: Observable): Observable { return requests$.pipe( map(({ id }) => ({ id, name: `Hero ${id}`, })), ); } } ``` ## AI Coding Instructions - Use `GrpcStreamCall` for gRPC methods that receive and return streams; use the matching service and RPC method names defined in the `.proto` file. - Keep the decorated handler signature compatible with streaming RPCs, typically accepting and returning `Observable` values. - Ensure the controller is registered in the microservice module and that the application is configured with the `Transport.GRPC` transport. - Avoid changing service or method names independently from the protobuf contract, as routing depends on exact metadata matches. # GrpcStreamCall **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L196) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcStreamCall` decorates a controller method as a gRPC streaming call handler. It registers the target service and method as a gRPC message pattern, allowing the microservice runtime to route a bidirectional stream request to the decorated handler. ## Signature ```ts function GrpcStreamCall(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client] -->|stream request| Server[gRPC Microservice Server] Server -->|match service + method| Metadata[GrpcStreamCall Metadata] Metadata --> Handler[Decorated Controller Handler] Handler -->|response stream| Client ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { GrpcStreamCall } from '@nestjs/microservices'; import { Observable, map } from 'rxjs'; interface HeroById { id: number; } interface Hero { id: number; name: string; } @Controller() export class HeroesController { @GrpcStreamCall('HeroesService', 'FindMany') findMany(requests$: Observable): Observable { return requests$.pipe( map(({ id }) => ({ id, name: `Hero ${id}`, })), ); } } ``` ## AI Coding Instructions - Use `GrpcStreamCall` for gRPC methods that receive and return streams; use the matching service and RPC method names defined in the `.proto` file. - Keep the decorated handler signature compatible with streaming RPCs, typically accepting and returning `Observable` values. - Ensure the controller is registered in the microservice module and that the application is configured with the `Transport.GRPC` transport. - Avoid changing service or method names independently from the protobuf contract, as routing depends on exact metadata matches. # KafkaJSNumberOfRetriesExceeded **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1170) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSNonRetriableError` ## Properties | Property | Type | |---|---| | `stack` | `string` | | `retryCount` | `number` | | `retryTime` | `number` | # TcpContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/tcp.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/tcp.context.ts#L9) **Part of:** [Microservices](subsystem-packages-microservices) `TcpContext` provides TCP-specific metadata to NestJS microservice message handlers. It exposes the underlying client socket and the pattern associated with the incoming message, allowing handlers to inspect connection details when needed. **Extends:** `BaseRpcContext` ## Methods | Method | Signature | Returns | |---|---|---| | `getSocketRef` | `getSocketRef()` | `void` | | `getPattern` | `getPattern()` | `void` | ## Diagram ```mermaid graph LR Client[TCP Client] --> Server[NestJS TCP Server] Server --> Handler[Message Handler] Handler --> Context[TcpContext] Context --> Socket[getSocketRef()] Context --> Pattern[getPattern()] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, MessagePattern, TcpContext } from '@nestjs/microservices'; @Controller() export class MathController { @MessagePattern('sum') sum( data: number[], @Ctx() context: TcpContext, ): number { const socket = context.getSocketRef(); const pattern = context.getPattern(); console.log(`Received "${pattern}" from ${socket.remoteAddress}`); return data.reduce((total, value) => total + value, 0); } } ``` ## AI Coding Instructions - Use `TcpContext` only in handlers invoked through the NestJS TCP microservice transport. - Inject the context with `@Ctx() context: TcpContext` alongside `@MessagePattern()` handlers. - Use `getSocketRef()` for connection-level metadata such as remote address or port; avoid mutating or closing the socket unless the transport lifecycle requires it. - Use `getPattern()` when logging, tracing, or routing behavior based on the incoming message pattern. ## How it works `TcpContext` is a public context class for TCP message handling. It extends `BaseRpcContext` with an argument tuple whose first item is a `TcpSocket` and whose second item is a string pattern. [tcp.context.ts:4-11](packages/microservices/ctx-host/tcp.context.ts#L4-L11) - Construct it with `[socket, pattern]`; its constructor passes that tuple directly to `BaseRpcContext`. [tcp.context.ts:4-12](packages/microservices/ctx-host/tcp.context.ts#L4-L12) - `getSocketRef()` returns the tuple’s first item—the same `TcpSocket` reference supplied at construction. [tcp.context.ts:17-19](packages/microservices/ctx-host/tcp.context.ts#L17-L19) - `getPattern()` returns the tuple’s second item—the supplied pattern string. [tcp.context.ts:24-26](packages/microservices/ctx-host/tcp.context.ts#L24-L26) - Through `BaseRpcContext`, it also inherits `getArgs()` to return the complete tuple and `getArgByIndex(index)` to return an item at the requested index. [base-rpc.context.ts:4-20](packages/microservices/ctx-host/base-rpc.context.ts#L4-L20) `ServerTCP.handleMessage()` deserializes an incoming message, converts a non-string packet pattern with `JSON.stringify`, constructs `TcpContext` from `[socket, pattern]`, and passes that context to either event handling or the matched request handler. [server-tcp.ts:93-101](packages/microservices/server/server-tcp.ts#L93-L101) [server-tcp.ts:114-120](packages/microservices/server/server-tcp.ts#L114-L120) There is no runtime validation, error throwing, socket I/O, or mutation in `TcpContext` itself; its constructor stores the supplied tuple via the base class, and its declared methods only read tuple elements. [tcp.context.ts:9-26](packages/microservices/ctx-host/tcp.context.ts#L9-L26) # ClientGrpc **Kind:** Interface **Source:** [`packages/microservices/interfaces/client-grpc.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/client-grpc.interface.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) ## Used by 4 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Injected or called by (1) - `HeroController` — `sample/04-grpc/src/hero/hero.controller.ts`:17 ### Imported by (3) - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 - `AdvancedGrpcController` — `integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`:14 - `HeroController` — `sample/04-grpc/src/hero/hero.controller.ts`:17 # GrpcMethod **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L104) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcMethod()` marks a controller method as a handler for a gRPC service RPC. It stores the service and method metadata used by the microservice transport to route incoming gRPC requests to the decorated method. ## Signature ```ts function GrpcMethod(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client] --> Server[gRPC Microservice Server] Server --> Service[Proto Service and RPC] Service --> Decorator["@GrpcMethod('UsersService', 'FindOne')"] Decorator --> Handler[Controller Handler Method] Handler --> Response[gRPC Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { GrpcMethod } from '@nestjs/microservices'; interface FindUserRequest { id: string; } interface User { id: string; name: string; } @Controller() export class UsersController { @GrpcMethod('UsersService', 'FindOne') findOne(request: FindUserRequest): User { return { id: request.id, name: 'Ada Lovelace', }; } } ``` ## AI Coding Instructions - Match the `service` and RPC method names with the definitions in the loaded `.proto` file. - Decorate methods in a controller that is registered with the gRPC microservice module. - Keep handler request and response shapes compatible with the generated protobuf contract. - Use the explicit method argument when the TypeScript method name differs from the proto RPC name. - Do not use this decorator for HTTP routes; use it only for handlers served by a gRPC transport. # GrpcMethod **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L104) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcMethod()` marks a controller method as a handler for a gRPC service RPC. It stores the service and method metadata used by the microservice transport to route incoming gRPC requests to the decorated method. ## Signature ```ts function GrpcMethod(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client] --> Server[gRPC Microservice Server] Server --> Service[Proto Service and RPC] Service --> Decorator["@GrpcMethod('UsersService', 'FindOne')"] Decorator --> Handler[Controller Handler Method] Handler --> Response[gRPC Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { GrpcMethod } from '@nestjs/microservices'; interface FindUserRequest { id: string; } interface User { id: string; name: string; } @Controller() export class UsersController { @GrpcMethod('UsersService', 'FindOne') findOne(request: FindUserRequest): User { return { id: request.id, name: 'Ada Lovelace', }; } } ``` ## AI Coding Instructions - Match the `service` and RPC method names with the definitions in the loaded `.proto` file. - Decorate methods in a controller that is registered with the gRPC microservice module. - Keep handler request and response shapes compatible with the generated protobuf contract. - Use the explicit method argument when the TypeScript method name differs from the proto RPC name. - Do not use this decorator for HTTP routes; use it only for handlers served by a gRPC transport. # GrpcMethod **Kind:** Function **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L104) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcMethod()` marks a controller method as a handler for a gRPC service RPC. It stores the service and method metadata used by the microservice transport to route incoming gRPC requests to the decorated method. ## Signature ```ts function GrpcMethod(service: string | undefined, method: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `service` | `string | undefined` | | `method` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[gRPC Client] --> Server[gRPC Microservice Server] Server --> Service[Proto Service and RPC] Service --> Decorator["@GrpcMethod('UsersService', 'FindOne')"] Decorator --> Handler[Controller Handler Method] Handler --> Response[gRPC Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { GrpcMethod } from '@nestjs/microservices'; interface FindUserRequest { id: string; } interface User { id: string; name: string; } @Controller() export class UsersController { @GrpcMethod('UsersService', 'FindOne') findOne(request: FindUserRequest): User { return { id: request.id, name: 'Ada Lovelace', }; } } ``` ## AI Coding Instructions - Match the `service` and RPC method names with the definitions in the loaded `.proto` file. - Decorate methods in a controller that is registered with the gRPC microservice module. - Keep handler request and response shapes compatible with the generated protobuf contract. - Use the explicit method argument when the TypeScript method name differs from the proto RPC name. - Do not use this decorator for HTTP routes; use it only for handlers served by a gRPC transport. # IORedisOptions **Kind:** Interface **Source:** [`packages/microservices/external/redis.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/redis.interface.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `IORedisOptions` defines the Redis client connection and behavior options used by the microservices Redis integration. It configures authentication, database selection, TCP settings, command timeouts, client identification, and reconnect behavior for an ioredis-compatible connector. ## Properties | Property | Type | |---|---| | `Connector` | `any` | | `retryStrategy` | `(times: number) => number | void | null` | | `commandTimeout` | `number` | | `keepAlive` | `number` | | `noDelay` | `boolean` | | `connectionName` | `string` | | `clientInfoTag` | `string` | | `username` | `string` | | `password` | `string` | | `db` | `number` | | `autoResubscribe` | `boolean` | | `autoResendUnfulfilledCommands` | `boolean` | | `reconnectOnError` | `((err: Error) => boolean | 1 | 2) | null` | | `readOnly` | `boolean` | | `stringNumbers` | `boolean` | | `connectTimeout` | `number` | | `monitor` | `boolean` | | `maxRetriesPerRequest` | `number | null` | | `maxLoadingRetryTime` | `number` | | `enableAutoPipelining` | `boolean` | | `autoPipeliningIgnoredCommands` | `string[]` | | `offlineQueue` | `boolean` | | `commandQueue` | `boolean` | | `enableOfflineQueue` | `boolean` | | `enableReadyCheck` | `boolean` | | `lazyConnect` | `boolean` | | `scripts` | `Record< string, { lua: string; numberOfKeys?: number; readOnly?: boolean } >` | | `keyPrefix` | `string` | | `showFriendlyErrorStack` | `boolean` | | `disconnectTimeout` | `number` | | `tls` | `ConnectionOptions` | | `name` | `string` | | `role` | `'master' | 'slave'` | | `sentinelUsername` | `string` | | `sentinelPassword` | `string` | | `sentinels` | `Array>` | | `sentinelRetryStrategy` | `(retryAttempts: number) => number | void | null` | | `sentinelReconnectStrategy` | `(retryAttempts: number) => number | void | null` | | `preferredSlaves` | `any` | | `sentinelCommandTimeout` | `number` | | `enableTLSForSentinelMode` | `boolean` | | `sentinelTLS` | `ConnectionOptions` | | `natMap` | `any` | | `updateSentinels` | `boolean` | | `sentinelMaxConnections` | `number` | | `failoverDetector` | `boolean` | ## Diagram ```mermaid graph LR App[Microservice] --> Options[IORedisOptions] Options --> Connector[Connector] Options --> Auth[username / password] Options --> Database[db] Options --> Network[keepAlive / noDelay] Options --> Retry[retryStrategy] Options --> Timeout[commandTimeout] Options --> Identity[connectionName / clientInfoTag] Connector --> Redis[(Redis Server)] ``` ## Usage ```ts import type { IORedisOptions } from './redis.interface'; import Redis from 'ioredis'; const redisOptions: IORedisOptions = { Connector: Redis, host: 'localhost', port: 6379, username: 'default', password: process.env.REDIS_PASSWORD, db: 0, connectionName: 'orders-service', clientInfoTag: 'orders-worker', commandTimeout: 5_000, keepAlive: 10_000, noDelay: true, retryStrategy: (times) => { if (times > 10) { return null; // Stop retrying after 10 attempts. } return Math.min(times * 200, 2_000); }, }; ``` ## AI Coding Instructions - Provide an ioredis-compatible constructor through `Connector`; ensure it supports the configured connection options. - Keep credentials in environment variables or a secrets manager rather than hardcoding `username` or `password`. - Return a delay in milliseconds from `retryStrategy`; return `null` or `void` when reconnect attempts should stop. - Use distinct `connectionName` and `clientInfoTag` values per service to simplify Redis monitoring and debugging. - Configure `commandTimeout`, `keepAlive`, and `noDelay` according to the deployment network and service latency requirements. # KafkaLogger **Kind:** Function **Source:** [`packages/microservices/helpers/kafka-logger.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/kafka-logger.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function KafkaLogger(logger: any) ``` ## Parameters | Name | Type | |---|---| | `logger` | `any` | # KafkaJSServerDoesNotSupportApiKey **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1215) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSNonRetriableError` ## Properties | Property | Type | |---|---| | `apiKey` | `number` | | `apiName` | `string` | # KafkaJSStaleTopicMetadataAssignment **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1206) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `topic` | `string` | | `unknownPartitions` | `number` | # KafkaResponseDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/kafka-response.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/kafka-response.deserializer.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaResponseDeserializer` converts Kafka consumer messages into Nest microservice `IncomingResponse` objects. It extracts the correlation ID and disposal state from Kafka headers while preserving the message value as the response payload, allowing `ClientKafka` to match responses to pending RPC requests. **Implements:** `Deserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `deserialize` | `deserialize(message: any, options: Record)` | `IncomingResponse` | ## Where it refuses work - `KafkaResponseDeserializer` stops the work with an early return when `!isUndefined(message.headers[KafkaHeaders.NEST_ERR])`. - `KafkaResponseDeserializer` stops the work with an early return when `!isUndefined(message.headers[KafkaHeaders.NEST_IS_DISPOSED])`. ## Diagram ```mermaid graph LR A[Kafka consumer message] --> B[KafkaResponseDeserializer.deserialize] B --> C[Read headers] C --> D[Correlation ID] C --> E[Disposed flag] B --> F[Message value] D --> G[IncomingResponse] E --> G F --> G G --> H[ClientKafka RPC response handling] ``` ## Usage ```ts import { KafkaHeaders, KafkaResponseDeserializer, } from '@nestjs/microservices'; const deserializer = new KafkaResponseDeserializer(); const incomingResponse = deserializer.deserialize({ key: 'order.created', value: { orderId: 'order-123', status: 'created', }, headers: { [KafkaHeaders.CORRELATION_ID]: 'request-abc-123', [KafkaHeaders.NEST_IS_DISPOSED]: false, }, }); console.log(incomingResponse); // { // id: 'request-abc-123', // response: { orderId: 'order-123', status: 'created' }, // isDisposed: false // } ``` ## AI Coding Instructions - Preserve the Kafka correlation ID header; it is required for matching a response with the originating RPC request. - Keep the Kafka message `value` as the response payload rather than transforming its shape in this deserializer. - Use `KafkaHeaders.CORRELATION_ID` and `KafkaHeaders.NEST_IS_DISPOSED` instead of hard-coded header names. - Ensure response-producing Kafka consumers include the expected Nest Kafka headers when implementing custom request-response flows. ## Relationships - IMPORTS → `isUndefined` # NatsRecordSerializer **Kind:** Class **Source:** [`packages/microservices/serializers/nats-record.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/nats-record.serializer.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) `NatsRecordSerializer` converts outbound microservice packets into `NatsRecord` instances for NATS transport. It preserves an existing `NatsRecord` when provided and carries packet headers into the serialized record so NATS metadata is sent with the message. **Implements:** `Serializer` ## Methods | Method | Signature | Returns | |---|---|---| | `serialize` | `serialize(packet: any)` | `NatsRecord` | ## Diagram ```mermaid graph LR A[Outbound packet] --> B[NatsRecordSerializer.serialize] B --> C{Packet data is NatsRecord?} C -->|Yes| D[Reuse NatsRecord] C -->|No| E[Build new NatsRecord] D --> F[Apply packet headers] E --> F F --> G[NATS publish/request transport] ``` ## Usage ```ts import { NatsRecordSerializer } from '@nestjs/microservices'; const serializer = new NatsRecordSerializer(); const record = serializer.serialize({ pattern: 'orders.created', data: { orderId: 'order-123', status: 'created', }, headers: { 'x-correlation-id': 'request-456', }, }); // Pass the serialized record to the NATS transport layer. console.log(record.data); console.log(record.headers); ``` ## AI Coding Instructions - Use `NatsRecordSerializer` at the NATS transport boundary to convert outbound packet data into the NATS-specific record format. - Preserve packet headers when constructing or modifying serialization flows; headers commonly carry correlation IDs, tracing context, and routing metadata. - Do not unnecessarily wrap data that is already a `NatsRecord`; the serializer is designed to retain existing records. - Keep application payloads transport-agnostic where possible, and add NATS-specific headers or record configuration only when integrating with the NATS client. ## Relationships - IMPORTS → `loadPackage` - IMPORTS → `isObject` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) **Part of:** [Microservices](subsystem-packages-microservices) `Payload()` decorates a microservice message handler parameter with the incoming message payload. It can receive pipes, such as `ValidationPipe`, to transform or validate the payload before the handler receives it. ## Signature ```ts function Payload(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Message[Incoming microservice message] --> PayloadDecorator["@Payload()"] PayloadDecorator --> Pipes[Parameter pipes] Pipes --> Handler[Message handler parameter] ``` ## Usage ```typescript import { Controller, ValidationPipe } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; class CreateCatDto { name: string; age: number; } @Controller() export class CatsController { @MessagePattern('cats.create') create( @Payload(new ValidationPipe()) createDto: CreateCatDto, ) { return createDto; } } ``` ## AI Coding Instructions - Apply `@Payload()` only to parameters in handlers decorated with microservice pattern decorators such as `@MessagePattern()`. - Pass parameter pipes to `@Payload()` when the incoming payload needs validation or transformation. - Keep the decorated parameter type aligned with the expected message payload shape. - Do not use `@Payload()` to access message metadata; use the relevant microservice context parameter for transport-specific data. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) **Part of:** [Microservices](subsystem-packages-microservices) `Payload()` decorates a microservice message handler parameter with the incoming message payload. It can receive pipes, such as `ValidationPipe`, to transform or validate the payload before the handler receives it. ## Signature ```ts function Payload(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Message[Incoming microservice message] --> PayloadDecorator["@Payload()"] PayloadDecorator --> Pipes[Parameter pipes] Pipes --> Handler[Message handler parameter] ``` ## Usage ```typescript import { Controller, ValidationPipe } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; class CreateCatDto { name: string; age: number; } @Controller() export class CatsController { @MessagePattern('cats.create') create( @Payload(new ValidationPipe()) createDto: CreateCatDto, ) { return createDto; } } ``` ## AI Coding Instructions - Apply `@Payload()` only to parameters in handlers decorated with microservice pattern decorators such as `@MessagePattern()`. - Pass parameter pipes to `@Payload()` when the incoming payload needs validation or transformation. - Keep the decorated parameter type aligned with the expected message payload shape. - Do not use `@Payload()` to access message metadata; use the relevant microservice context parameter for transport-specific data. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) **Part of:** [Microservices](subsystem-packages-microservices) `Payload()` decorates a microservice message handler parameter with the incoming message payload. It can receive pipes, such as `ValidationPipe`, to transform or validate the payload before the handler receives it. ## Signature ```ts function Payload(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Message[Incoming microservice message] --> PayloadDecorator["@Payload()"] PayloadDecorator --> Pipes[Parameter pipes] Pipes --> Handler[Message handler parameter] ``` ## Usage ```typescript import { Controller, ValidationPipe } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; class CreateCatDto { name: string; age: number; } @Controller() export class CatsController { @MessagePattern('cats.create') create( @Payload(new ValidationPipe()) createDto: CreateCatDto, ) { return createDto; } } ``` ## AI Coding Instructions - Apply `@Payload()` only to parameters in handlers decorated with microservice pattern decorators such as `@MessagePattern()`. - Pass parameter pipes to `@Payload()` when the incoming payload needs validation or transformation. - Keep the decorated parameter type aligned with the expected message payload shape. - Do not use `@Payload()` to access message metadata; use the relevant microservice context parameter for transport-specific data. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) **Part of:** [Microservices](subsystem-packages-microservices) `Payload()` decorates a microservice message handler parameter with the incoming message payload. It can receive pipes, such as `ValidationPipe`, to transform or validate the payload before the handler receives it. ## Signature ```ts function Payload(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Message[Incoming microservice message] --> PayloadDecorator["@Payload()"] PayloadDecorator --> Pipes[Parameter pipes] Pipes --> Handler[Message handler parameter] ``` ## Usage ```typescript import { Controller, ValidationPipe } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; class CreateCatDto { name: string; age: number; } @Controller() export class CatsController { @MessagePattern('cats.create') create( @Payload(new ValidationPipe()) createDto: CreateCatDto, ) { return createDto; } } ``` ## AI Coding Instructions - Apply `@Payload()` only to parameters in handlers decorated with microservice pattern decorators such as `@MessagePattern()`. - Pass parameter pipes to `@Payload()` when the incoming payload needs validation or transformation. - Keep the decorated parameter type aligned with the expected message payload shape. - Do not use `@Payload()` to access message metadata; use the relevant microservice context parameter for transport-specific data. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # ServerFactory **Kind:** Class **Source:** [`packages/microservices/server/server-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-factory.ts#L20) **Part of:** [Microservices](subsystem-packages-microservices) `ServerFactory` creates the appropriate NestJS microservice server implementation for a configured transport, such as TCP, Redis, NATS, MQTT, gRPC, or Kafka. It centralizes transport-to-server resolution so the rest of the microservices package can work with a common server interface. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(microserviceOptions: MicroserviceOptions)` | `void` | ## Diagram ```mermaid graph LR A[MicroserviceOptions] --> B[ServerFactory.create()] B --> C{transport} C -->|TCP| D[ServerTCP] C -->|Redis| E[ServerRedis] C -->|NATS| F[ServerNats] C -->|MQTT| G[ServerMqtt] C -->|gRPC| H[ServerGrpc] C -->|Kafka / RMQ| I[Transport-specific Server] D --> J[Microservice Server Interface] E --> J F --> J G --> J H --> J I --> J ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import { ServerFactory } from '@nestjs/microservices/server/server-factory'; const server = ServerFactory.create({ transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001, }, }); server.listen(() => { console.log('TCP microservice server is listening'); }); ``` ## AI Coding Instructions - Pass a valid `MicroserviceOptions` object with the intended `Transport` value and transport-specific options. - Treat the returned value as a common microservice server abstraction; avoid coupling calling code to a specific `Server*` implementation. - Add support for new transports by extending the factory mapping and returning a server implementation compatible with the existing server contract. - Ensure transport options match the selected transport; TCP options, broker credentials, and gRPC package settings are not interchangeable. - Prefer using Nest application factory APIs in application code when possible; use `ServerFactory` directly for framework-level or custom integration scenarios. ## How it works `ServerFactory` is a class with one static method, `create`, that constructs a transport-specific microservice server from a `MicroserviceOptions` configuration. It reads `transport` and `options` from the input after a TypeScript-only exclusion of the `CustomStrategy` union member. [packages/microservices/server/server-factory.ts:20-25](packages/microservices/server/server-factory.ts#L20-L25) `create` selects the constructed class as follows: - `Transport.REDIS` → `ServerRedis` [packages/microservices/server/server-factory.ts:26-28](packages/microservices/server/server-factory.ts#L26-L28) - `Transport.NATS` → `ServerNats` [packages/microservices/server/server-factory.ts:29-30](packages/microservices/server/server-factory.ts#L29-L30) - `Transport.MQTT` → `ServerMqtt` [packages/microservices/server/server-factory.ts:31-32](packages/microservices/server/server-factory.ts#L31-L32) - `Transport.GRPC` → `ServerGrpc` [packages/microservices/server/server-factory.ts:33-34](packages/microservices/server/server-factory.ts#L33-L34) - `Transport.KAFKA` → `ServerKafka` [packages/microservices/server/server-factory.ts:35-36](packages/microservices/server/server-factory.ts#L35-L36) - `Transport.RMQ` → `ServerRMQ` [packages/microservices/server/server-factory.ts:37-38](packages/microservices/server/server-factory.ts#L37-L38) - Any other value, including an omitted `transport`, → `ServerTCP` [packages/microservices/server/server-factory.ts:39-40](packages/microservices/server/server-factory.ts#L39-L40). The repository test asserts that `create({})` returns a `ServerTCP`. [packages/microservices/test/server/server-factory.spec.ts:13-16](packages/microservices/test/server/server-factory.spec.ts#L13-L16) The method passes `options` directly to `ServerGrpc`; for the other constructors, it applies a type assertion to the corresponding transport’s `options` type. These assertions do not perform runtime validation. [packages/microservices/server/server-factory.ts:21-40](packages/microservices/server/server-factory.ts#L21-L40) The factory itself has no input checks, fallback error, or `try`/`catch`; errors thrown while constructing a selected server escape from `create`. [packages/microservices/server/server-factory.ts:21-42](packages/microservices/server/server-factory.ts#L21-L42) Construction can have immediate side effects before a server starts listening. For example, `ServerTCP` initializes its underlying server and serializer/deserializer in its constructor, [packages/microservices/server/server-tcp.ts:49-60](packages/microservices/server/server-tcp.ts#L49-L60) while the Redis, NATS, MQTT, Kafka, RMQ, and gRPC constructors load their respective external packages. [packages/microservices/server/server-redis.ts:42-50](packages/microservices/server/server-redis.ts#L42-L50) [packages/microservices/server/server-nats.ts:50-58](packages/microservices/server/server-nats.ts#L50-L58) [packages/microservices/server/server-mqtt.ts:47-56](packages/microservices/server/server-mqtt.ts#L47-L56) [packages/microservices/server/server-kafka.ts:78-85](packages/microservices/server/server-kafka.ts#L78-L85) [packages/microservices/server/server-rmq.ts:77-95](packages/microservices/server/server-rmq.ts#L77-L95) [packages/microservices/server/server-grpc.ts:70-88](packages/microservices/server/server-grpc.ts#L70-L88) `MicroserviceOptions` also permits `CustomStrategy`, whose shape has `strategy` and optional `options` rather than `transport`. [packages/microservices/interfaces/microservice-configuration.interface.ts:25-33](packages/microservices/interfaces/microservice-configuration.interface.ts#L25-L33) [packages/microservices/interfaces/microservice-configuration.interface.ts:50-53](packages/microservices/interfaces/microservice-configuration.interface.ts#L50-L53) In the visible `NestMicroservice` caller, configurations with `strategy` bypass `ServerFactory.create` and assign that strategy as the server instance. [packages/microservices/nest-microservice.ts:84-109](packages/microservices/nest-microservice.ts#L84-L109) # createPipesRpcParamDecorator **Kind:** Function **Source:** [`packages/microservices/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/utils/param.utils.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function createPipesRpcParamDecorator(paramtype: RpcParamtype) ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `RpcParamtype` | # Ctx **Kind:** Constant **Source:** [`packages/microservices/decorators/ctx.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/ctx.decorator.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createRpcParamDecorator( RpcParamtype.CONTEXT, ) ``` ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 - `RMQFanoutExchangeConsumerController` — `integration/microservices/src/rmq/fanout-exchange-consumer-rmq.controller.ts`:4 - `RMQController` — `integration/microservices/src/rmq/rmq.controller.ts`:16 - `RMQTopicExchangeController` — `integration/microservices/src/rmq/topic-exchange-rmq.controller.ts`:12 # KafkaRequestDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/kafka-request.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/kafka-request.deserializer.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaRequestDeserializer` converts raw Kafka request records into the internal `IncomingRequest` or `IncomingEvent` schema used by the microservices layer. It extracts the Kafka message key as the request pattern and forwards the message value as the payload, allowing downstream handlers to process Kafka messages consistently with other transports. **Extends:** `IncomingRequestDeserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `mapToSchema` | `mapToSchema(data: KafkaRequest, options: Record)` | `IncomingRequest | IncomingEvent` | ## Where it refuses work - `KafkaRequestDeserializer` stops the work with an early return when `!options`. ## Diagram ```mermaid graph LR A[Kafka broker message] --> B[KafkaRequestDeserializer] B --> C{Message has a value?} C -->|Yes| D[IncomingRequest / IncomingEvent] D --> E[pattern: Kafka key] D --> F[data: Kafka value] C -->|No| G[Return original data] ``` ## Usage ```ts import { KafkaRequestDeserializer } from '@nestjs/microservices/deserializers/kafka-request.deserializer'; const deserializer = new KafkaRequestDeserializer(); const kafkaMessage = { key: Buffer.from('orders.create'), value: { orderId: 'order-123', customerId: 'customer-456', }, }; const incomingMessage = deserializer.mapToSchema(kafkaMessage); console.log(incomingMessage); // { // pattern: 'orders.create', // data: { // orderId: 'order-123', // customerId: 'customer-456' // } // } ``` ## AI Coding Instructions - Preserve the Kafka convention: use the message key as the handler pattern and the message value as the payload. - Handle malformed or value-less Kafka records defensively; the deserializer should not assume every input has a `value` property. - Keep output compatible with the shared `IncomingRequest` and `IncomingEvent` contracts used by microservice transport handlers. - When extending Kafka message handling, avoid mutating the original Kafka record or its payload. - Configure this deserializer at the Kafka transport boundary so application handlers receive normalized messages. # MqttClientOptions **Kind:** Interface **Source:** [`packages/microservices/external/mqtt-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/mqtt-options.interface.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `MqttClientOptions` defines connection and protocol settings for an MQTT client used by the microservices transport layer. It supports direct MQTT/TCP connections as well as WebSocket-based MQTT transports, including client identity, keepalive behavior, and WebSocket-specific options. ## Properties | Property | Type | |---|---| | `port` | `number` | | `host` | `string` | | `hostname` | `string` | | `path` | `string` | | `protocol` | `'wss' | 'ws' | 'mqtt' | 'mqtts' | 'tcp' | 'ssl' | 'wx' | 'wxs'` | | `wsOptions` | `{ [x: string]: any; }` | | `keepalive` | `number` | | `clientId` | `string` | | `protocolId` | `string` | | `protocolVersion` | `number` | | `clean` | `boolean` | | `reconnectPeriod` | `number` | | `connectTimeout` | `number` | | `username` | `string` | | `password` | `string` | | `incomingStore` | `any` | | `outgoingStore` | `any` | | `queueQoSZero` | `boolean` | | `properties` | `{ sessionExpiryInterval?: number; receiveMaximum?: number; maximumPacketSize?: number; topicAliasMaximum?: number; requestResponseInformation?: boolean; requestProblemInformation?: boolean; userProperties?: object; authenticationMethod?: string; authenticationData?: any; }` | | `reschedulePings` | `boolean` | | `servers` | `Array<{ host: string; port: number; }>` | | `resubscribe` | `boolean` | | `will` | `{ topic: string; payload: string; qos: QoS; retain: boolean; }` | | `transformWsUrl` | `(url: string, options: any, client: any) => string` | ## Diagram ```mermaid graph LR Client[Microservice MQTT Client] --> Options[MqttClientOptions] Options --> Connection[host / hostname / port / path] Options --> Transport[protocol] Options --> Identity[clientId] Options --> Protocol[protocolId / protocolVersion] Options --> Keepalive[keepalive] Options --> WebSocket[wsOptions] Transport --> MQTT[mqtt / mqtts / tcp / ssl] Transport --> WS[ws / wss / wx / wxs] WebSocket --> WS ``` ## Usage ```ts import type { MqttClientOptions } from './mqtt-options.interface'; const mqttOptions: MqttClientOptions = { host: 'broker.example.com', hostname: 'broker.example.com', port: 8883, path: '/mqtt', protocol: 'mqtts', clientId: 'orders-service', protocolId: 'MQTT', protocolVersion: 4, keepalive: 60, wsOptions: {}, }; // Pass mqttOptions to the MQTT client or microservice transport configuration. ``` ## AI Coding Instructions - Provide a valid `protocol` value that matches the target transport, such as `mqtts` for secure TCP or `wss` for secure WebSockets. - Keep `host`/`hostname`, `port`, and `path` consistent with the MQTT broker endpoint; `path` is especially important for WebSocket connections. - Use a stable, unique `clientId` per running service instance to avoid broker-side client session conflicts. - Set `protocolId` and `protocolVersion` to values supported by the broker; common MQTT settings are `MQTT` and version `4`. - Only populate `wsOptions` when using a WebSocket-based protocol and pass broker-required headers, TLS options, or proxy configuration there. ## How it works `MqttClientOptions` is a TypeScript interface that describes MQTT connection options. It extends `ISecureClientOptions`, so its shape includes optional TLS key, certificate, CA, and `rejectUnauthorized` fields. [mqtt-options.interface.ts:8](packages/microservices/external/mqtt-options.interface.ts#L8) [mqtt-options.interface.ts:136-150](packages/microservices/external/mqtt-options.interface.ts#L136-L150) All of its fields are optional. The declaration itself contains no runtime validation, defaults assignment, error throwing, or side effects. [mqtt-options.interface.ts:8-135](packages/microservices/external/mqtt-options.interface.ts#L8-L135) # NatsRequestJSONDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/nats-request-json.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/nats-request-json.deserializer.ts#L11) **Part of:** [Microservices](subsystem-packages-microservices) `NatsRequestJSONDeserializer` converts raw NATS request messages into Nest microservice `IncomingRequest` or `IncomingEvent` objects. It parses the JSON payload, reads the correlation ID from NATS headers, and attaches a response function backed by the original NATS message. **Extends:** `IncomingRequestDeserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `deserialize` | `deserialize(value: Uint8Array, options: Record)` | `IncomingRequest | IncomingEvent` | ## Diagram ```mermaid graph LR A[NATS message] --> B[NatsRequestJSONDeserializer.deserialize] B --> C[Parse JSON payload] B --> D[Read correlation ID header] B --> E[Bind message.respond] C --> F[IncomingRequest or IncomingEvent] D --> F E --> F ``` ## Usage ```ts import { NatsRequestJSONDeserializer } from '@nestjs/microservices'; const deserializer = new NatsRequestJSONDeserializer(); const natsMessage = { data: Buffer.from( JSON.stringify({ pattern: 'users.findOne', data: { id: '42' }, }), ), headers: { get: (key: string) => key === 'Nats-Correlation-Id' ? 'request-123' : undefined, }, respond: (payload: Uint8Array) => { // Send a response through NATS }, }; const request = deserializer.deserialize(natsMessage); console.log(request.pattern); // "users.findOne" console.log(request.data); // { id: "42" } console.log(request.id); // "request-123" ``` ## AI Coding Instructions - Preserve the expected NATS message shape: payload data, optional headers, and a `respond` function. - Keep payloads JSON-serializable because `deserialize()` parses the message body as JSON. - Do not remove the bound `response` function; request-response handlers depend on it to publish replies. - Ensure clients include the NATS correlation ID header when request identity or response matching is required. - Treat the deserialized result as either an `IncomingRequest` or `IncomingEvent`, depending on the payload shape and transport flow. ## Relationships - IMPORTS → `loadPackage` # NatsResponseJSONDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/nats-response-json.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/nats-response-json.deserializer.ts#L12) **Part of:** [Microservices](subsystem-packages-microservices) `NatsResponseJSONDeserializer` converts NATS response records containing JSON payloads into the framework’s normalized `IncomingResponse` format. It extracts response metadata such as the correlation ID and disposal status so request-response clients can match replies to the originating request. **Extends:** `IncomingResponseDeserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `deserialize` | `deserialize(value: Uint8Array, options: Record)` | `IncomingResponse` | ## Diagram ```mermaid graph LR A[NATS response record] --> B[NatsResponseJSONDeserializer] B --> C[Decode JSON response payload] B --> D[Read correlation and disposal headers] C --> E[IncomingResponse] D --> E E --> F[Client request-response handler] ``` ## Usage ```ts import { NatsResponseJSONDeserializer } from '@nestjs/microservices'; const deserializer = new NatsResponseJSONDeserializer(); // `natsResponse` is the record received from a NATS reply subscription. const incomingResponse = deserializer.deserialize(natsResponse); console.log(incomingResponse.id); // Correlation ID for the request console.log(incomingResponse.response); // Decoded JSON payload console.log(incomingResponse.isDisposed); // Whether the response stream ended ``` ## AI Coding Instructions - Use this deserializer for NATS request-response replies that contain JSON-encoded payloads. - Preserve NATS response headers when creating or forwarding records; correlation and disposal metadata are required for correct request matching. - Ensure response payloads are valid JSON before publishing them to NATS. - Do not use this deserializer for arbitrary binary payloads; provide a custom deserializer when responses use another encoding. - Keep the returned `IncomingResponse` shape compatible with the microservices client response-handling pipeline. ## Relationships - IMPORTS → `loadPackage` # RmqRecordSerializer **Kind:** Class **Source:** [`packages/microservices/serializers/rmq-record.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/rmq-record.serializer.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) `RmqRecordSerializer` converts outgoing NestJS microservice packets into RabbitMQ-compatible record payloads. It preserves the request packet shape while extracting or merging RabbitMQ-specific metadata, such as headers and message properties, for transport delivery. **Implements:** `Serializer` ## Methods | Method | Signature | Returns | |---|---|---| | `serialize` | `serialize(packet: ReadPacket)` | `ReadPacket & Partial` | ## Diagram ```mermaid graph LR A[Application Message] --> B[RmqRecordSerializer] B --> C[ReadPacket] B --> D[Partial RmqRecord] C --> E[RabbitMQ Transport] D --> E ``` ## Usage ```ts import { RmqRecordSerializer } from '@nestjs/microservices'; const serializer = new RmqRecordSerializer(); const packet = serializer.serialize({ pattern: 'orders.created', data: { orderId: 'order_123', customerId: 'customer_456', }, }); client.send('orders.created', packet.data); ``` ## AI Coding Instructions - Use `RmqRecordSerializer` at the RabbitMQ transport boundary when outgoing packets may include RabbitMQ record metadata. - Preserve the standard NestJS `ReadPacket` fields, especially `pattern` and `data`, when extending serialization behavior. - Ensure RabbitMQ-specific options, such as headers or properties, are carried through without mutating the original payload. - Keep custom serializers compatible with the `serialize(): ReadPacket & Partial` return contract. - Test serialization with both plain message payloads and `RmqRecord`-style payloads containing transport metadata. ## How it works - `RmqRecordSerializer` is an exported serializer class implementing `Serializer>`. Its `serialize` method accepts a packet with `pattern` and `data` fields. [rmq-record.serializer.ts:6-10](packages/microservices/serializers/rmq-record.serializer.ts#L6-L10) [packet.interface.ts:5-8](packages/microservices/interfaces/packet.interface.ts#L5-L8) [serializer.interface.ts:10-12](packages/microservices/interfaces/serializer.interface.ts#L10-L12) - It recognizes a packet only when `packet.data` is truthy, is a non-null JavaScript object, and is an actual `RmqRecord` instance according to `instanceof`. [rmq-record.serializer.ts:11-15](packages/microservices/serializers/rmq-record.serializer.ts#L11-L15) [`isObject` checks non-null values whose `typeof` is `object`.](packages/common/utils/shared.utils.ts#L4-L5) - For such a packet, `serialize` returns a **new** packet object: it copies the packet’s existing enumerable properties, replaces `data` with `RmqRecord.data`, and writes `RmqRecord.options` to a top-level `options` field. [rmq-record.serializer.ts:16-21](packages/microservices/serializers/rmq-record.serializer.ts#L16-L21) `RmqRecord` stores its payload in readonly `data` and can store optional `options`. [rmq.record-builder.ts:25-29](packages/microservices/record-builders/rmq.record-builder.ts#L25-L29) - If the payload does not meet that runtime check—including plain objects that merely resemble a record—the method returns the original packet reference unchanged. [rmq-record.serializer.ts:22-23](packages/microservices/serializers/rmq-record.serializer.ts#L22-L23) The serializer test checks reference identity for a non-`RmqRecord` payload. [rmq-record.serializer.spec.ts:31-37](packages/microservices/test/serializers/rmq-record.serializer.spec.ts#L31-L37) - The method has no explicit error handling or thrown validation error in its implementation. [rmq-record.serializer.ts:10-24](packages/microservices/serializers/rmq-record.serializer.ts#L10-L24) It does not modify the input itself when it unwraps an `RmqRecord`; that branch constructs and returns an object literal. [rmq-record.serializer.ts:16-21](packages/microservices/serializers/rmq-record.serializer.ts#L16-L21) - `ClientRMQ` and `ServerRMQ` select this class as their serializer when transport options do not specify a custom serializer. [client-rmq.ts:488-490](packages/microservices/client/client-rmq.ts#L488-L490) [server-rmq.ts:424-426](packages/microservices/server/server-rmq.ts#L424-L426) - In the RMQ client send and event paths, the serialized packet’s top-level `options` is read and then deleted before the remaining packet is JSON-encoded; those options are spread into RabbitMQ send options, with headers merged separately. [client-rmq.ts:393-412](packages/microservices/client/client-rmq.ts#L393-L412) [client-rmq.ts:446-484](packages/microservices/client/client-rmq.ts#L446-L484) Therefore, when this serializer returns the input unchanged, that later deletion operates on the caller’s packet object. [rmq-record.serializer.ts:22-23](packages/microservices/serializers/rmq-record.serializer.ts#L22-L23) [client-rmq.ts:447-451](packages/microservices/client/client-rmq.ts#L447-L451) ## Relationships - IMPORTS → `isObject` # RpcParamsFactory **Kind:** Class **Source:** [`packages/microservices/factories/rpc-params-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/factories/rpc-params-factory.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) `RpcParamsFactory` resolves RPC handler parameter values from the arguments supplied by a microservice transport. Its `exchangeKeyForValue()` method maps an RPC parameter type—such as payload or context—to the appropriate value, including selecting a named property from the payload. ## Methods | Method | Signature | Returns | |---|---|---| | `exchangeKeyForValue` | `exchangeKeyForValue(type: number, data: string | undefined, args: unknown[])` | `void` | ## Where it refuses work - `RpcParamsFactory` stops the work with an early return when `!args`. ## Diagram ```mermaid graph LR A[Transport invokes RPC handler] --> B[Handler arguments array] B --> C[RpcParamsFactory.exchangeKeyForValue] C --> D{RPC parameter type} D -->|PAYLOAD| E[Full payload or payload property] D -->|CONTEXT| F[Transport context] D -->|Unknown type| G[null] ``` ## Usage ```ts import { RpcParamsFactory } from '@nestjs/microservices/factories/rpc-params-factory'; import { RpcParamtype } from '@nestjs/microservices/enums/rpc-paramtype.enum'; const paramsFactory = new RpcParamsFactory(); const payload = { id: 'user-123', action: 'created' }; const context = { pattern: 'users.create' }; const args = [payload, context]; // Resolve the complete message payload. const message = paramsFactory.exchangeKeyForValue( RpcParamtype.PAYLOAD, undefined, args, ); // Resolve a property from the message payload. const userId = paramsFactory.exchangeKeyForValue( RpcParamtype.PAYLOAD, 'id', args, ); // Resolve the RPC transport context. const rpcContext = paramsFactory.exchangeKeyForValue( RpcParamtype.CONTEXT, undefined, args, ); ``` ## AI Coding Instructions - Pass handler arguments in their expected order: payload at index `0` and RPC context at index `1`. - Use `RpcParamtype.PAYLOAD` with a property key to extract a specific payload field; omit the key to return the full payload. - Use `RpcParamtype.CONTEXT` only when the transport provides context as the second handler argument. - Preserve the `null` fallback for unsupported parameter types or missing argument arrays so parameter resolution fails safely. ## How it works `RpcParamsFactory` is a class with one method, `exchangeKeyForValue(type, data, args)`, that selects an RPC handler parameter value from an invocation-argument array. Its parameters are a numeric type, optional string data, and `unknown[]` arguments. [packages/microservices/factories/rpc-params-factory.ts:3-8] - For `RpcParamtype.PAYLOAD`, it returns `args[0]` when `data` is falsy; when `data` is truthy, it returns the property named by `data` from `args[0]`. Optional chaining means a missing or nullish first argument yields `undefined` for property extraction. [packages/microservices/factories/rpc-params-factory.ts:12-15] - For `RpcParamtype.CONTEXT`, it returns `args[1]`; `data` is ignored. [packages/microservices/factories/rpc-params-factory.ts:12-17] - For `RpcParamtype.GRPC_CALL`, it returns `args[2]`; `data` is ignored. [packages/microservices/factories/rpc-params-factory.ts:12-19] - The enum defines these three kinds as `PAYLOAD`, `CONTEXT`, and `GRPC_CALL`. [packages/microservices/enums/rpc-paramtype.enum.ts:3-7] - If `args` is falsy, or if `type` does not match one of those enum values, the method returns `null`. [packages/microservices/factories/rpc-params-factory.ts:9-11] [packages/microservices/factories/rpc-params-factory.ts:19-20] - It does not check whether the selected array slot or requested payload property exists. Thus, with a truthy `args` array, missing slots or properties can result in `undefined`. [packages/microservices/factories/rpc-params-factory.ts:14-18] - The method only reads from `args` and does not write to it or other state. [packages/microservices/factories/rpc-params-factory.ts:9-21] `RpcContextCreator` owns an instance of this class and creates extraction callbacks that pass the callback’s received arguments into `exchangeKeyForValue`. [packages/microservices/context/rpc-context-creator.ts:41-45] [packages/microservices/context/rpc-context-creator.ts:237-241] The default non-gRPC metadata maps the payload parameter to argument slot `0`; the gRPC defaults additionally map context and gRPC call parameters to slots `1` and `2`. [packages/microservices/context/rpc-metadata-constants.ts:3-10] # Admin **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L502) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { connect(): Promise; disconnect(): Promise; listTopics(): Promise; createTopics(options: { validateOnly?: boolean; waitForLeaders?: boolean; timeout?: number; topics: ITopicConfig[]; }): Promise; deleteTopics(options: { topics: string[]; timeout?: number }): Promise; createPartitions(options: { validateOnly?: boolean; timeout?: number; topicPartitions: ITopicPartitionConfig[]; }): Promise; fetchTopicMetadata(options?: { topics: string[]; }): Promise<{ topics: Array }>; fetchOffsets(options: { groupId: string; topics?: string[]; resolveOffsets?: boolean; }): Promise>; fetchTopicOffsets( topic: string, ): Promise>; fetchTopicOffsetsByTimestamp( topic: string, timestamp?: number, ): Promise>; describeCluster(): Promise<{ brokers: Array<{ nodeId: number; host: string; port: number }>; controller: number | null; clusterId: string; }>; setOffsets(options: { groupId: string; topic: string; partitions: SeekEntry[]; }): Promise; resetOffsets(options: { groupId: string; topic: string; earliest: boolean; }): Promise; describeConfigs(configs: { resources: ResourceConfigQuery[]; includeSynonyms: boolean; }): Promise; alterConfigs(configs: { validateOnly: boolean; resources: IResourceConfig[]; }): Promise; listGroups(): Promise<{ groups: GroupOverview[] }>; deleteGroups(groupIds: string[]): Promise; describeGroups(groupIds: string[]): Promise; describeAcls(options: AclFilter): Promise; deleteAcls(options: { filters: AclFilter[] }): Promise; createAcls(options: { acl: AclEntry[] }): Promise; deleteTopicRecords(options: { topic: string; partitions: SeekEntry[]; }): Promise; logger(): Logger; on( eventName: AdminEvents['CONNECT'], listener: (event: ConnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: AdminEvents['DISCONNECT'], listener: (event: DisconnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: AdminEvents['REQUEST'], listener: (event: RequestEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: AdminEvents['REQUEST_QUEUE_SIZE'], listener: (event: RequestQueueSizeEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: AdminEvents['REQUEST_TIMEOUT'], listener: (event: RequestTimeoutEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ValueOf, listener: (event: InstrumentationEvent) => void, ): RemoveInstrumentationEventListener; readonly events: AdminEvents; } ``` # Consumer **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1043) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { connect(): Promise; disconnect(): Promise; subscribe(subscription: ConsumerSubscribeTopics): Promise; stop(): Promise; run(config?: ConsumerRunConfig): Promise; commitOffsets( topicPartitions: Array, ): Promise; seek(topicPartitionOffset: TopicPartitionOffset): void; describeGroup(): Promise; pause(topics: Array<{ topic: string; partitions?: number[] }>): void; paused(): TopicPartitions[]; resume(topics: Array<{ topic: string; partitions?: number[] }>): void; on( eventName: ConsumerEvents['HEARTBEAT'], listener: (event: ConsumerHeartbeatEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['COMMIT_OFFSETS'], listener: (event: ConsumerCommitOffsetsEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['GROUP_JOIN'], listener: (event: ConsumerGroupJoinEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['FETCH_START'], listener: (event: ConsumerFetchStartEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['FETCH'], listener: (event: ConsumerFetchEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['START_BATCH_PROCESS'], listener: (event: ConsumerStartBatchProcessEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['END_BATCH_PROCESS'], listener: (event: ConsumerEndBatchProcessEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['CONNECT'], listener: (event: ConnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['DISCONNECT'], listener: (event: DisconnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['STOP'], listener: (event: InstrumentationEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['CRASH'], listener: (event: ConsumerCrashEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['REBALANCING'], listener: (event: ConsumerRebalancingEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['RECEIVED_UNSUBSCRIBED_TOPICS'], listener: (event: ConsumerReceivedUnsubscribedTopicsEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['REQUEST'], listener: (event: RequestEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['REQUEST_TIMEOUT'], listener: (event: RequestTimeoutEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ConsumerEvents['REQUEST_QUEUE_SIZE'], listener: (event: RequestQueueSizeEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ValueOf, listener: (event: InstrumentationEvent) => void, ): RemoveInstrumentationEventListener; logger(): Logger; readonly events: ConsumerEvents; } ``` # createRpcParamDecorator **Kind:** Function **Source:** [`packages/microservices/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/utils/param.utils.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function createRpcParamDecorator(paramtype: RpcParamtype): (...pipes: (Type | PipeTransform)[]) => ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `RpcParamtype` | **Returns:** `(...pipes: (Type | PipeTransform)[]) => ParameterDecorator` ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` - IMPORTS → `assignMetadata` - IMPORTS → `isNil` - IMPORTS → `isString` # GrpcOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L58) **Part of:** [Microservices](subsystem-packages-microservices) `GrpcOptions` configures a NestJS microservice that uses the `Transport.GRPC` transport. It defines how protobuf packages are loaded, how the gRPC server listens for requests, and optional channel, message-size, keepalive, credential, and shutdown behavior. ## Properties | Property | Type | |---|---| | `transport` | `Transport.GRPC` | | `options` | `{ url?: string; maxSendMessageLength?: number; maxReceiveMessageLength?: number; maxMetadataSize?: number; keepalive?: { keepaliveTimeMs?: number; keepaliveTimeoutMs?: number; keepalivePermitWithoutCalls?: number; http2MaxPingsWithoutData?: number; http2MinTimeBetweenPingsMs?: number; http2MinPingIntervalWithoutDataMs?: number; http2MaxPingStrikes?: number; }; channelOptions?: ChannelOptions; credentials?: any; protoPath?: string | string[]; package: string | string[]; protoLoader?: string; packageDefinition?: any; gracefulShutdown?: boolean; onLoadPackageDefinition?: (pkg: any, server: any) => void; loader?: { keepCase?: boolean; alternateCommentMode?: boolean; longs?: Function; enums?: Function; bytes?: Function; defaults?: boolean; arrays?: boolean; objects?: boolean; oneofs?: boolean; json?: boolean; includeDirs?: string[]; }; }` | ## Diagram ```mermaid graph LR App[Nest Microservice] --> Config[GrpcOptions] Config --> Transport[Transport.GRPC] Config --> Endpoint[url] Config --> Proto[protoPath] Config --> Package[package] Config --> Loader[loader / protoLoader] Config --> Runtime[channelOptions & credentials] Config --> Connection[keepalive settings] Config --> Lifecycle[gracefulShutdown & onLoadPackageDefinition] Proto --> Service[gRPC Service Definitions] Package --> Service ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { Transport, type MicroserviceOptions } from '@nestjs/microservices'; import { AppModule } from './app.module'; import { join } from 'path'; async function bootstrap() { const app = await NestFactory.createMicroservice( AppModule, { transport: Transport.GRPC, options: { url: '0.0.0.0:50051', protoPath: join(__dirname, 'proto', 'users.proto'), package: 'users', loader: { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, }, maxSendMessageLength: 4 * 1024 * 1024, maxReceiveMessageLength: 4 * 1024 * 1024, keepalive: { keepaliveTimeMs: 30_000, keepaliveTimeoutMs: 10_000, keepalivePermitWithoutCalls: true, }, gracefulShutdown: true, }, }, ); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Always set `transport: Transport.GRPC`; this interface is only valid for gRPC microservice configurations. - Provide both `protoPath` and `package`; use arrays when loading multiple protobuf files or packages. - Use `loader` options consistently between gRPC clients and servers, especially `keepCase`, `longs`, `enums`, and `defaults`. - Configure `maxSendMessageLength` and `maxReceiveMessageLength` when services exchange large payloads; verify limits match connected clients. - Enable `gracefulShutdown` for production services and use `onLoadPackageDefinition` only when custom access to the loaded package definition is required. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `grpcClientOptions` — `sample/04-grpc/src/grpc-client.options.ts`:5 # KafkaJSOffsetOutOfRange **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1164) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSProtocolError` ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partition` | `number` | # KafkaJSProtocolError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1158) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `code` | `number` | | `type` | `string` | # RmqOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L222) **Part of:** [Microservices](subsystem-packages-microservices) `RmqOptions` configures a NestJS microservice that uses the RabbitMQ (`Transport.RMQ`) transport. It defines connection URLs, queue and exchange behavior, consumer acknowledgement settings, message serialization, routing, and connection retry behavior. ## Properties | Property | Type | |---|---| | `transport` | `Transport.RMQ` | | `options` | `{ urls?: string[] | RmqUrl[]; queue?: string; prefetchCount?: number; isGlobalPrefetchCount?: boolean; queueOptions?: AmqplibQueueOptions; socketOptions?: AmqpConnectionManagerSocketOptions; noAck?: boolean; consumerTag?: string; serializer?: Serializer; deserializer?: Deserializer; replyQueue?: string; persistent?: boolean; headers?: Record; noAssert?: boolean; exchange?: string; exchangeType?: 'direct' | 'fanout' | 'topic' | 'headers' | (string & {}); exchangeArguments?: Record; routingKey?: string; wildcards?: boolean; maxConnectionAttempts?: number; }` | ## Diagram ```mermaid graph LR App[NestJS Application] --> Config[RmqOptions] Config --> Transport[Transport.RMQ] Config --> Connection[AMQP Connection URLs] Config --> Queue[Queue Configuration] Config --> Exchange[Exchange and Routing] Config --> Consumer[Consumer Settings] Config --> Serialization[Serializer / Deserializer] Connection --> RabbitMQ[RabbitMQ Broker] Queue --> RabbitMQ Exchange --> RabbitMQ Consumer --> RabbitMQ ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { Transport, RmqOptions } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const rmqOptions: RmqOptions = { transport: Transport.RMQ, options: { urls: ['amqp://guest:guest@localhost:5672'], queue: 'orders', queueOptions: { durable: true, }, prefetchCount: 10, noAck: false, persistent: true, exchange: 'events', exchangeType: 'topic', routingKey: 'orders.created', maxConnectionAttempts: 5, }, }; const app = await NestFactory.createMicroservice(AppModule, rmqOptions); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Always set `transport: Transport.RMQ`; this interface is specifically for RabbitMQ microservice configuration. - Configure a durable `queue` and `queueOptions.durable: true` when messages must survive broker restarts. - Set `noAck: false` for reliable processing, then explicitly acknowledge messages in handlers after successful work. - Use `exchange`, `exchangeType`, and `routingKey` together when implementing publish/subscribe or topic-based routing. - Provide custom `serializer` and `deserializer` only when all producers and consumers agree on the message format. # RQM_NO_EVENT_HANDLER **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L43) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function RQM_NO_EVENT_HANDLER(text: TemplateStringsArray, pattern: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `pattern` | `string` | # RQM_NO_MESSAGE_HANDLER **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L48) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function RQM_NO_MESSAGE_HANDLER(text: TemplateStringsArray, pattern: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `pattern` | `string` | # MqttRecordSerializer **Kind:** Class **Source:** [`packages/microservices/serializers/mqtt-record.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/mqtt-record.serializer.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) `MqttRecordSerializer` converts an `MqttRecord` into a JSON string suitable for MQTT transport. It preserves MQTT publish options such as `qos`, `retain`, and `dup`, while serializing object payloads into the record's `data` field. **Implements:** `Serializer` ## Methods | Method | Signature | Returns | |---|---|---| | `serialize` | `serialize(packet: ReadPacket)` | `string` | ## Diagram ```mermaid graph LR A[MqttRecord] --> B[MqttRecordSerializer.serialize] B --> C[Serialize object data when needed] C --> D[Merge MQTT publish options] D --> E[JSON string payload] E --> F[MQTT transport] ``` ## Usage ```ts import { MqttRecord } from '@nestjs/microservices'; import { MqttRecordSerializer } from '@nestjs/microservices/serializers/mqtt-record.serializer'; const record = new MqttRecord( { deviceId: 'sensor-42', temperature: 21.5 }, { qos: 1, retain: true, }, ); const serializer = new MqttRecordSerializer(); const payload = serializer.serialize(record); console.log(payload); // {"data":"{\"deviceId\":\"sensor-42\",\"temperature\":21.5}","qos":1,"retain":true} ``` ## AI Coding Instructions - Pass an `MqttRecord` containing both the message payload (`data`) and MQTT-specific publish options. - Object payloads are JSON-stringified before being embedded in the final serialized message; avoid passing circular object structures. - Keep MQTT options compatible with the underlying MQTT client, including fields such as `qos`, `retain`, and `dup`. - Use this serializer at the MQTT transport boundary; application handlers should typically work with deserialized message data instead of the serialized string. ## Relationships - IMPORTS → `isObject` # RedisContext **Kind:** Class **Source:** [`packages/microservices/ctx-host/redis.context.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/ctx-host/redis.context.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) `RedisContext` provides Redis-specific metadata to microservice message handlers. It wraps the incoming Redis message context and exposes the channel name through `getChannel()`, allowing handlers to identify the source channel. **Extends:** `BaseRpcContext` ## Methods | Method | Signature | Returns | |---|---|---| | `getChannel` | `getChannel()` | `void` | ## Diagram ```mermaid graph LR Redis[Redis Pub/Sub Channel] --> Server[Redis Transport Server] Server --> Context[RedisContext] Context --> Handler[Message Handler] Handler --> Channel[getChannel()] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, MessagePattern, RedisContext } from '@nestjs/microservices'; @Controller() export class NotificationsController { @MessagePattern('notifications.*') handleNotification( payload: { message: string }, @Ctx() context: RedisContext, ) { const channel = context.getChannel(); console.log(`Received "${payload.message}" from ${channel}`); return { received: true, channel }; } } ``` ## AI Coding Instructions - Use `RedisContext` only in handlers executed through the Redis microservice transport. - Retrieve the originating Redis channel with `context.getChannel()` rather than relying on a hard-coded channel name. - Inject the context with `@Ctx()` alongside payload parameters in `@MessagePattern()` handlers. - Treat the channel value as transport metadata; keep business logic independent of Redis-specific context where possible. ## How it works `RedisContext` is an exported RPC context class for Redis message handling. It extends `BaseRpcContext` with a one-element argument tuple whose item is a `string`. [redis.context.ts:3-10](packages/microservices/ctx-host/redis.context.ts#L3-L10) - **Construction:** `new RedisContext(args)` accepts the `[string]` tuple and passes that same tuple to the base-class constructor, which stores it as protected, read-only `args`. [redis.context.ts:3-10](packages/microservices/ctx-host/redis.context.ts#L3-L10) [base-rpc.context.ts:4-5](packages/microservices/ctx-host/base-rpc.context.ts#L4-L5) - **`getChannel()`** returns the tuple’s first item (`args[0]`); the class documentation identifies this value as the channel name. [redis.context.ts:13-18](packages/microservices/ctx-host/redis.context.ts#L13-L18) - **Inherited accessors:** `getArgs()` returns the stored tuple, and `getArgByIndex(index)` returns the item at the requested index. [base-rpc.context.ts:7-20](packages/microservices/ctx-host/base-rpc.context.ts#L7-L20) - **Server construction:** `ServerRedis` creates this context as `new RedisContext([pattern])` while handling an incoming message. Without wildcard mode, it passes the received `channel` as `pattern`; with wildcard mode, it passes the callback’s `pattern` argument. [server-redis.ts:126-142](packages/microservices/server/server-redis.ts#L126-L142) The resulting context is passed to event handling, request handlers, and processing hooks. [server-redis.ts:144-172](packages/microservices/server/server-redis.ts#L144-L172) - **Validation, errors, and side effects:** Neither the constructor nor `getChannel()` performs runtime validation, throws an error, or mutates external state in the visible code; they store and read the argument tuple. [redis.context.ts:8-18](packages/microservices/ctx-host/redis.context.ts#L8-L18) [base-rpc.context.ts:4-5](packages/microservices/ctx-host/base-rpc.context.ts#L4-L5) # Broker **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L667) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { isConnected(): boolean; connect(): Promise; disconnect(): Promise; apiVersions(): Promise; metadata(topics: string[]): Promise; describeGroups: (options: { groupIds: string[] }) => Promise; offsetCommit(request: { groupId: string; groupGenerationId: number; memberId: string; retentionTime?: number; topics: TopicOffsets[]; }): Promise; offsetFetch(request: { groupId: string; topics: TopicOffsets[] }): Promise<{ responses: TopicOffsets[]; }>; fetch(request: { replicaId?: number; isolationLevel?: number; maxWaitTime?: number; minBytes?: number; maxBytes?: number; topics: Array<{ topic: string; partitions: Array<{ partition: number; fetchOffset: string; maxBytes: number; }>; }>; rackId?: string; }): Promise; produce(request: { topicData: Array<{ topic: string; partitions: Array<{ partition: number; firstSequence?: number; messages: Message[]; }>; }>; transactionalId?: string; producerId?: number; producerEpoch?: number; acks?: number; timeout?: number; compression?: CompressionTypes; }): Promise; } ``` # KafkaHeaders **Kind:** Enum **Source:** [`packages/microservices/enums/kafka-headers.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/enums/kafka-headers.enum.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `ACKNOWLEDGMENT` - `BATCH_CONVERTED_HEADERS` - `CONSUMER` - `CORRELATION_ID` - `DELIVERY_ATTEMPT` - `DLT_EXCEPTION_FQCN` - `DLT_EXCEPTION_MESSAGE` - `DLT_EXCEPTION_STACKTRACE` - `DLT_ORIGINAL_OFFSET` - `DLT_ORIGINAL_PARTITION` - `DLT_ORIGINAL_TIMESTAMP` - `DLT_ORIGINAL_TIMESTAMP_TYPE` - `DLT_ORIGINAL_TOPIC` - `GROUP_ID` - `MESSAGE_KEY` - `NATIVE_HEADERS` - `OFFSET` - `PARTITION_ID` - `PREFIX` - `RAW_DATA` - `RECEIVED` - `RECEIVED_MESSAGE_KEY` - `RECEIVED_PARTITION_ID` - `RECEIVED_TIMESTAMP` - `RECEIVED_TOPIC` - `RECORD_METADATA` - `REPLY_PARTITION` - `REPLY_TOPIC` - `TIMESTAMP` - `TIMESTAMP_TYPE` - `TOPIC` - `NEST_ERR` - `NEST_IS_DISPOSED` # KafkaJSTopicMetadataNotLoaded **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1198) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSMetadataNotLoaded` ## Properties | Property | Type | |---|---| | `topic` | `string` | # NatsOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L173) **Part of:** [Microservices](subsystem-packages-microservices) `NatsOptions` defines the configuration required to run a NestJS microservice using the `Transport.NATS` transport. It combines Nest-specific settings such as serializers, deserializers, and queue groups with NATS client connection, authentication, reconnection, TLS, and request behavior options. ## Properties | Property | Type | |---|---| | `transport` | `Transport.NATS` | | `options` | `{ headers?: Record; authenticator?: any; debug?: boolean; ignoreClusterUpdates?: boolean; inboxPrefix?: string; encoding?: string; name?: string; user?: string; pass?: string; maxPingOut?: number; maxReconnectAttempts?: number; reconnectTimeWait?: number; reconnectJitter?: number; reconnectJitterTLS?: number; reconnectDelayHandler?: any; servers?: string[] | string; nkey?: any; reconnect?: boolean; pedantic?: boolean; tls?: any; queue?: string; serializer?: Serializer; deserializer?: Deserializer; userJWT?: string; nonceSigner?: any; userCreds?: any; useOldRequestStyle?: boolean; pingInterval?: number; preserveBuffers?: boolean; waitOnFirstConnect?: boolean; verbose?: boolean; noEcho?: boolean; noRandomize?: boolean; timeout?: number; token?: string; yieldTime?: number; tokenHandler?: any; gracefulShutdown?: boolean; gracePeriod?: number; [key: string]: any; }` | ## Diagram ```mermaid graph LR App[Nest Application] --> Config[NatsOptions] Config --> Transport[Transport.NATS] Config --> Connection[NATS Connection Settings] Config --> Auth[Authentication / TLS] Config --> Reconnect[Reconnect & Ping Settings] Config --> Messaging[Queue, Headers, Request Settings] Config --> Serialization[Serializer / Deserializer] Connection --> NATS[NATS Server or Cluster] Auth --> NATS Reconnect --> NATS Messaging --> NATS Serialization --> NATS ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { Transport, type NatsOptions } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const natsOptions: NatsOptions = { transport: Transport.NATS, options: { servers: ['nats://localhost:4222'], queue: 'orders-service', name: 'orders-microservice', user: process.env.NATS_USER, pass: process.env.NATS_PASSWORD, reconnect: true, maxReconnectAttempts: 10, reconnectTimeWait: 1_000, pingInterval: 30_000, headers: { 'x-service-name': 'orders-service', }, }, }; const app = await NestFactory.createMicroservice(AppModule, natsOptions); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Always set `transport: Transport.NATS`; place NATS client and Nest transport configuration inside `options`. - Configure `servers` with one or more NATS endpoints, especially when connecting to a clustered deployment. - Use environment variables or secret management for credentials, tokens, JWTs, NKeys, and TLS configuration; do not hardcode sensitive values. - Set a stable `queue` when multiple service instances should share subscriptions through a NATS queue group. - Configure `serializer` and `deserializer` consistently across communicating services when using custom message formats. ## How it works `NatsOptions` is a public TypeScript configuration interface for selecting the NATS microservice transport. It is one member of the `MicroserviceOptions` union, and its optional `transport` property is restricted to `Transport.NATS`. [packages/microservices/interfaces/microservice-configuration.interface.ts:25-33](packages/microservices/interfaces/microservice-configuration.interface.ts#L25-L33) [packages/microservices/interfaces/microservice-configuration.interface.ts:170-175](packages/microservices/interfaces/microservice-configuration.interface.ts#L170-L175) `Transport.NATS` is the NATS enum member. [packages/microservices/enums/transport.enum.ts:1-9](packages/microservices/enums/transport.enum.ts#L1-L9) All declared configuration is optional: both `transport` and the nested `options` object may be omitted. [packages/microservices/interfaces/microservice-configuration.interface.ts:173-216](packages/microservices/interfaces/microservice-configuration.interface.ts#L173-L216) When a client is created through `ClientProxyFactory` with `Transport.NATS`, the factory substitutes `{}` when its top-level `options` is absent and constructs `ClientNats`. [packages/microservices/client/client-proxy-factory.ts:48-57](packages/microservices/client/client-proxy-factory.ts#L48-L57) ## Connection options The `options` object declares NATS connection-related fields including `servers`, authentication-related fields (`authenticator`, `user`, `pass`, `token`, `nkey`, `userJWT`, `nonceSigner`, `userCreds`, and `tokenHandler`), TLS, reconnect controls, ping controls, `timeout`, and other NATS flags. Several callback-like or credential fields are typed as `any`; `servers` accepts either one string or a string array. [packages/microservices/interfaces/microservice-configuration.interface.ts:175-215](packages/microservices/interfaces/microservice-configuration.interface.ts#L175-L215) It also has an index signature, `[key: string]: any`, so TypeScript permits additional string-keyed option values. [packages/microservices/interfaces/microservice-configuration.interface.ts:213-215](packages/microservices/interfaces/microservice-configuration.interface.ts#L213-L215) Both `ClientNats` and `ServerNats` load the optional `nats` package and call its `connect` function with a default `servers` value of `nats://localhost:4222`, followed by a spread of this options object. Consequently, an `options.servers` value overrides that default in these paths. [packages/microservices/client/client-nats.ts:38-43](packages/microservices/client/client-nats.ts#L38-L43) [packages/microservices/client/client-nats.ts:69-75](packages/microservices/client/client-nats.ts#L69-L75) [packages/microservices/server/server-nats.ts:50-59](packages/microservices/server/server-nats.ts#L50-L59) [packages/microservices/server/server-nats.ts:126-132](packages/microservices/server/server-nats.ts#L126-L132) [packages/microservices/constants.ts:7](packages/microservices/constants.ts#L7) ## Nest-specific options and behavior - `queue` is used by `ServerNats` as the default queue when it subscribes each registered message-handler channel. A handler-level `extras.queue` takes precedence when present. [packages/microservices/interfaces/microservice-configuration.interface.ts:195-198](packages/microservices/interfaces/microservice-configuration.interface.ts#L195-L198) [packages/microservices/server/server-nats.ts:82-96](packages/microservices/server/server-nats.ts#L82-L96) - `headers` is merged into client-published request and event headers. Existing serialized-message header keys are retained; configured headers are added only when that key is absent. [packages/microservices/interfaces/microservice-configuration.interface.ts:175-177](packages/microservices/interfaces/microservice-configuration.interface.ts#L175-L177) [packages/microservices/client/client-nats.ts:223-227](packages/microservices/client/client-nats.ts#L223-L227) [packages/microservices/client/client-nats.ts:236-245](packages/microservices/client/client-nats.ts#L236-L245) [packages/microservices/client/client-nats.ts:262-275](packages/microservices/client/client-nats.ts#L262-L275) - `inboxPrefix` is passed to `nats.createInbox()` for client request/reply publishing. [packages/microservices/interfaces/microservice-configuration.interface.ts:179-182](packages/microservices/interfaces/microservice-configuration.interface.ts#L179-L182) [packages/microservices/client/client-nats.ts:209-227](packages/microservices/client/client-nats.ts#L209-L227) - `serializer` and `deserializer` accept objects implementing `serialize()` and `deserialize()` respectively. [packages/microservices/interfaces/microservice-configuration.interface.ts:196-198](packages/microservices/interfaces/microservice-configuration.interface.ts#L196-L198) [packages/microservices/interfaces/serializer.interface.ts:10-12](packages/microservices/interfaces/serializer.interface.ts#L10-L12) [packages/microservices/interfaces/deserializer.interface.ts:10-15](packages/microservices/interfaces/deserializer.interface.ts#L10-L15) The client defaults to `NatsRecordSerializer` and `NatsResponseJSONDeserializer`; the server defaults to `NatsRecordSerializer` and `NatsRequestJSONDeserializer` when these fields are absent. [packages/microservices/client/client-nats.ts:253-260](packages/microservices/client/client-nats.ts#L253-L260) [packages/microservices/server/server-nats.ts:281-288](packages/microservices/server/server-nats.ts#L281-L288) - When `debug` is truthy, both client and server log NATS `pingTimer` status updates at debug level. [packages/microservices/interfaces/microservice-configuration.interface.ts:176-179](packages/microservices/interfaces/microservice-configuration.interface.ts#L176-L179) [packages/microservices/client/client-nats.ts:126-132](packages/microservices/client/client-nats.ts#L126-L132) [packages/microservices/server/server-nats.ts:225-231](packages/microservices/server/server-nats.ts#L225-L231) - On server shutdown, `gracefulShutdown` causes all tracked subscriptions to unsubscribe, then waits for `gracePeriod`; if `gracePeriod` is absent, the wait is `10000` milliseconds, before closing the NATS client. Without `gracefulShutdown`, the server closes the client without that unsubscribe-and-wait branch. [packages/microservices/interfaces/microservice-configuration.interface.ts:213-214](packages/microservices/interfaces/microservice-configuration.interface.ts#L213-L214) [packages/microservices/server/server-nats.ts:99-124](packages/microservices/server/server-nats.ts#L99-L124) [packages/microservices/constants.ts:65](packages/microservices/constants.ts#L65) The observed client and server connection paths spread the options directly into `nats.connect`; they contain no field-by-field validation before that call. [packages/microservices/client/client-nats.ts:69-75](packages/microservices/client/client-nats.ts#L69-L75) [packages/microservices/server/server-nats.ts:126-132](packages/microservices/server/server-nats.ts#L126-L132) # ClientOptions **Kind:** Type **Source:** [`packages/microservices/interfaces/client-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/client-metadata.interface.ts#L17) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts | RedisOptions | NatsOptions | MqttOptions | GrpcOptions | KafkaOptions | TcpClientOptions | RmqOptions ``` ## Relationships - IMPORTS → `Type` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ConfigService` — `integration/microservices/src/app.module.ts`:18 - `ConfigService` — `integration/microservices/src/tcp-tls/app.module.ts`:29 # Cluster **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L199) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { getNodeIds(): number[]; metadata(): Promise; removeBroker(options: { host: string; port: number }): void; addMultipleTargetTopics(topics: string[]): Promise; isConnected(): boolean; connect(): Promise; disconnect(): Promise; refreshMetadata(): Promise; refreshMetadataIfNecessary(): Promise; addTargetTopic(topic: string): Promise; findBroker(node: { nodeId: string }): Promise; findControllerBroker(): Promise; findTopicPartitionMetadata(topic: string): PartitionMetadata[]; findLeaderForPartitions( topic: string, partitions: number[], ): { [leader: string]: number[] }; findGroupCoordinator(group: { groupId: string }): Promise; findGroupCoordinatorMetadata(group: { groupId: string; }): Promise; defaultOffset(config: { fromBeginning: boolean }): number; fetchTopicsOffset( topics: Array< { topic: string; partitions: Array<{ partition: number }>; } & XOR<{ fromBeginning: boolean }, { fromTimestamp: number }> >, ): Promise; } ``` # IdentityDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/identity.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/identity.deserializer.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) `IdentityDeserializer` is a pass-through microservice deserializer that returns incoming message data without transforming it. It is useful when a transport adapter already provides data in the format expected by the application and no custom parsing or normalization is required. **Implements:** `Deserializer` ## Methods | Method | Signature | Returns | |---|---|---| | `deserialize` | `deserialize(value: any)` | `void` | ## Diagram ```mermaid graph LR A[Microservice Transport] --> B[Incoming Message] B --> C[IdentityDeserializer] C --> D[deserialize()] D --> E[Original Message Value] E --> F[Message Handler] ``` ## Usage ```ts import { IdentityDeserializer } from '@nestjs/microservices'; const deserializer = new IdentityDeserializer(); const incomingMessage = { pattern: 'user.created', data: { id: 'user-123', email: 'user@example.com', }, }; const result = deserializer.deserialize(incomingMessage); console.log(result === incomingMessage); // true ``` ## AI Coding Instructions - Use `IdentityDeserializer` when transport payloads should be passed directly to message handlers without parsing or transformation. - Do not add validation, serialization, or cloning logic here; use a custom deserializer when payload normalization is required. - Ensure the configured microservice transport produces payloads compatible with the consuming handler's expected shape. - Configure this deserializer through the microservice transport options when replacing a transport-specific or custom deserialization strategy. # IdentitySerializer **Kind:** Class **Source:** [`packages/microservices/serializers/identity.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/identity.serializer.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) `IdentitySerializer` is a microservices serializer that returns values without transforming their content. It is useful when messages are already in the required transport format or when a custom serialization step is unnecessary. Its `serialize()` method preserves the original payload for downstream transport handling. **Implements:** `Serializer` ## Methods | Method | Signature | Returns | |---|---|---| | `serialize` | `serialize(value: any)` | `void` | ## Diagram ```mermaid graph LR A[Application Payload] --> B[IdentitySerializer] B -->|serialize() returns unchanged value| C[Microservice Transport] ``` ## Usage ```ts import { IdentitySerializer } from '@nestjs/microservices'; const serializer = new IdentitySerializer(); const payload = { event: 'user.created', userId: 'user_123', }; const serializedPayload = serializer.serialize(payload); console.log(serializedPayload); // { event: 'user.created', userId: 'user_123' } ``` ## AI Coding Instructions - Use `IdentitySerializer` when the transport or application already accepts the payload in its original form. - Do not expect `serialize()` to convert objects into JSON, buffers, or another wire format. - Configure this serializer in microservice client or server transport options when no custom serialization is required. - Prefer a custom serializer when the target transport requires encoding, schema mapping, validation, or payload normalization. # KafkaRetriableException **Kind:** Class **Source:** [`packages/microservices/exceptions/kafka-retriable-exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/exceptions/kafka-retriable-exception.ts#L13) **Part of:** [Microservices](subsystem-packages-microservices) Exception that instructs Kafka driver to instead of introspecting error processing flow and sending serialized error message to the consumer, force bubble it up to the "eachMessage" callback of the underlying "kafkajs" package (even if interceptors are applied, or an observable stream is returned from the message handler). A transient exception that if retried may succeed. `KafkaRetriableException` signals that Kafka message processing failed due to a transient error that may succeed on retry. It bypasses Nest's normal Kafka error serialization flow and bubbles the error to KafkaJS's `eachMessage` callback, allowing the underlying consumer to handle retries or failure behavior. **Extends:** `RpcException` ## Methods | Method | Signature | Returns | |---|---|---| | `getError` | `getError()` | `string | object` | ## Diagram ```mermaid graph LR A[Kafka message received] --> B[NestJS message handler] B --> C{Transient failure?} C -- No --> D[Normal error processing / serialization] C -- Yes --> E[Throw KafkaRetriableException] E --> F[Bypass Nest Kafka error flow] F --> G[KafkaJS eachMessage callback] G --> H[KafkaJS retry / consumer error handling] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Ctx, KafkaContext, MessagePattern, } from '@nestjs/microservices'; import { KafkaRetriableException } from '@nestjs/microservices/exceptions/kafka-retriable-exception'; @Controller() export class OrdersConsumer { @MessagePattern('orders.created') async handleOrder(@Ctx() context: KafkaContext) { try { await this.processOrder(context.getMessage().value); } catch (error) { // Throw for temporary failures that should be handled by KafkaJS. throw new KafkaRetriableException({ message: 'Order service is temporarily unavailable', cause: error, }); } } private async processOrder(order: unknown) { // Process the incoming order. } } ``` ## AI Coding Instructions - Throw `KafkaRetriableException` only for transient failures, such as temporary network, database, or downstream-service errors. - Do not use this exception for validation errors or permanently invalid messages; those should follow normal application error handling. - The exception intentionally bypasses Nest's Kafka error serialization and reaches KafkaJS's `eachMessage` processing flow. - Use `getError()` when integration code needs the original string or object error payload. - Ensure KafkaJS consumer retry and offset-commit settings match the intended retry behavior before introducing this exception. # NO_EVENT_HANDLER **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L55) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function NO_EVENT_HANDLER(text: TemplateStringsArray, pattern: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `pattern` | `string` | # Producer **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L798) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Sender & { connect(): Promise; disconnect(): Promise; isIdempotent(): boolean; readonly events: ProducerEvents; on( eventName: ProducerEvents['CONNECT'], listener: (event: ConnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ProducerEvents['DISCONNECT'], listener: (event: DisconnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ProducerEvents['REQUEST'], listener: (event: RequestEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ProducerEvents['REQUEST_QUEUE_SIZE'], listener: (event: RequestQueueSizeEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ProducerEvents['REQUEST_TIMEOUT'], listener: (event: RequestTimeoutEvent) => void, ): RemoveInstrumentationEventListener; on( eventName: ValueOf, listener: (event: InstrumentationEvent) => void, ): RemoveInstrumentationEventListener; transaction(): Promise; logger(): Logger; } ``` # ClientKafkaProxy **Kind:** Interface **Source:** [`packages/microservices/interfaces/client-kafka-proxy.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/client-kafka-proxy.interface.ts#L9) **Part of:** [Microservices](subsystem-packages-microservices) `ClientKafkaProxy` defines the Kafka client resources managed by a microservice client proxy. It exposes nullable `consumer` and `producer` references so the proxy can create, reuse, and clean up Kafka connections during its lifecycle. ## Properties | Property | Type | |---|---| | `consumer` | `Consumer | null` | | `producer` | `Producer | null` | ## Diagram ```mermaid graph LR Proxy[Kafka Client Proxy] --> Interface[ClientKafkaProxy] Interface --> Consumer[consumer: Consumer | null] Interface --> Producer[producer: Producer | null] Consumer --> Kafka[Kafka Broker] Producer --> Kafka ``` ## Usage ```ts import type { Consumer, Producer } from 'kafkajs'; import type { ClientKafkaProxy } from './client-kafka-proxy.interface'; class KafkaClient implements ClientKafkaProxy { consumer: Consumer | null = null; producer: Producer | null = null; async publish(topic: string, message: unknown) { if (!this.producer) { throw new Error('Kafka producer has not been initialized.'); } await this.producer.send({ topic, messages: [{ value: JSON.stringify(message) }], }); } async close() { await this.consumer?.disconnect(); await this.producer?.disconnect(); this.consumer = null; this.producer = null; } } ``` ## AI Coding Instructions - Treat `consumer` and `producer` as optional lifecycle-managed resources; always handle the `null` case before calling Kafka methods. - Initialize Kafka clients before subscribing, consuming, or publishing messages, and reset references to `null` after disconnecting. - Use the KafkaJS `Consumer` and `Producer` types when implementing this interface. - Ensure shutdown logic disconnects both resources safely, using optional chaining or explicit null checks. # KafkaJSConnectionError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1180) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `broker` | `string` | # KafkaJSDeleteGroupsError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1256) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `groups` | `DeleteGroupsResult[]` | # KafkaOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L333) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaOptions` configures a NestJS microservice that communicates through Apache Kafka. It combines Kafka client, consumer, producer, subscription, serialization, and message-parsing settings while enforcing `Transport.KAFKA` as the selected transport. ## Properties | Property | Type | |---|---| | `transport` | `Transport.KAFKA` | | `options` | `{ postfixId?: string; client?: KafkaConfig; consumer?: ConsumerConfig; run?: Omit; subscribe?: Omit; producer?: ProducerConfig; send?: Omit; serializer?: Serializer; deserializer?: Deserializer; parser?: KafkaParserConfig; producerOnlyMode?: boolean; }` | ## Diagram ```mermaid graph LR A[KafkaOptions] --> B[transport: Transport.KAFKA] A --> C[options] C --> D[client: KafkaConfig] C --> E[consumer: ConsumerConfig] C --> F[run: ConsumerRunConfig] C --> G[subscribe: ConsumerSubscribeTopics] C --> H[producer: ProducerConfig] C --> I[send: ProducerRecord defaults] C --> J[serializer / deserializer] C --> K[parser: KafkaParserConfig] C --> L[producerOnlyMode] D --> M[Kafka Broker] E --> M H --> M ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { KafkaOptions, Transport } from '@nestjs/microservices'; async function bootstrap() { const kafkaOptions: KafkaOptions = { transport: Transport.KAFKA, options: { client: { clientId: 'billing-service', brokers: ['localhost:9092'], }, consumer: { groupId: 'billing-consumer-group', }, subscribe: { fromBeginning: false, }, run: { autoCommit: true, }, producer: { allowAutoTopicCreation: false, }, send: { acks: -1, }, }, }; const app = await NestFactory.createMicroservice(AppModule, kafkaOptions); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Always set `transport` to `Transport.KAFKA`; this interface is specifically for Kafka-based microservices. - Configure a unique `client.clientId` and stable `consumer.groupId` to avoid conflicts between deployed service instances. - Do not provide `topics` in `subscribe`, `topic` or `messages` in `send`, or `eachBatch`/`eachMessage` in `run`; NestJS manages these values per handler and message operation. - Use custom `serializer`, `deserializer`, or `parser` options when integrating with non-Nest producers or consumers that use different payload formats. - Set `producerOnlyMode: true` for services that publish Kafka messages but do not register Kafka message handlers. # MqttOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L142) **Part of:** [Microservices](subsystem-packages-microservices) `MqttOptions` configures a NestJS microservice that communicates through the MQTT transport. It combines standard MQTT client settings with Nest-specific serialization, deserialization, subscription, and MQTT v5 user-property options. ## Properties | Property | Type | |---|---| | `transport` | `Transport.MQTT` | | `options` | `MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; subscribeOptions?: { qos: QoS; nl?: boolean; rap?: boolean; rh?: number; }; userProperties?: Record; }` | ## Diagram ```mermaid graph LR A[Microservice Configuration] --> B[MqttOptions] B --> C[transport: Transport.MQTT] B --> D[options] D --> E[MqttClientOptions] D --> F[url] D --> G[serializer / deserializer] D --> H[subscribeOptions] D --> I[userProperties] H --> J[qos, nl, rap, rh] B --> K[MQTT Broker] ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import type { MqttOptions } from '@nestjs/microservices'; const mqttConfig: MqttOptions = { transport: Transport.MQTT, options: { url: 'mqtt://localhost:1883', clientId: 'orders-service', clean: true, subscribeOptions: { qos: 1, nl: false, rap: true, rh: 0, }, userProperties: { service: 'orders', environment: 'production', }, }, }; // Example integration: // NestFactory.createMicroservice(AppModule, mqttConfig); ``` ## AI Coding Instructions - Always set `transport` to `Transport.MQTT`; this interface is specifically for MQTT microservice configurations. - Use `options.url` for the broker connection string, or provide equivalent host, port, and protocol settings supported by `MqttClientOptions`. - Configure `serializer` and `deserializer` together when using a custom message format so outgoing and incoming payloads remain compatible. - Set `subscribeOptions.qos` intentionally based on delivery guarantees; higher QoS can increase broker and network overhead. - Use `userProperties` only when the connected broker and clients support MQTT v5 properties. ## How it works `MqttOptions` is the public TypeScript configuration interface for selecting the MQTT microservice transport. It is one variant of `MicroserviceOptions`; its optional `transport` discriminator is `Transport.MQTT`, and its optional `options` object combines MQTT client connection settings with Nest-specific MQTT settings. [microservice-configuration.interface.ts:25-33](packages/microservices/interfaces/microservice-configuration.interface.ts#L25-L33) [microservice-configuration.interface.ts:142-168](packages/microservices/interfaces/microservice-configuration.interface.ts#L142-L168) # MqttRecordOptions **Kind:** Interface **Source:** [`packages/microservices/record-builders/mqtt.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/mqtt.record-builder.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) `MqttRecordOptions` defines MQTT-specific delivery and message metadata used when building MQTT records in the microservices layer. It controls QoS, retained and duplicate delivery flags, and MQTT v5 properties such as expiry intervals, response topics, correlation data, and user properties. ## Properties | Property | Type | |---|---| | `qos` | `0 | 1 | 2` | | `retain` | `boolean` | | `dup` | `boolean` | | `properties` | `{ payloadFormatIndicator?: boolean; messageExpiryInterval?: number; topicAlias?: number; responseTopic?: string; correlationData?: Buffer; userProperties?: Record; subscriptionIdentifier?: number; contentType?: string; }` | ## Diagram ```mermaid graph LR Builder[Mqtt Record Builder] --> Options[MqttRecordOptions] Options --> Delivery[Delivery Flags] Options --> Properties[MQTT v5 Properties] Delivery --> QoS["qos: 0 | 1 | 2"] Delivery --> Retain["retain: boolean"] Delivery --> Dup["dup: boolean"] Properties --> PayloadFormat[payloadFormatIndicator] Properties --> Expiry[messageExpiryInterval] Properties --> Response[responseTopic] Properties --> Correlation[correlationData] Properties --> UserProps[userProperties] ``` ## Usage ```ts import type { MqttRecordOptions } from './mqtt.record-builder'; const options: MqttRecordOptions = { qos: 1, retain: false, dup: false, properties: { contentType: 'application/json', messageExpiryInterval: 300, responseTopic: 'devices/device-123/responses', correlationData: Buffer.from('request-abc'), userProperties: { source: 'api', tags: ['telemetry', 'priority'], }, }, }; // Pass options to the MQTT record builder or publishing workflow. ``` ## AI Coding Instructions - Use `qos` values only from the supported MQTT levels: `0`, `1`, or `2`. - Set `retain` only when the broker should store the message as the topic's latest retained value. - Preserve `dup` when retrying an MQTT delivery; do not use it to indicate an application-level duplicate payload. - Keep MQTT v5 metadata inside `properties`, including response/correlation fields for request-response flows. - Use `Buffer` for `correlationData` and allow `userProperties` values to be either a single string or an array of strings. ## How it works `MqttRecordOptions` is an exported, public TypeScript interface for optional MQTT publish settings attached to an `MqttRecord`. [`packages/microservices/record-builders/mqtt.record-builder.ts:1-4`](packages/microservices/record-builders/mqtt.record-builder.ts#L1-L4) [`packages/microservices/record-builders/mqtt.record-builder.ts:35-39`](packages/microservices/record-builders/mqtt.record-builder.ts#L35-L39) - `qos` is optional and is typed as `0`, `1`, or `2`; `retain` and `dup` are optional booleans. [`packages/microservices/record-builders/mqtt.record-builder.ts:5-16`](packages/microservices/record-builders/mqtt.record-builder.ts#L5-L16) - Its optional `properties` object declares `payloadFormatIndicator`, `messageExpiryInterval`, `topicAlias`, `responseTopic`, `correlationData`, `userProperties`, `subscriptionIdentifier`, and `contentType`. `userProperties` maps strings to either a string or an array of strings. [`packages/microservices/record-builders/mqtt.record-builder.ts:17-29`](packages/microservices/record-builders/mqtt.record-builder.ts#L17-L29) - The interface declares no required members, runtime validation, or errors. Its declared type restricts `qos`, while the numeric property fields are declared as `number`. [`packages/microservices/record-builders/mqtt.record-builder.ts:4-30`](packages/microservices/record-builders/mqtt.record-builder.ts#L4-L30) `MqttRecordBuilder` accumulates these fields through `setQoS`, `setRetain`, `setDup`, and `setProperties`; each method replaces the corresponding option while retaining previously set top-level options, then returns the builder. [`packages/microservices/record-builders/mqtt.record-builder.ts:45-85`](packages/microservices/record-builders/mqtt.record-builder.ts#L45-L85) `build()` passes the accumulated options to a new `MqttRecord`. [`packages/microservices/record-builders/mqtt.record-builder.ts:87-89`](packages/microservices/record-builders/mqtt.record-builder.ts#L87-L89) When `ClientMqtt` sends a packet whose data is an `MqttRecord`, it reads `record.options`, deletes the record’s `options` property before serialization, and passes the options to the MQTT client’s `publish` call. [`packages/microservices/client/client-mqtt.ts:237-249`](packages/microservices/client/client-mqtt.ts#L237-L249) [`packages/microservices/client/client-mqtt.ts:271-286`](packages/microservices/client/client-mqtt.ts#L271-L286) The default MQTT record serializer serializes `record.data` as the packet’s `data`, not the options object. [`packages/microservices/serializers/mqtt-record.serializer.ts:5-14`](packages/microservices/serializers/mqtt-record.serializer.ts#L5-L14) If client-level `userProperties` are configured, `ClientMqtt` merges them with record-level `properties.userProperties`; record-level keys are spread last and therefore overwrite matching client-level keys. [`packages/microservices/client/client-mqtt.ts:303-326`](packages/microservices/client/client-mqtt.ts#L303-L326) # ConsumerConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L164) **Part of:** [Microservices](subsystem-packages-microservices) `ConsumerConfig` defines configuration options for a Kafka consumer used by the microservices Kafka transport. It controls consumer group membership, partition assignment and rebalancing behavior, heartbeat/session timing, and message fetch batch limits. ## Properties | Property | Type | |---|---| | `groupId` | `string` | | `partitionAssigners` | `PartitionAssigner[]` | | `metadataMaxAge` | `number` | | `sessionTimeout` | `number` | | `rebalanceTimeout` | `number` | | `heartbeatInterval` | `number` | | `maxBytesPerPartition` | `number` | | `minBytes` | `number` | | `maxBytes` | `number` | | `maxWaitTimeInMs` | `number` | | `retry` | `RetryOptions & { restartOnFailure?: (err: Error) => Promise; }` | | `allowAutoTopicCreation` | `boolean` | | `maxInFlightRequests` | `number` | | `readUncommitted` | `boolean` | | `rackId` | `string` | ## Diagram ```mermaid graph LR App[Microservice Consumer] --> Config[ConsumerConfig] Config --> Group[groupId] Config --> Assignment[partitionAssigners] Config --> Rebalancing[Session, rebalance, and heartbeat settings] Config --> Fetching[Fetch size and wait-time settings] Group --> Kafka[Kafka Consumer Group] Assignment --> Kafka Rebalancing --> Kafka Fetching --> Kafka ``` ## Usage ```ts import type { ConsumerConfig } from './kafka.interface'; const consumerConfig: ConsumerConfig = { groupId: 'billing-service', partitionAssigners: [], metadataMaxAge: 300_000, sessionTimeout: 30_000, rebalanceTimeout: 60_000, heartbeatInterval: 3_000, maxBytesPerPartition: 1_048_576, minBytes: 1, maxBytes: 10_485_760, maxWaitTimeInMs: 5_000, }; // Pass consumerConfig to the Kafka transport/client initialization. ``` ## AI Coding Instructions - Use a stable, service-specific `groupId`; consumers sharing a group ID load-balance partitions. - Keep `heartbeatInterval` meaningfully lower than `sessionTimeout` to prevent unintended consumer removal. - Ensure `maxBytes` is large enough for the expected aggregate batch size and is compatible with broker fetch limits. - Configure `partitionAssigners` consistently across consumers in the same group to avoid rebalance compatibility issues. - Treat timeout and fetch-size changes as operational tuning values; validate them against message volume and processing duration. ## How it works `ConsumerConfig` is an exported TypeScript interface representing the KafkaJS consumer-creation options in this repository’s Kafka type surface; the file explicitly states that it contains KafkaJS types only, not NestJS logic. [`packages/microservices/external/kafka.interface.ts:1-8`](packages/microservices/external/kafka.interface.ts#L1-L8) A `Kafka` instance accepts this type as the required argument to `consumer()` and returns a `Consumer`. [`packages/microservices/external/kafka.interface.ts:19-24`](packages/microservices/external/kafka.interface.ts#L19-L24) # ConsumerEvents **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L910) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { HEARTBEAT: 'consumer.heartbeat'; COMMIT_OFFSETS: 'consumer.commit_offsets'; GROUP_JOIN: 'consumer.group_join'; FETCH_START: 'consumer.fetch_start'; FETCH: 'consumer.fetch'; START_BATCH_PROCESS: 'consumer.start_batch_process'; END_BATCH_PROCESS: 'consumer.end_batch_process'; CONNECT: 'consumer.connect'; DISCONNECT: 'consumer.disconnect'; STOP: 'consumer.stop'; CRASH: 'consumer.crash'; REBALANCING: 'consumer.rebalancing'; RECEIVED_UNSUBSCRIBED_TOPICS: 'consumer.received_unsubscribed_topics'; REQUEST: 'consumer.network.request'; REQUEST_TIMEOUT: 'consumer.network.request_timeout'; REQUEST_QUEUE_SIZE: 'consumer.network.request_queue_size'; } ``` # InvalidTcpDataReceptionException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-tcp-data-reception.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-tcp-data-reception.exception.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # RmqRecordOptions **Kind:** Interface **Source:** [`packages/microservices/record-builders/rmq.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/rmq.record-builder.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) `RmqRecordOptions` defines RabbitMQ message properties used when building a record for publishing through the microservices layer. It controls message lifetime, routing metadata, delivery behavior, content metadata, and custom headers passed to the RabbitMQ broker. ## Properties | Property | Type | |---|---| | `expiration` | `string | number` | | `userId` | `string` | | `CC` | `string | string[]` | | `mandatory` | `boolean` | | `persistent` | `boolean` | | `deliveryMode` | `boolean | number` | | `BCC` | `string | string[]` | | `contentType` | `string` | | `contentEncoding` | `string` | | `headers` | `Record` | | `priority` | `number` | | `messageId` | `string` | | `timestamp` | `number` | | `type` | `string` | | `appId` | `string` | ## Diagram ```mermaid graph LR A[Application Message] --> B[RmqRecordOptions] B --> C[RMQ Record Builder] C --> D[RabbitMQ Publish Properties] B --> E[Routing: CC / BCC] B --> F[Delivery: mandatory / persistent / deliveryMode] B --> G[Metadata: contentType / contentEncoding / headers] B --> H[Lifetime: expiration] ``` ## Usage ```ts import type { RmqRecordOptions } from './rmq.record-builder'; const options: RmqRecordOptions = { expiration: 60_000, userId: 'notification-service', CC: ['audit.queue'], BCC: 'internal-monitoring.queue', mandatory: true, persistent: true, deliveryMode: 2, contentType: 'application/json', contentEncoding: 'utf-8', headers: { 'x-request-id': 'req_123456', 'x-message-source': 'notifications', }, }; // Pass options to the RMQ record/message builder used by your publisher. ``` ## AI Coding Instructions - Provide all required properties when creating `RmqRecordOptions`; use `headers: {}` when no custom headers are needed. - Use `expiration` as a millisecond value or RabbitMQ-compatible string, and ensure it matches the intended message TTL behavior. - Use `CC` and `BCC` for additional broker routing targets; provide either a single queue name or an array of queue names. - Prefer `deliveryMode: 2` and `persistent: true` for messages that should survive broker restarts. - Keep `headers` values as strings, serializing complex values before assigning them. # TcpOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L101) **Part of:** [Microservices](subsystem-packages-microservices) `TcpOptions` configures a NestJS microservice that communicates over the TCP transport. It defines the required `transport` type and optional connection, retry, serialization, TLS, socket, and buffer settings used when creating the microservice. ## Properties | Property | Type | |---|---| | `transport` | `Transport.TCP` | | `options` | `{ host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; tlsOptions?: TlsOptions; deserializer?: Deserializer; socketClass?: Type; maxBufferSize?: number; }` | ## Diagram ```mermaid graph LR A[Microservice Configuration] --> B[TcpOptions] B --> C[transport: Transport.TCP] B --> D[options] D --> E[host and port] D --> F[retryAttempts and retryDelay] D --> G[serializer and deserializer] D --> H[tlsOptions] D --> I[socketClass] D --> J[maxBufferSize] E --> K[TCP Microservice Server] ``` ## Usage ```ts import { Transport, type TcpOptions } from '@nestjs/microservices'; const tcpConfig: TcpOptions = { transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001, retryAttempts: 5, retryDelay: 1000, maxBufferSize: 1024 * 1024, }, }; // Example: NestFactory.createMicroservice(AppModule, tcpConfig) ``` ## AI Coding Instructions - Always set `transport` to `Transport.TCP`; this interface is specific to TCP-based microservices. - Configure both `host` and `port` explicitly for predictable local, container, and production networking behavior. - Use `retryAttempts` and `retryDelay` when the application must reconnect to TCP dependencies that may start later. - Provide matching `serializer` and `deserializer` implementations when communicating with services that use custom message formats. - Set `tlsOptions`, `socketClass`, or `maxBufferSize` only when required by the deployment environment or protocol requirements. ## How it works `TcpOptions` is a public TypeScript interface for configuring a TCP microservice server. It is one member of the `MicroserviceOptions` union, and its optional `transport` discriminator is `Transport.TCP`. Its `options` object is also optional. [microservice-configuration.interface.ts:25-33](packages/microservices/interfaces/microservice-configuration.interface.ts#L25-L33) [microservice-configuration.interface.ts:98-118](packages/microservices/interfaces/microservice-configuration.interface.ts#L98-L118) The interface itself has no executable validation: every declared property, including `options`, is optional. [microservice-configuration.interface.ts:101-117](packages/microservices/interfaces/microservice-configuration.interface.ts#L101-L117) When the server factory receives a non-custom configuration whose transport is not one of the explicitly handled non-TCP transports, it constructs `ServerTCP` with this interface’s `options` object. [server-factory.ts:21-41](packages/microservices/server/server-factory.ts#L21-L41) # AclOperationTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L319) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `UNKNOWN` - `ANY` - `ALL` - `READ` - `WRITE` - `CREATE` - `DELETE` - `ALTER` - `DESCRIBE` - `CLUSTER_ACTION` - `DESCRIBE_CONFIGS` - `ALTER_CONFIGS` - `IDEMPOTENT_WRITE` # ChannelOptions **Kind:** Interface **Source:** [`packages/microservices/external/grpc-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/grpc-options.interface.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) An interface that contains options used when initializing a Channel instance. This listing is incomplete. Full reference: https://grpc.github.io/grpc/core/group__grpc__arg__keys.html `ChannelOptions` defines gRPC channel arguments used when creating or configuring a client connection. It provides typed access to common transport, message-size, TLS authority, user-agent, service configuration, and reconnection settings passed to the underlying gRPC implementation. ## Properties | Property | Type | |---|---| | `'grpc.max_send_message_length'` | `number` | | `'grpc.max_receive_message_length'` | `number` | | `'grpc.max_metadata_size'` | `number` | | `'grpc.ssl_target_name_override'` | `string` | | `'grpc.primary_user_agent'` | `string` | | `'grpc.secondary_user_agent'` | `string` | | `'grpc.default_authority'` | `string` | | `'grpc.service_config'` | `string` | | `'grpc.max_concurrent_streams'` | `number` | | `'grpc.initial_reconnect_backoff_ms'` | `number` | | `'grpc.max_reconnect_backoff_ms'` | `number` | | `'grpc.use_local_subchannel_pool'` | `number` | | `'grpc-node.max_session_memory'` | `number` | ## Diagram ```mermaid graph LR Client[gRPC Client Configuration] --> Options[ChannelOptions] Options --> Limits[Message and Metadata Limits] Options --> TLS[TLS Target and Authority] Options --> Identity[User-Agent Settings] Options --> Connection[Streams and Reconnect Settings] Options --> Service[Service Configuration] Limits --> Channel[gRPC Channel] TLS --> Channel Identity --> Channel Connection --> Channel Service --> Channel ``` ## Usage ```ts import type { ChannelOptions } from './grpc-options.interface'; const channelOptions: ChannelOptions = { 'grpc.max_send_message_length': 4 * 1024 * 1024, 'grpc.max_receive_message_length': 4 * 1024 * 1024, 'grpc.max_metadata_size': 8 * 1024, 'grpc.ssl_target_name_override': 'grpc.example.com', 'grpc.primary_user_agent': 'my-service/1.0.0', 'grpc.default_authority': 'grpc.example.com', 'grpc.max_concurrent_streams': 100, 'grpc.initial_reconnect_backoff_ms': 1_000, }; // Pass the options to the gRPC client/channel factory used by your application. const client = createGrpcClient('grpc.example.com:443', channelOptions); ``` ## AI Coding Instructions - Use the exact gRPC argument names, including the `grpc.` prefix; these keys are consumed by the underlying gRPC runtime. - Specify message and metadata limits in bytes, and ensure configured limits match expected payload sizes across clients and servers. - Set `grpc.ssl_target_name_override` and `grpc.default_authority` only when required for TLS, proxy, or custom authority scenarios. - Treat `grpc.service_config` as serialized service configuration data expected by gRPC, not as an arbitrary application configuration object. - Consult the gRPC channel argument reference before adding new options, since this interface represents only a subset of supported arguments. # ClientsModuleOptionsFactory **Kind:** Interface **Source:** [`packages/microservices/module/interfaces/clients-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/interfaces/clients-module.interface.ts#L17) **Part of:** [Microservices](subsystem-packages-microservices) ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ConfigService` — `integration/microservices/src/app.module.ts`:18 - `ConfigService` — `integration/microservices/src/tcp-tls/app.module.ts`:29 # CustomTransportStrategy **Kind:** Interface **Source:** [`packages/microservices/interfaces/custom-transport-strategy.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/custom-transport-strategy.interface.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) `CustomTransportStrategy` identifies a custom microservice transport implementation through its `transportId`. It is used by the microservices layer to distinguish custom transport strategies from built-in transports and route configuration or lifecycle handling to the correct implementation. ## Properties | Property | Type | |---|---| | `transportId` | `TransportId` | ## Diagram ```mermaid graph LR App[Application Configuration] --> Strategy[CustomTransportStrategy] Strategy --> TransportId[transportId: TransportId] TransportId --> CustomTransport[Custom Transport Implementation] CustomTransport --> Microservice[Microservice Runtime] ``` ## Usage ```ts import { CustomTransportStrategy } from '@nestjs/microservices'; import { Transport } from '@nestjs/microservices/enums/transport.enum'; class RedisStreamsTransportStrategy implements CustomTransportStrategy { transportId = Transport.REDIS; listen(callback: () => void) { // Start the custom transport server. callback(); } close() { // Release transport resources. } } const strategy = new RedisStreamsTransportStrategy(); // Pass the strategy to your microservice configuration as needed. console.log(strategy.transportId); ``` ## AI Coding Instructions - Implement `transportId` with the `TransportId` value that uniquely identifies the custom transport. - Keep the identifier stable; changing it can break transport selection and configuration lookup. - Use this interface alongside the required custom server or client transport strategy interfaces when implementing runtime behavior. - Ensure the custom transport's lifecycle methods, such as startup and shutdown, are handled by the associated strategy implementation. # IClientPublishOptions **Kind:** Interface **Source:** [`packages/microservices/external/mqtt-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/mqtt-options.interface.ts#L151) **Part of:** [Microservices](subsystem-packages-microservices) `IClientPublishOptions` defines MQTT-specific options applied when publishing a message from a microservice client. It controls the delivery quality of service, whether the broker retains the message, and whether the message is marked as a duplicate delivery. ## Properties | Property | Type | |---|---| | `qos` | `QoS` | | `retain` | `boolean` | | `dup` | `boolean` | ## Diagram ```mermaid graph LR Client[MQTT Client] -->|publish topic + payload| Options[IClientPublishOptions] Options --> QoS[qos: QoS] Options --> Retain[retain: boolean] Options --> Duplicate[dup: boolean] Options --> Broker[MQTT Broker] ``` ## Usage ```ts import { IClientPublishOptions } from '@nestjs/microservices'; const publishOptions: IClientPublishOptions = { qos: 1, retain: true, dup: false, }; client.publish( 'devices/thermostat/status', JSON.stringify({ temperature: 21.5 }), publishOptions, ); ``` ## AI Coding Instructions - Set `qos` according to delivery requirements: `0` for best-effort, `1` for at-least-once delivery, and `2` for exactly-once delivery. - Use `retain: true` only for topics where new subscribers should receive the latest published state. - Keep `dup` as `false` for normal publishes; set it only when explicitly retransmitting a previously sent MQTT message. - Pass these options to the underlying MQTT client's publish operation when implementing custom transport or client behavior. # ISecureClientOptions **Kind:** Interface **Source:** [`packages/microservices/external/mqtt-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/mqtt-options.interface.ts#L136) **Part of:** [Microservices](subsystem-packages-microservices) `ISecureClientOptions` defines TLS/SSL configuration for MQTT client connections in the microservices package. It supplies client credentials, trusted certificate authorities, and certificate-validation behavior when connecting to secure MQTT brokers. ## Properties | Property | Type | |---|---| | `key` | `string | string[] | Buffer | Buffer[] | Record[]` | | `cert` | `string | string[] | Buffer | Buffer[]` | | `ca` | `string | string[] | Buffer | Buffer[]` | | `rejectUnauthorized` | `boolean` | ## Diagram ```mermaid graph LR Client[MQTT Client] --> Options[ISecureClientOptions] Options --> Key[key: Client private key] Options --> Cert[cert: Client certificate] Options --> CA[ca: Trusted CA certificates] Options --> Reject[rejectUnauthorized: Validate broker certificate] Options --> Broker[Secure MQTT Broker] ``` ## Usage ```ts import { readFileSync } from 'node:fs'; import type { ISecureClientOptions } from './mqtt-options.interface'; const secureOptions: ISecureClientOptions = { key: readFileSync('./certs/client-key.pem'), cert: readFileSync('./certs/client-cert.pem'), ca: readFileSync('./certs/ca-cert.pem'), rejectUnauthorized: true, }; // Pass secureOptions to the MQTT client connection configuration. ``` ## AI Coding Instructions - Provide `key` and `cert` together when configuring mutual TLS authentication. - Use `ca` to trust private or self-signed certificate authorities instead of disabling validation. - Keep `rejectUnauthorized` set to `true` in production to verify the MQTT broker certificate. - Accept certificate values as PEM strings, `Buffer` instances, or arrays when multiple certificates are required. - Load private keys and certificates from secure configuration or secret storage; do not hardcode them in source files. # KafkaConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L60) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaConfig` defines the connection, authentication, timeout, and retry settings used to create a Kafka client for the microservices transport layer. It supports static or dynamically resolved brokers, optional TLS, SASL authentication, and configurable request retry behavior. ## Properties | Property | Type | |---|---| | `brokers` | `string[] | BrokersFunction` | | `ssl` | `tls.ConnectionOptions | boolean` | | `sasl` | `SASLOptions | Mechanism` | | `clientId` | `string` | | `connectionTimeout` | `number` | | `authenticationTimeout` | `number` | | `reauthenticationThreshold` | `number` | | `requestTimeout` | `number` | | `enforceRequestTimeout` | `boolean` | | `retry` | `RetryOptions` | | `socketFactory` | `ISocketFactory` | | `logLevel` | `logLevel` | | `logCreator` | `logCreator` | ## Diagram ```mermaid graph LR App[Microservice Application] --> Config[KafkaConfig] Config --> Brokers[brokers
string[] or BrokersFunction] Config --> Security[ssl and sasl] Config --> Identity[clientId] Config --> Timeouts[Connection and Request Timeouts] Config --> Retry[retry Options] Brokers --> Kafka[Kafka Cluster] Security --> Kafka Identity --> Kafka Timeouts --> Kafka Retry --> Kafka ``` ## Usage ```ts import type { KafkaConfig } from '@nestjs/microservices'; const kafkaConfig: KafkaConfig = { clientId: 'orders-service', brokers: ['kafka-1.example.com:9092', 'kafka-2.example.com:9092'], ssl: true, sasl: { mechanism: 'plain', username: process.env.KAFKA_USERNAME!, password: process.env.KAFKA_PASSWORD!, }, connectionTimeout: 10_000, authenticationTimeout: 10_000, reauthenticationThreshold: 10_000, requestTimeout: 30_000, enforceRequestTimeout: true, retry: { retries: 8, initialRetryTime: 300, }, }; ``` ## AI Coding Instructions - Provide at least one reachable Kafka broker through `brokers`; use a `BrokersFunction` only when broker discovery must be resolved dynamically. - Match `ssl` and `sasl` settings to the Kafka cluster security configuration; enabling SASL without valid credentials will prevent client startup. - Set a stable, unique `clientId` per service to make Kafka logs, metrics, and broker-side diagnostics easier to trace. - Keep timeout and retry values aligned with deployment networking conditions, especially when connecting to managed or cross-region Kafka clusters. - Enable `enforceRequestTimeout` when requests must fail predictably instead of waiting indefinitely for broker responses. # RedisOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L123) **Part of:** [Microservices](subsystem-packages-microservices) `RedisOptions` configures a NestJS microservice that uses the Redis transport layer. It combines Redis connection settings from `IORedisOptions` with Nest-specific retry, wildcard subscription, serialization, and deserialization behavior. ## Properties | Property | Type | |---|---| | `transport` | `Transport.REDIS` | | `options` | `{ host?: string; port?: number; retryAttempts?: number; retryDelay?: number; wildcards?: boolean; serializer?: Serializer; deserializer?: Deserializer; } & IORedisOptions` | ## Diagram ```mermaid graph LR App[Application Bootstrap] --> Config[RedisOptions] Config --> Transport[transport: Transport.REDIS] Config --> Connection[IORedis Connection Options] Config --> Retry[Retry Configuration] Config --> Serialization[Serializer / Deserializer] Config --> Wildcards[Wildcard Subscriptions] Connection --> Redis[(Redis Server)] Transport --> Redis ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import type { RedisOptions } from '@nestjs/microservices'; const redisMicroserviceOptions: RedisOptions = { transport: Transport.REDIS, options: { host: 'localhost', port: 6379, retryAttempts: 5, retryDelay: 3000, wildcards: true, // Any additional ioredis options are also supported. password: process.env.REDIS_PASSWORD, db: 0, }, }; // Example: // app.connectMicroservice(redisMicroserviceOptions); ``` ## AI Coding Instructions - Always set `transport` to `Transport.REDIS`; this interface is only valid for Redis-based microservices. - Place Redis connection settings such as `host`, `port`, `password`, `db`, and TLS configuration inside `options`. - Use `retryAttempts` and `retryDelay` to control Nest microservice reconnection behavior; ensure retry values match deployment reliability requirements. - Enable `wildcards` only when message patterns require wildcard Redis channel subscriptions. - Provide compatible `serializer` and `deserializer` implementations when using custom message payload formats. # RequestEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L408) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ apiKey: number; apiName: string; apiVersion: number; broker: string; clientId: string; correlationId: number; createdAt: number; duration: number; pendingDuration: number; sentAt: number; size: number; }> ``` # TcpClientOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/client-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/client-metadata.interface.ts#L37) **Part of:** [Microservices](subsystem-packages-microservices) `TcpClientOptions` configures a microservice client that communicates over the TCP transport. It defines the target host and port, optional serialization behavior, TLS settings, socket implementation, and the maximum inbound buffer size. ## Properties | Property | Type | |---|---| | `transport` | `Transport.TCP` | | `options` | `{ host?: string; port?: number; serializer?: Serializer; deserializer?: Deserializer; tlsOptions?: ConnectionOptions; socketClass?: Type; maxBufferSize?: number; }` | ## Diagram ```mermaid graph LR Client[TCP Microservice Client] --> Config[TcpClientOptions] Config --> Transport[transport: Transport.TCP] Config --> Connection[options] Connection --> Host[host] Connection --> Port[port] Connection --> Serialization[serializer / deserializer] Connection --> TLS[tlsOptions] Connection --> Socket[socketClass] Connection --> Buffer[maxBufferSize] Client --> Server[TCP Server] ``` ## Usage ```ts import { ClientProxyFactory, Transport } from '@nestjs/microservices'; import type { TcpClientOptions } from '@nestjs/microservices'; const tcpOptions: TcpClientOptions = { transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001, maxBufferSize: 1024 * 1024, }, }; const client = ClientProxyFactory.create(tcpOptions); client.send({ cmd: 'get_user' }, { id: '123' }).subscribe(response => { console.log(response); }); ``` ## AI Coding Instructions - Always set `transport` to `Transport.TCP`; this interface is only valid for TCP client configurations. - Provide `host` and `port` values that match the TCP microservice server configuration. - Use matching `serializer` and `deserializer` implementations on both client and server when customizing message encoding. - Configure `tlsOptions` only when connecting to a TLS-enabled TCP server, using compatible Node.js `ConnectionOptions`. - Set `maxBufferSize` appropriately for expected payload sizes to prevent oversized TCP message buffering. ## How it works `TcpClientOptions` is the public TypeScript configuration interface for a TCP microservice client. Its `transport` field is required and must be `Transport.TCP`; it is one member of the `ClientOptions` union. [client-metadata.interface.ts:17-24](packages/microservices/interfaces/client-metadata.interface.ts#L17-L24) [client-metadata.interface.ts:34-38](packages/microservices/interfaces/client-metadata.interface.ts#L34-L38) - `options` is optional. When present, it may contain `host`, `port`, `serializer`, `deserializer`, `tlsOptions`, `socketClass`, and `maxBufferSize`. [client-metadata.interface.ts:37-51](packages/microservices/interfaces/client-metadata.interface.ts#L37-L51) - `ClientProxyFactory.create()` defaults a missing `options` object to `{}` and, for TCP/default transport selection, constructs `ClientTCP` with those options. [client-proxy-factory.ts:42-49](packages/microservices/client/client-proxy-factory.ts#L42-L49) [client-proxy-factory.ts:70-73](packages/microservices/client/client-proxy-factory.ts#L70-L73) - `host` and `port` select the connection endpoint. If absent, `ClientTCP` uses `localhost` and `3000`, respectively. [client-tcp.ts:30-33](packages/microservices/client/client-tcp.ts#L30-L33) [constants.ts:3-4](packages/microservices/constants.ts#L3-L4) - `serializer` must implement `serialize(value, options?)`; `deserializer` must implement `deserialize(value, options?)`, which may return a value or promise. If either is absent or falsy, the client initializes an identity serializer or incoming-response deserializer, respectively. [serializer.interface.ts:10-12](packages/microservices/interfaces/serializer.interface.ts#L10-L12) [deserializer.interface.ts:10-15](packages/microservices/interfaces/deserializer.interface.ts#L10-L15) [client-proxy.ts:208-231](packages/microservices/client/client-proxy.ts#L208-L231) - `tlsOptions` has Node TLS `ConnectionOptions` type. When it is set, the client creates its underlying socket with `tls.connect`, merging these options while overriding its `port` and `host`; otherwise it creates a `net.Socket` and explicitly connects it during `connect()`. [client-metadata.interface.ts:42-45](packages/microservices/interfaces/client-metadata.interface.ts#L42-L45) [client-tcp.ts:65-68](packages/microservices/client/client-tcp.ts#L65-L68) [client-tcp.ts:99-121](packages/microservices/client/client-tcp.ts#L99-L121) - `socketClass` is a `TcpSocket` constructor. It defaults to `JsonSocket`. [client-metadata.interface.ts:44-45](packages/microservices/interfaces/client-metadata.interface.ts#L44-L45) [client-tcp.ts:32-36](packages/microservices/client/client-tcp.ts#L32-L36) - `maxBufferSize` is passed only when `socketClass` is exactly the built-in `JsonSocket`; custom socket classes receive no such constructor option. [client-tcp.ts:113-121](packages/microservices/client/client-tcp.ts#L113-L121) For `JsonSocket`, an omitted value defaults to `(512 * 1024 * 1024) / 4` characters. [json-socket.ts:7-11](packages/microservices/helpers/json-socket.ts#L7-L11) [json-socket.ts:21-24](packages/microservices/helpers/json-socket.ts#L21-L24) - With `JsonSocket`, received data accumulates in a string buffer. If its length exceeds `maxBufferSize`, the buffer is cleared and `MaxPacketLengthExceededException` is thrown; the base socket catches this, emits an error, and ends the socket. [json-socket.ts:30-43](packages/microservices/helpers/json-socket.ts#L30-L43) [tcp-socket.ts:54-60](packages/microservices/helpers/tcp-socket.ts#L54-L60) - The interface itself declares no runtime validation for option values. The visible TCP constructor reads the fields and initializes serializer/deserializer without checks. [client-tcp.ts:30-40](packages/microservices/client/client-tcp.ts#L30-L40) # AmqplibQueueOptions **Kind:** Interface **Source:** [`packages/microservices/external/rmq-url.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/rmq-url.interface.ts#L59) **Part of:** [Microservices](subsystem-packages-microservices) `AmqplibQueueOptions` defines RabbitMQ queue configuration options used when declaring or managing queues through the AMQP integration. It covers queue lifecycle behavior, message retention, dead-letter routing, capacity limits, and priority support. ## Properties | Property | Type | |---|---| | `durable` | `boolean` | | `autoDelete` | `boolean` | | `arguments` | `any` | | `messageTtl` | `number` | | `expires` | `number` | | `deadLetterExchange` | `string` | | `deadLetterRoutingKey` | `string` | | `maxLength` | `number` | | `maxPriority` | `number` | ## Diagram ```mermaid graph LR A[AmqplibQueueOptions] --> B[Queue Lifecycle] A --> C[Message Retention] A --> D[Dead-Letter Routing] A --> E[Capacity and Priority] B --> B1[durable] B --> B2[autoDelete] B --> B3[expires] C --> C1[messageTtl] D --> D1[deadLetterExchange] D --> D2[deadLetterRoutingKey] E --> E1[maxLength] E --> E2[maxPriority] A --> F[arguments] ``` ## Usage ```ts import type { AmqplibQueueOptions } from './rmq-url.interface'; const queueOptions: AmqplibQueueOptions = { durable: true, autoDelete: false, arguments: { 'x-queue-type': 'classic', }, messageTtl: 60_000, expires: 86_400_000, deadLetterExchange: 'orders.dlx', deadLetterRoutingKey: 'orders.failed', maxLength: 10_000, maxPriority: 10, }; // Map these options to the AMQP queue declaration options as needed. await channel.assertQueue('orders.created', { durable: queueOptions.durable, autoDelete: queueOptions.autoDelete, arguments: { ...queueOptions.arguments, 'x-message-ttl': queueOptions.messageTtl, 'x-expires': queueOptions.expires, 'x-dead-letter-exchange': queueOptions.deadLetterExchange, 'x-dead-letter-routing-key': queueOptions.deadLetterRoutingKey, 'x-max-length': queueOptions.maxLength, 'x-max-priority': queueOptions.maxPriority, }, }); ``` ## AI Coding Instructions - Preserve RabbitMQ argument names such as `x-message-ttl`, `x-dead-letter-exchange`, and `x-max-priority` when mapping these fields to AMQP options. - Treat `messageTtl` and `expires` as millisecond durations; avoid passing values intended to be seconds. - Configure `deadLetterExchange` and `deadLetterRoutingKey` together, and ensure the referenced dead-letter exchange exists. - Use `durable: true` for queues that must survive broker restarts, and avoid `autoDelete: true` for long-lived production queues. - Keep custom broker-specific configuration in `arguments` without overwriting explicitly mapped queue settings. # Batch **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L887) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { topic: string; partition: number; highWatermark: string; messages: KafkaMessage[]; isEmpty(): boolean; firstOffset(): string | null; lastOffset(): string; offsetLag(): string; offsetLagLow(): string; } ``` # BLOCKED_RMQ_MESSAGE **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L61) **Part of:** [Microservices](subsystem-packages-microservices) ## Signature ```ts function BLOCKED_RMQ_MESSAGE(reason: string) ``` ## Parameters | Name | Type | |---|---| | `reason` | `string` | # ClientsProviderAsyncOptions **Kind:** Interface **Source:** [`packages/microservices/module/interfaces/clients-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/interfaces/clients-module.interface.ts#L21) **Part of:** [Microservices](subsystem-packages-microservices) `ClientsProviderAsyncOptions` configures an asynchronously created microservice client provider. It supports resolving client options from an existing factory, instantiating a factory class, or invoking a factory function with injected dependencies. The optional provider metadata helps Nest register the resulting client under a string or symbol token. ## Properties | Property | Type | |---|---| | `useExisting` | `Type` | | `useClass` | `Type` | | `useFactory` | `(...args: any[]) => Promise | ClientProvider` | | `inject` | `any[]` | | `extraProviders` | `Provider[]` | | `name` | `string | symbol` | ## Diagram ```mermaid graph LR A[ClientsProviderAsyncOptions] --> B{Configuration strategy} B -->|useExisting| C[Existing ClientsModuleOptionsFactory] B -->|useClass| D[New ClientsModuleOptionsFactory] B -->|useFactory| E[Factory Function] F[inject dependencies] --> E G[extraProviders] --> D C --> H[ClientProvider] D --> H E --> H H --> I[name: string or symbol] I --> J[Injectable Microservice Client] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ClientProvider, ClientsModuleOptionsFactory, } from '@nestjs/microservices'; import { ClientsProviderAsyncOptions } from '@nestjs/microservices/module/interfaces/clients-module.interface'; @Injectable() class MessagingClientConfigService implements ClientsModuleOptionsFactory { createClientOptions(): ClientProvider { return { name: 'MESSAGING_CLIENT', transport: 0, // Replace with the appropriate Transport enum value options: { host: 'localhost', port: 3001, }, }; } } const messagingClientOptions: ClientsProviderAsyncOptions = { name: 'MESSAGING_CLIENT', useClass: MessagingClientConfigService, extraProviders: [MessagingClientConfigService], }; // Example registration: // ClientsModule.registerAsync([messagingClientOptions]); ``` ## AI Coding Instructions - Use exactly one configuration strategy: `useExisting`, `useClass`, or `useFactory`; do not combine them for the same client registration. - Ensure the resolved factory returns a valid `ClientProvider`, either directly or through a `Promise`. - Add dependencies required by `useFactory` to `inject`, and ensure those dependencies are available in the importing module. - Use `extraProviders` when the async client factory or its supporting services must be registered alongside the client configuration. - Keep the `name` token consistent with the token used when injecting the resulting microservice client. # DescribeConfigResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L365) **Part of:** [Microservices](subsystem-packages-microservices) `DescribeConfigResponse` represents the response returned after requesting Kafka configuration details for one or more resources. It groups configuration entries, resource-level status information, and broker throttling metadata so callers can inspect successful and failed configuration lookups. ## Properties | Property | Type | |---|---| | `resources` | `{ configEntries: ConfigEntries[]; errorCode: number; errorMessage: string; resourceName: string; resourceType: ConfigResourceTypes; }[]` | | `throttleTime` | `number` | ## Diagram ```mermaid graph LR Client[Kafka client] --> Request[Describe config request] Request --> Broker[Kafka broker] Broker --> Response[DescribeConfigResponse] Response --> Throttle[throttleTime] Response --> Resources[resources[]] Resources --> ResourceName[resourceName] Resources --> ResourceType[resourceType] Resources --> Entries[configEntries: ConfigEntries[]] Resources --> ErrorCode[errorCode] Resources --> ErrorMessage[errorMessage] ``` ## Usage ```ts import type { DescribeConfigResponse } from './kafka.interface'; function logConfigResponse(response: DescribeConfigResponse): void { console.log(`Broker throttle time: ${response.throttleTime}ms`); for (const resource of response.resources) { if (resource.errorCode !== 0) { console.error( `Unable to describe ${resource.resourceName}: ${resource.errorMessage}`, ); continue; } console.log( `Configuration for ${resource.resourceType}:${resource.resourceName}`, ); for (const entry of resource.configEntries) { console.log(`${entry.configName}=${entry.configValue}`); } } } ``` ## AI Coding Instructions - Treat `resources` as a multi-resource response; validate each resource's `errorCode` instead of assuming the entire request succeeded. - Check `errorCode` before reading or acting on `configEntries`, and surface `errorMessage` when a resource lookup fails. - Preserve `resourceType` and `resourceName` together when mapping results to Kafka topics, brokers, or other configurable resources. - Use `throttleTime` for observability and retry/backoff decisions when Kafka brokers are under load. ## How it works `DescribeConfigResponse` is an exported TypeScript interface representing the result type of `Admin.describeConfigs(...)`. The declaration file is intended only to mirror KafkaJS package types, rather than contain NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [packages/microservices/external/kafka.interface.ts:548-551](packages/microservices/external/kafka.interface.ts#L548-L551) - `resources` is an array with one object per described resource. Each object contains: - `resourceName: string` and `resourceType: ConfigResourceTypes`, identifying the resource. `ConfigResourceTypes` permits `UNKNOWN` (`0`), `TOPIC` (`2`), `BROKER` (`4`), and `BROKER_LOGGER` (`8`). [packages/microservices/external/kafka.interface.ts:365-372](packages/microservices/external/kafka.interface.ts#L365-L372) [packages/microservices/external/kafka.interface.ts:295-300](packages/microservices/external/kafka.interface.ts#L295-L300) - `errorCode: number` and `errorMessage: string`. [packages/microservices/external/kafka.interface.ts:366-372](packages/microservices/external/kafka.interface.ts#L366-L372) - `configEntries: ConfigEntries[]`. Each entry has a configuration name and value, default, sensitivity, and read-only flags, a `ConfigSource`, and an array of synonym entries. [packages/microservices/external/kafka.interface.ts:349-357](packages/microservices/external/kafka.interface.ts#L349-L357) - Each synonym records `configName`, `configValue`, and `configSource`. [packages/microservices/external/kafka.interface.ts:359-363](packages/microservices/external/kafka.interface.ts#L359-L363) `ConfigSource` has declared values for unknown, topic, dynamic broker, dynamic default broker, static broker, default, and dynamic broker-logger sources. [packages/microservices/external/kafka.interface.ts:302-310](packages/microservices/external/kafka.interface.ts#L302-L310) - `throttleTime: number` is a top-level field of the response. [packages/microservices/external/kafka.interface.ts:365-374](packages/microservices/external/kafka.interface.ts#L365-L374) `Admin.describeConfigs` requires an object containing `resources: ResourceConfigQuery[]` and `includeSynonyms: boolean`, and its declared return type is `Promise`. A resource query requires a resource `type` and `name`, with optional `configNames`. [packages/microservices/external/kafka.interface.ts:343-347](packages/microservices/external/kafka.interface.ts#L343-L347) [packages/microservices/external/kafka.interface.ts:548-551](packages/microservices/external/kafka.interface.ts#L548-L551) This interface declares data shape only; it contains no executable validation, thrown errors, or side effects. [packages/microservices/external/kafka.interface.ts:365-374](packages/microservices/external/kafka.interface.ts#L365-L374) # EachBatchPayload **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1002) **Part of:** [Microservices](subsystem-packages-microservices) `EachBatchPayload` represents the payload provided to Kafka batch-processing handlers. It exposes the consumed `Batch`, allowing consumers to inspect batch metadata and process the messages it contains as a unit. ## Properties | Property | Type | |---|---| | `batch` | `Batch` | ## Diagram ```mermaid graph LR Consumer[Kafka Consumer Handler] --> Payload[EachBatchPayload] Payload --> Batch[Batch] Batch --> Messages[Kafka Messages] ``` ## Usage ```ts import type { EachBatchPayload } from '@nestjs/microservices'; async function handleBatch(payload: EachBatchPayload) { const { batch } = payload; for (const message of batch.messages) { const value = message.value?.toString(); console.log(`Processing message from ${batch.topic}:`, value); } } ``` ## AI Coding Instructions - Use `payload.batch.messages` to iterate through all messages received in the Kafka batch. - Treat `message.value` as nullable and check for `null` before converting or parsing it. - Use batch metadata such as `batch.topic` and `batch.partition` when logging, routing, or handling failures. - Keep batch handlers idempotent because Kafka may redeliver messages after consumer failures. ## How it works `EachBatchPayload` is an exported TypeScript interface that models the argument passed to an `EachBatchHandler`. This declaration file is intended to represent KafkaJS types only, without NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) An `EachBatchHandler` accepts this payload and must return `Promise`; such a handler can be assigned to the optional `eachBatch` setting of `ConsumerRunConfig`, which can be passed to `Consumer.run()`. [packages/microservices/external/kafka.interface.ts:1025-1035](packages/microservices/external/kafka.interface.ts#L1025-L1035) [packages/microservices/external/kafka.interface.ts:1043-1049](packages/microservices/external/kafka.interface.ts#L1043-L1049) Its members are: - `batch: Batch` exposes the batch’s `topic`, `partition`, `highWatermark`, and `KafkaMessage[]`, plus methods to test whether it is empty and read its first/last offsets and offset-lag values. [packages/microservices/external/kafka.interface.ts:887-897](packages/microservices/external/kafka.interface.ts#L887-L897) - `resolveOffset(offset: string): void` accepts one string offset and has no return value. [packages/microservices/external/kafka.interface.ts:1002-1005](packages/microservices/external/kafka.interface.ts#L1002-L1005) - `heartbeat(): Promise` is asynchronous and resolves with no value. [packages/microservices/external/kafka.interface.ts:1004-1006](packages/microservices/external/kafka.interface.ts#L1004-L1006) - `pause(): () => void` returns a zero-argument function that returns no value. [packages/microservices/external/kafka.interface.ts:1005-1007](packages/microservices/external/kafka.interface.ts#L1005-L1007) - `commitOffsetsIfNecessary(offsets?: Offsets): Promise` optionally accepts offsets and resolves with no value. `Offsets` contains `topics`, each with a topic name and partition/offset pairs. [packages/microservices/external/kafka.interface.ts:1007-1008](packages/microservices/external/kafka.interface.ts#L1007-L1008) [packages/microservices/external/kafka.interface.ts:771-783](packages/microservices/external/kafka.interface.ts#L771-L783) - `uncommittedOffsets(): OffsetsByTopicPartition` returns an object with `topics: TopicOffsets[]`. [packages/microservices/external/kafka.interface.ts:990-992](packages/microservices/external/kafka.interface.ts#L990-L992) [packages/microservices/external/kafka.interface.ts:1007-1009](packages/microservices/external/kafka.interface.ts#L1007-L1009) - `isRunning(): boolean` and `isStale(): boolean` return boolean status values. [packages/microservices/external/kafka.interface.ts:1008-1011](packages/microservices/external/kafka.interface.ts#L1008-L1011) `ConsumerEachBatchPayload` is an alias of `EachBatchPayload`, retained for compatibility with `@types/kafkajs`. [packages/microservices/external/kafka.interface.ts:1019-1023](packages/microservices/external/kafka.interface.ts#L1019-L1023) This is a type declaration: it contains no implementation, runtime validation, explicit thrown errors, or observable runtime side effects. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [packages/microservices/external/kafka.interface.ts:1002-1011](packages/microservices/external/kafka.interface.ts#L1002-L1011) # IClientReconnectOptions **Kind:** Interface **Source:** [`packages/microservices/external/mqtt-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/mqtt-options.interface.ts#L171) **Part of:** [Microservices](subsystem-packages-microservices) `IClientReconnectOptions` defines the MQTT message stores used when an MQTT client reconnects. It provides separate stores for incoming and outgoing packets so message state can be preserved or restored across connection interruptions. ## Properties | Property | Type | |---|---| | `incomingStore` | `any` | | `outgoingStore` | `any` | ## Diagram ```mermaid graph LR Client[MQTT Client] --> Reconnect[IClientReconnectOptions] Reconnect --> Incoming[incomingStore] Reconnect --> Outgoing[outgoingStore] Incoming --> RestoredIncoming[Restored incoming packet state] Outgoing --> ResentOutgoing[Resent pending outgoing packets] ``` ## Usage ```ts import type { IClientReconnectOptions } from './mqtt-options.interface'; const reconnectOptions: IClientReconnectOptions = { incomingStore: new Map(), outgoingStore: new Map(), }; // Pass the stores into the MQTT client reconnect configuration. function configureReconnect(options: IClientReconnectOptions) { return { incomingStore: options.incomingStore, outgoingStore: options.outgoingStore, }; } const mqttReconnectConfig = configureReconnect(reconnectOptions); ``` ## AI Coding Instructions - Provide both `incomingStore` and `outgoingStore` when configuring reconnect behavior. - Use stores that match the MQTT client's expected store implementation; avoid assuming `any` accepts arbitrary incompatible values. - Preserve store instances across reconnect attempts when pending packet state must survive temporary disconnections. - Ensure outgoing stores can retain unacknowledged QoS messages so they can be resent after reconnection. - Integrate these options with the underlying MQTT client configuration rather than handling packet restoration manually. # MatchingAcl **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L479) **Part of:** [Microservices](subsystem-packages-microservices) `MatchingAcl` represents a Kafka ACL entry returned when querying or filtering access-control rules. It combines the resource being protected, the principal and host being evaluated, the allowed or denied operation, and any broker-reported error details. ## Properties | Property | Type | |---|---| | `errorCode` | `number` | | `errorMessage` | `string` | | `resourceType` | `AclResourceTypes` | | `resourceName` | `string` | | `resourcePatternType` | `ResourcePatternTypes` | | `principal` | `string` | | `host` | `string` | | `operation` | `AclOperationTypes` | | `permissionType` | `AclPermissionTypes` | ## Diagram ```mermaid graph LR MatchingAcl["MatchingAcl"] MatchingAcl --> Error["errorCode
errorMessage"] MatchingAcl --> Resource["Kafka Resource"] MatchingAcl --> Subject["Principal and Host"] MatchingAcl --> Permission["Operation and Permission"] Resource --> ResourceType["resourceType: AclResourceTypes"] Resource --> ResourceName["resourceName: string"] Resource --> PatternType["resourcePatternType: ResourcePatternTypes"] Subject --> Principal["principal: string"] Subject --> Host["host: string"] Permission --> Operation["operation: AclOperationTypes"] Permission --> PermissionType["permissionType: AclPermissionTypes"] ``` ## Usage ```ts import { AclOperationTypes, AclPermissionTypes, AclResourceTypes, ResourcePatternTypes, } from '@nestjs/microservices'; import type { MatchingAcl } from '@nestjs/microservices'; const matchingAcl: MatchingAcl = { errorCode: 0, errorMessage: '', resourceType: AclResourceTypes.TOPIC, resourceName: 'orders', resourcePatternType: ResourcePatternTypes.LITERAL, principal: 'User:order-service', host: '*', operation: AclOperationTypes.READ, permissionType: AclPermissionTypes.ALLOW, }; if ( matchingAcl.errorCode === 0 && matchingAcl.permissionType === AclPermissionTypes.ALLOW ) { console.log( `${matchingAcl.principal} can ${matchingAcl.operation} from ${matchingAcl.resourceName}`, ); } ``` ## AI Coding Instructions - Treat `errorCode` and `errorMessage` as broker response metadata; check for non-zero error codes before relying on an ACL result. - Use the Kafka ACL enum values for `resourceType`, `resourcePatternType`, `operation`, and `permissionType`; avoid raw numeric values. - Preserve Kafka principal formatting, such as `User:service-name`, when comparing or constructing ACL-related data. - Account for wildcard hosts (`*`) and resource pattern types when evaluating whether an ACL applies to a request. # MessageHandler **Kind:** Interface **Source:** [`packages/microservices/interfaces/message-handler.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/message-handler.interface.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) `MessageHandler` defines the executable portion of a microservice message pipeline. Its `next` method processes incoming data with optional context and resolves either a direct result or an RxJS `Observable`, while metadata fields identify event handlers and carry framework-specific extras. ## Properties | Property | Type | |---|---| | `next` | `( data: TInput, ctx?: TContext, ) => Promise> | Promise` | | `isEventHandler` | `boolean` | | `extras` | `Record` | ## Diagram ```mermaid graph LR A[Incoming message data] --> B[MessageHandler.next] C[Optional context] --> B B --> D{Handler result} D --> E[Promise] D --> F[Promise>] G[isEventHandler] --> H[Message routing behavior] I[extras] --> J[Additional handler metadata] ``` ## Usage ```ts import { Observable, of } from 'rxjs'; import { MessageHandler } from './interfaces/message-handler.interface'; interface CreateUserCommand { email: string; } interface User { id: string; email: string; } const createUserHandler: MessageHandler< CreateUserCommand, User, { requestId: string } > = { isEventHandler: false, extras: { transport: 'tcp', pattern: 'users.create', }, async next(data, ctx): Promise> { console.log(`Creating user for request ${ctx?.requestId}`); const user = { id: crypto.randomUUID(), email: data.email, }; return of(user); }, }; // The framework invokes the handler when a matching message arrives. const result$ = await createUserHandler.next( { email: 'user@example.com' }, { requestId: 'req-123' }, ); ``` ## AI Coding Instructions - Implement `next` as an async function that accepts the message payload first and optional transport or request context second. - Return either `Promise` for single direct results or `Promise>` when the response should be streamed. - Set `isEventHandler` to `true` for fire-and-forget event consumers; use `false` for request-response handlers. - Store transport-specific or framework-specific metadata in `extras` rather than adding ad hoc handler properties. - Preserve the generic input, result, and context types so message contracts remain type-safe across the microservice pipeline. ## How it works `MessageHandler` is a public callable TypeScript interface for a microservice message callback. Its three generic types default to `any`. [message-handler.interface.ts:3-6] - The handler is invoked with required `data: TInput` and optional `ctx?: TContext`. It must return `Promise` or `Promise>`; a direct, non-Promise result is not part of this interface. [message-handler.interface.ts:6-10] - It may carry an optional `next` handler with the same parameters and return type. [message-handler.interface.ts:11-14] - It may carry an optional `isEventHandler` boolean and optional `extras` object whose string keys map to `any` values. [message-handler.interface.ts:15-16] `Server.addHandler()` mutates the callback by assigning its `isEventHandler` and `extras` properties before registration. When an event handler is registered for a pattern that already has a handler, it walks that handler’s `next` chain and appends the callback at the tail; otherwise, it replaces or creates the map entry for the normalized pattern. [server.ts:139-158] For request-scoped event handlers, `ListenersController` checks `handlerRef.next`, invokes it with the original arguments, converts both the current and next results to observables, and returns a `forkJoin` containing both results. Without `next`, it returns the current value unchanged. [listeners-controller.ts:187-202] The request-scoped handler calls this logic only when its `isEventHandler` argument is true. [listeners-controller.ts:273-281] The interface itself contains no runtime implementation, input validation, error handling, or direct side effects; these members are declarations only. [message-handler.interface.ts:6-17] # MqttEvents **Kind:** Type **Source:** [`packages/microservices/events/mqtt.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/mqtt.events.ts#L29) **Part of:** [Microservices](subsystem-packages-microservices) MQTT events map for the MQTT client. Key is the event name and value is the corresponding callback function. `MqttEvents` defines the event-to-callback map used by the MQTT client integration. Each key represents an MQTT client event name, and its value is the handler invoked when that event is emitted. Use this type to keep MQTT lifecycle, message, and error handling centralized and consistently typed. ## Definition ```ts { connect: OnPacketCallback; reconnect: VoidCallback; disconnect: OnPacketCallback; close: VoidCallback; offline: VoidCallback; end: VoidCallback; error: OnErrorCallback; packetreceive: OnPacketCallback; packetsend: OnPacketCallback; } ``` ## Diagram ```mermaid graph LR Client[MQTT Client] -->|emits event| Events[MqttEvents map] Events --> Connect[connect handler] Events --> Message[message handler] Events --> Error[error handler] Events --> Close[close handler] ``` ## Usage ```ts import type { MqttEvents } from './mqtt.events'; const mqttEvents: MqttEvents = { connect: () => { console.log('Connected to MQTT broker'); }, message: (topic, payload) => { console.log(`Received message on ${topic}: ${payload.toString()}`); }, error: (error) => { console.error('MQTT client error:', error); }, close: () => { console.log('MQTT connection closed'); }, }; // Register handlers with the MQTT client. client.on('connect', mqttEvents.connect); client.on('message', mqttEvents.message); client.on('error', mqttEvents.error); client.on('close', mqttEvents.close); ``` ## AI Coding Instructions - Keep event names aligned with the events emitted by the configured MQTT client library. - Define handlers in a `MqttEvents` object rather than scattering anonymous callbacks throughout connection setup code. - Handle `error` events explicitly to avoid unhandled MQTT client failures. - Treat message payloads as binary data and convert or parse them only after validating the topic and expected format. - Register the event map when creating the MQTT client so lifecycle handlers are attached before connection activity begins. # MqttEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/mqtt.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/mqtt.events.ts#L12) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `CONNECT` - `RECONNECT` - `DISCONNECT` - `CLOSE` - `OFFLINE` - `END` - `ERROR` - `PACKETRECEIVE` - `PACKETSEND` # Partitioners **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L139) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { DefaultPartitioner: DefaultPartitioner; LegacyPartitioner: LegacyPartitioner; JavaCompatiblePartitioner: DefaultPartitioner; } ``` # ProducerConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L110) **Part of:** [Microservices](subsystem-packages-microservices) `ProducerConfig` defines Kafka producer-specific options used when configuring a microservice client. It controls partitioning, retries, metadata refresh behavior, topic creation, and transactional delivery guarantees. ## Properties | Property | Type | |---|---| | `createPartitioner` | `ICustomPartitioner` | | `retry` | `RetryOptions` | | `metadataMaxAge` | `number` | | `allowAutoTopicCreation` | `boolean` | | `idempotent` | `boolean` | | `transactionalId` | `string` | | `transactionTimeout` | `number` | | `maxInFlightRequests` | `number` | ## Diagram ```mermaid graph LR A[Kafka Microservice Client] --> B[ProducerConfig] B --> C[Custom Partitioner] B --> D[Retry Options] B --> E[Topic Metadata Settings] B --> F[Idempotent Producer] B --> G[Transactional Producer] G --> H[transactionalId] G --> I[transactionTimeout] B --> J[maxInFlightRequests] ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import type { ProducerConfig } from '@nestjs/microservices/external/kafka.interface'; const producerConfig: ProducerConfig = { retry: { retries: 5, initialRetryTime: 300, }, metadataMaxAge: 300_000, allowAutoTopicCreation: false, idempotent: true, transactionalId: 'orders-producer-1', transactionTimeout: 30_000, maxInFlightRequests: 1, }; const kafkaOptions = { transport: Transport.KAFKA, options: { client: { clientId: 'orders-service', brokers: ['localhost:9092'], }, producer: producerConfig, }, }; ``` ## AI Coding Instructions - Configure `idempotent: true` with a stable `transactionalId` when producers require exactly-once or transactional delivery semantics. - Keep `maxInFlightRequests` low, typically `1`, when ordering and idempotent delivery guarantees are required. - Set `allowAutoTopicCreation: false` in production and provision topics explicitly through infrastructure tooling. - Use `retry` settings appropriate for broker availability and transient network failures; avoid excessively aggressive retry loops. - Provide `createPartitioner` only when default Kafka partition selection does not meet message routing requirements. ## How it works `ProducerConfig` is an exported TypeScript interface that describes the optional configuration argument accepted by `Kafka.producer(config?)`. The file states that its declarations are intended to represent KafkaJS package types only. [kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [kafka.interface.ts:19-24](packages/microservices/external/kafka.interface.ts#L19-L24) All of its properties are optional, so the type itself requires no fields. [kafka.interface.ts:110-119](packages/microservices/external/kafka.interface.ts#L110-L119) Its fields are: - `createPartitioner?: ICustomPartitioner` — a zero-argument function returning a partition-selection function. That returned function receives `topic`, `partitionMetadata`, and `message`, and returns a partition number. [kafka.interface.ts:111](packages/microservices/external/kafka.interface.ts#L111) [kafka.interface.ts:129-135](packages/microservices/external/kafka.interface.ts#L129-L135) - `retry?: RetryOptions` — retry settings: optional `maxRetryTime`, `initialRetryTime`, `factor`, `multiplier`, `retries`, and an optional asynchronous `restartOnFailure` callback receiving an `Error` and returning `Promise`. [kafka.interface.ts:112](packages/microservices/external/kafka.interface.ts#L112) [kafka.interface.ts:253-260](packages/microservices/external/kafka.interface.ts#L253-L260) - `metadataMaxAge?: number`, `allowAutoTopicCreation?: boolean`, `idempotent?: boolean`, `transactionalId?: string`, `transactionTimeout?: number`, and `maxInFlightRequests?: number`. [kafka.interface.ts:113-118](packages/microservices/external/kafka.interface.ts#L113-L118) Nest exposes this type as `KafkaOptions.options.producer`. [microservice-configuration.interface.ts:333-355](packages/microservices/interfaces/microservice-configuration.interface.ts#L333-L355) The Kafka client creates a producer with `this.options.producer || {}`, then registers producer event listeners and connects it. [client-kafka.ts:184-186](packages/microservices/client/client-kafka.ts#L184-L186) The Kafka server passes `this.options.producer` to `producer()`, registers producer event listeners, and connects the resulting producer. [server-kafka.ts:107-118](packages/microservices/server/server-kafka.ts#L107-L118) This interface contains no executable validation, error handling, or side effects. The observable configuration interpretation, validation, defaults, and errors belong to the externally declared KafkaJS `Kafka.producer()` implementation rather than code in this repository. [kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [kafka.interface.ts:19-24](packages/microservices/external/kafka.interface.ts#L19-L24) # RecordMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L748) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { topicName: string; partition: number; errorCode: number; offset?: string; timestamp?: string; baseOffset?: string; logAppendTime?: string; logStartOffset?: string; } ``` # RequestContext **Kind:** Interface **Source:** [`packages/microservices/interfaces/request-context.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/request-context.interface.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) `RequestContext` describes the normalized payload passed through a microservice request handler. It groups the message `pattern`, request `data`, and transport-specific `context` so handlers can process incoming requests consistently across transports. ## Properties | Property | Type | |---|---| | `pattern` | `string | Record` | | `data` | `TData` | | `context` | `TContext` | ## Diagram ```mermaid graph LR Client[Client Request] --> Pattern[pattern
Routing pattern] Client --> Data[data
Request payload] Transport[Microservice Transport] --> Context[context
Transport metadata] Pattern --> RequestContext[RequestContext] Data --> RequestContext Context --> RequestContext RequestContext --> Handler[Message Handler] ``` ## Usage ```ts import type { RequestContext } from './interfaces/request-context.interface'; interface CreateUserData { email: string; name: string; } interface TransportContext { correlationId: string; headers?: Record; } function handleCreateUser( request: RequestContext, ) { const { pattern, data, context } = request; console.log(`Handling pattern: ${String(pattern)}`); console.log(`Correlation ID: ${context.correlationId}`); return { email: data.email, name: data.name, }; } const request: RequestContext = { pattern: 'users.create', data: { email: 'ada@example.com', name: 'Ada Lovelace', }, context: { correlationId: 'req-123', }, }; handleCreateUser(request); ``` ## AI Coding Instructions - Use generic type parameters for `data` and `context` to preserve payload and transport metadata types. - Treat `pattern` as either a string route or a structured object when supporting complex message routing. - Keep business-specific payload validation in handlers or validation layers rather than expanding this shared interface. - Pass transport-specific metadata through `context`, such as headers, correlation IDs, acknowledgements, or connection details. - Avoid assuming a specific transport context shape unless the handler constrains `TContext` explicitly. ## How it works `RequestContext` is an exported generic interface for an RPC request-shaped object. `TData` defaults to `any`; `TContext` defaults to `any` and is constrained to extend `BaseRpcContext`. [request-context.interface.ts:3-6](packages/microservices/interfaces/request-context.interface.ts#L3-L6) An implementation must expose: - `pattern`, typed as either a `string` or `Record`. [request-context.interface.ts:7](packages/microservices/interfaces/request-context.interface.ts#L7) - `data`, typed as `TData`. [request-context.interface.ts:8](packages/microservices/interfaces/request-context.interface.ts#L8) - An optional `context` property typed as `TContext`. [request-context.interface.ts:9](packages/microservices/interfaces/request-context.interface.ts#L9) - `getData()`, `getPattern()`, and `getContext()` methods that return the corresponding declared types; notably, `getContext()` has return type `TContext` even though the `context` property is optional. [request-context.interface.ts:11-13](packages/microservices/interfaces/request-context.interface.ts#L11-L13) The `TContext` constraint means a typed context can inherit `BaseRpcContext`’s argument accessors: `getArgs()` returns its stored arguments, and `getArgByIndex(index)` returns the argument at that index. [base-rpc.context.ts:4-5](packages/microservices/ctx-host/base-rpc.context.ts#L4-L5) [base-rpc.context.ts:10-12](packages/microservices/ctx-host/base-rpc.context.ts#L10-L12) [base-rpc.context.ts:18-20](packages/microservices/ctx-host/base-rpc.context.ts#L18-L20) `RequestContextHost` is the concrete class in this package that implements this contract. Its constructor stores readonly `pattern`, `data`, and `context` values, and each getter returns the stored value without transformation. [request-context-host.ts:7-15](packages/microservices/context/request-context-host.ts#L7-L15) [request-context-host.ts:26-36](packages/microservices/context/request-context-host.ts#L26-L36) Its static `create()` accepts a pattern, data, and `BaseRpcContext` subtype, constructs a host, and returns it typed as `RequestContext`. [request-context-host.ts:17-24](packages/microservices/context/request-context-host.ts#L17-L24) For request-scoped microservice handlers, `ListenersController` creates a `RequestContextHost` from the handler’s pattern, first argument (`data`), and second argument cast as `BaseRpcContext` when the first argument is not already a host. [listeners-controller.ts:238-255](packages/microservices/listeners-controller.ts#L238-L255) It then obtains a context ID from that request object. [listeners-controller.ts:302-306](packages/microservices/listeners-controller.ts#L302-L306) If the request has no existing request-context ID property, this path defines a non-enumerable, non-writable, non-configurable ID property on it, registers either the ID payload or the request object merged with that payload as the request-provider value, and returns the ID. [listeners-controller.ts:307-320](packages/microservices/listeners-controller.ts#L307-L320) The interface itself declares no validation, error handling, construction logic, or side effects. [request-context.interface.ts:3-14](packages/microservices/interfaces/request-context.interface.ts#L3-L14) # RequestTimeoutEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L421) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ apiKey: number; apiName: string; apiVersion: number; broker: string; clientId: string; correlationId: number; createdAt: number; pendingDuration: number; sentAt: number; }> ``` # RmqUrl **Kind:** Interface **Source:** [`packages/microservices/external/rmq-url.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/rmq-url.interface.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) `RmqUrl` defines the connection components required to build or represent a RabbitMQ broker URL. It captures broker location, authentication, virtual host, and AMQP connection tuning values used by the microservices transport layer. ## Properties | Property | Type | |---|---| | `protocol` | `string` | | `hostname` | `string` | | `port` | `number` | | `username` | `string` | | `password` | `string` | | `locale` | `string` | | `frameMax` | `number` | | `heartbeat` | `number` | | `vhost` | `string` | ## Diagram ```mermaid graph LR RmqUrl["RmqUrl"] RmqUrl --> Protocol["protocol: string"] RmqUrl --> Hostname["hostname: string"] RmqUrl --> Port["port: number"] RmqUrl --> Credentials["username / password"] RmqUrl --> VHost["vhost: string"] RmqUrl --> Locale["locale: string"] RmqUrl --> Tuning["frameMax / heartbeat"] Credentials --> Connection["RabbitMQ Connection"] VHost --> Connection Tuning --> Connection Protocol --> Connection Hostname --> Connection Port --> Connection ``` ## Usage ```ts import type { RmqUrl } from './rmq-url.interface'; const rabbitMqConfig: RmqUrl = { protocol: 'amqp', hostname: 'localhost', port: 5672, username: 'guest', password: 'guest', locale: 'en_US', frameMax: 0, heartbeat: 60, vhost: '/', }; const connectionUrl = `${rabbitMqConfig.protocol}://` + `${encodeURIComponent(rabbitMqConfig.username)}:` + `${encodeURIComponent(rabbitMqConfig.password)}@` + `${rabbitMqConfig.hostname}:${rabbitMqConfig.port}` + `${rabbitMqConfig.vhost}`; ``` ## AI Coding Instructions - Keep all fields populated when constructing an `RmqUrl`; this interface does not mark connection settings as optional. - Use `amqp` or `amqps` for `protocol` depending on whether the RabbitMQ broker requires TLS. - Encode `username` and `password` before interpolating them into a connection URI, especially when they contain reserved URL characters. - Preserve `vhost`, `heartbeat`, and `frameMax` values when passing configuration into RabbitMQ transport or connection setup code. - Avoid hardcoding credentials in source files; populate `RmqUrl` from validated environment or configuration values. ## How it works - `RmqUrl` is an exported, public TypeScript interface for the object form of an RMQ connection URL. It declares only optional properties and has no methods or runtime implementation. [packages/microservices/external/rmq-url.interface.ts:4-17] - Its optional fields are: - `protocol`, `hostname`, `username`, `password`, `locale`, and `vhost` as strings. [packages/microservices/external/rmq-url.interface.ts:8-13,16] - `port`, `frameMax`, and `heartbeat` as numbers. [packages/microservices/external/rmq-url.interface.ts:10,14-15] - `RmqOptions.options.urls` accepts either an array of URL strings or an array of `RmqUrl` objects; the adjacent documentation says these are connection URLs tried in order. [packages/microservices/interfaces/microservice-configuration.interface.ts:222-228] - `ServerRMQ` stores this setting as `string[] | RmqUrl[]`. Its constructor reads `options.urls` and falls back to an array containing the RMQ default URL when the setting is falsy. [packages/microservices/server/server-rmq.ts:67,77-85] - When creating the RMQ client, `ServerRMQ` passes the stored URL array directly as the first argument to `amqp-connection-manager`’s `connect` call. [packages/microservices/server/server-rmq.ts:169-176] - No validation, normalization, field-level parsing, errors, or side effects are declared by `RmqUrl` itself. In the visible `ServerRMQ` path, individual `RmqUrl` fields are not inspected before the array is passed to `connect`. [packages/microservices/external/rmq-url.interface.ts:7-17] [packages/microservices/server/server-rmq.ts:169-176] # TcpEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/tcp.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/tcp.events.ts#L15) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `ERROR` - `CONNECT` - `END` - `CLOSE` - `TIMEOUT` - `DRAIN` - `LOOKUP` - `LISTENING` # AclFilter **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L469) **Part of:** [Microservices](subsystem-packages-microservices) `AclFilter` defines criteria for selecting Kafka ACL entries when querying, deleting, or managing permissions. It combines resource, principal, host, operation, and permission attributes to describe the ACL records that should match within the Kafka integration layer. ## Properties | Property | Type | |---|---| | `resourceType` | `AclResourceTypes` | | `resourceName` | `string` | | `resourcePatternType` | `ResourcePatternTypes` | | `principal` | `string` | | `host` | `string` | | `operation` | `AclOperationTypes` | | `permissionType` | `AclPermissionTypes` | ## Diagram ```mermaid graph LR A[AclFilter] --> B[resourceType: AclResourceTypes] A --> C[resourceName: string] A --> D[resourcePatternType: ResourcePatternTypes] A --> E[principal: string] A --> F[host: string] A --> G[operation: AclOperationTypes] A --> H[permissionType: AclPermissionTypes] B --> I[Kafka Resource] E --> J[Kafka Principal] G --> K[Allowed Operation] H --> L[Permission Rule] ``` ## Usage ```ts import { AclFilter, AclOperationTypes, AclPermissionTypes, AclResourceTypes, ResourcePatternTypes, } from '@nestjs/microservices'; const topicReadFilter: AclFilter = { resourceType: AclResourceTypes.TOPIC, resourceName: 'orders', resourcePatternType: ResourcePatternTypes.LITERAL, principal: 'User:order-service', host: '*', operation: AclOperationTypes.READ, permissionType: AclPermissionTypes.ALLOW, }; // Pass the filter to the Kafka admin client when listing or deleting ACLs. const matchingAcls = await kafkaAdmin.describeAcls(topicReadFilter); ``` ## AI Coding Instructions - Use the Kafka enum values for `resourceType`, `resourcePatternType`, `operation`, and `permissionType`; do not use arbitrary strings. - Set `resourceName` and `principal` to the exact Kafka resource and principal identifiers expected by the broker. - Use `host: '*'` when the ACL should apply from any client host; use a specific host only when network restrictions are required. - Ensure `resourcePatternType` matches the intended resource matching behavior, such as literal versus prefixed topic names. - Reuse the same `AclFilter` shape for ACL lookup and deletion operations so the targeted permissions remain consistent. # AclResourceTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L285) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `UNKNOWN` - `ANY` - `TOPIC` - `GROUP` - `CLUSTER` - `TRANSACTIONAL_ID` - `DELEGATION_TOKEN` # AmqpConnectionManagerSocketOptions **Kind:** Interface **Source:** [`packages/microservices/external/rmq-url.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/rmq-url.interface.ts#L47) **Part of:** [Microservices](subsystem-packages-microservices) `AmqpConnectionManagerSocketOptions` configures how an AMQP connection manager discovers RabbitMQ servers and maintains its socket connection. It defines reconnect and heartbeat timing, AMQP connection settings, and client metadata used when establishing connections. ## Properties | Property | Type | |---|---| | `reconnectTimeInSeconds` | `number` | | `heartbeatIntervalInSeconds` | `number` | | `findServers` | `() => string | string[]` | | `connectionOptions` | `AmqpConnectionOptions` | | `clientProperties` | `ClientProperties` | ## Diagram ```mermaid graph LR App[Application / Microservice] --> Options[AmqpConnectionManagerSocketOptions] Options --> Discovery[findServers()] Discovery --> Servers[AMQP Server URL(s)] Options --> Reconnect[reconnectTimeInSeconds] Options --> Heartbeat[heartbeatIntervalInSeconds] Options --> Connection[connectionOptions] Options --> Properties[clientProperties] Servers --> Manager[AMQP Connection Manager] Reconnect --> Manager Heartbeat --> Manager Connection --> Manager Properties --> Manager Manager --> RabbitMQ[RabbitMQ Cluster] ``` ## Usage ```ts import type { AmqpConnectionManagerSocketOptions, } from './rmq-url.interface'; const socketOptions: AmqpConnectionManagerSocketOptions = { reconnectTimeInSeconds: 5, heartbeatIntervalInSeconds: 30, findServers: () => [ 'amqp://rabbitmq-1:5672', 'amqp://rabbitmq-2:5672', ], connectionOptions: { username: process.env.RABBITMQ_USERNAME, password: process.env.RABBITMQ_PASSWORD, vhost: process.env.RABBITMQ_VHOST ?? '/', }, clientProperties: { connection_name: 'orders-service', }, }; // Pass socketOptions to the AMQP/RabbitMQ connection setup. ``` ## AI Coding Instructions - Return one or more valid AMQP server URLs from `findServers`; use multiple URLs for clustered RabbitMQ deployments. - Keep `reconnectTimeInSeconds` and `heartbeatIntervalInSeconds` positive and appropriate for the service reliability requirements. - Store credentials in environment variables or a secrets manager rather than hardcoding them in `connectionOptions`. - Set a meaningful `clientProperties.connection_name` value to make RabbitMQ management and connection debugging easier. - Ensure `connectionOptions` matches the AMQP client library's supported connection option format. # Assigner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L243) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { name: string; version: number; assign(group: { members: GroupMember[]; topics: string[]; }): Promise; protocol(subscription: { topics: string[] }): GroupState; } ``` # BrokerMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L651) **Part of:** [Microservices](subsystem-packages-microservices) `BrokerMetadata` represents Kafka cluster metadata returned by the microservices Kafka transport layer. It combines the list of available brokers with per-topic and per-partition metadata, allowing clients to discover broker endpoints and topic partition status. ## Properties | Property | Type | |---|---| | `brokers` | `Array<{ nodeId: number; host: string; port: number; rack?: string }>` | | `topicMetadata` | `Array<{ topicErrorCode: number; topic: string; partitionMetadata: PartitionMetadata[]; }>` | ## Diagram ```mermaid graph LR BM[BrokerMetadata] B[brokers] TM[topicMetadata] BM --> B BM --> TM B --> Broker["Broker endpoint
nodeId, host, port, rack?"] TM --> Topic["Topic metadata
topic, topicErrorCode"] Topic --> Partitions["PartitionMetadata[]"] ``` ## Usage ```ts import type { BrokerMetadata } from './kafka.interface'; function logClusterMetadata(metadata: BrokerMetadata): void { for (const broker of metadata.brokers) { console.log( `Broker ${broker.nodeId} is available at ${broker.host}:${broker.port}`, ); } for (const topicMetadata of metadata.topicMetadata) { if (topicMetadata.topicErrorCode !== 0) { console.warn( `Unable to read metadata for topic "${topicMetadata.topic}"`, ); continue; } console.log( `Topic "${topicMetadata.topic}" has ` + `${topicMetadata.partitionMetadata.length} partition(s)`, ); } } ``` ## AI Coding Instructions - Treat `topicErrorCode` as a Kafka protocol status code; verify it before relying on `partitionMetadata`. - Use `nodeId` as the stable broker identifier, and use `host` plus `port` only for connection endpoints. - Handle the optional `rack` field defensively because rack-aware metadata may not be configured. - Keep broker and topic metadata aligned with Kafka protocol responses; do not assume every requested topic has valid partition metadata. - Reuse `PartitionMetadata` when extending topic-level metadata rather than duplicating partition fields. ## How it works `BrokerMetadata` is an exported TypeScript interface in a file explicitly intended to represent KafkaJS package types rather than NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) It describes metadata with two required arrays: - `brokers`: broker records containing required numeric `nodeId`, string `host`, and numeric `port`; a broker record may also contain a string `rack`. [packages/microservices/external/kafka.interface.ts:651-652](packages/microservices/external/kafka.interface.ts#L651-L652) - `topicMetadata`: topic records containing a numeric `topicErrorCode`, string `topic`, and `partitionMetadata` array. [packages/microservices/external/kafka.interface.ts:653-657](packages/microservices/external/kafka.interface.ts#L653-L657) Each partition record has error code, partition ID, leader ID, replica IDs, and in-sync replica IDs; `offlineReplicas` is optional. [packages/microservices/external/kafka.interface.ts:151-158](packages/microservices/external/kafka.interface.ts#L151-L158) It is the resolved type returned by `Cluster.metadata()` and by `Broker.metadata(topics)`. The cluster method takes no arguments, while the broker method requires a string array of topic names. [packages/microservices/external/kafka.interface.ts:199-201](packages/microservices/external/kafka.interface.ts#L199-L201) [packages/microservices/external/kafka.interface.ts:667-672](packages/microservices/external/kafka.interface.ts#L667-L672) The interface declaration contains no implementation, runtime validation, thrown errors, or side effects. [packages/microservices/external/kafka.interface.ts:651-658](packages/microservices/external/kafka.interface.ts#L651-L658) # ConfigEntries **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L349) **Part of:** [Microservices](subsystem-packages-microservices) `ConfigEntries` represents a single Kafka configuration entry returned or managed through the microservices Kafka integration. It captures the configuration value, its origin, mutability, sensitivity, default status, and any equivalent configuration synonyms. ## Properties | Property | Type | |---|---| | `configName` | `string` | | `configValue` | `string` | | `isDefault` | `boolean` | | `configSource` | `ConfigSource` | | `isSensitive` | `boolean` | | `readOnly` | `boolean` | | `configSynonyms` | `ConfigSynonyms[]` | ## Diagram ```mermaid graph LR ConfigEntries[ConfigEntries] ConfigEntries --> Name[configName: string] ConfigEntries --> Value[configValue: string] ConfigEntries --> Source[configSource: ConfigSource] ConfigEntries --> Default[isDefault: boolean] ConfigEntries --> Sensitive[isSensitive: boolean] ConfigEntries --> ReadOnly[readOnly: boolean] ConfigEntries --> Synonyms[configSynonyms: ConfigSynonyms[]] ``` ## Usage ```ts import type { ConfigEntries, ConfigSource, ConfigSynonyms, } from './kafka.interface'; const retentionConfig: ConfigEntries = { configName: 'retention.ms', configValue: '604800000', isDefault: false, configSource: ConfigSource.DYNAMIC_TOPIC_CONFIG, isSensitive: false, readOnly: false, configSynonyms: [ { configName: 'retention.ms', configValue: '604800000', configSource: ConfigSource.DYNAMIC_TOPIC_CONFIG, } as ConfigSynonyms, ], }; if (!retentionConfig.readOnly && !retentionConfig.isSensitive) { console.log( `${retentionConfig.configName} is set to ${retentionConfig.configValue}`, ); } ``` ## AI Coding Instructions - Preserve Kafka-provided metadata such as `configSource`, `isDefault`, and `readOnly` when mapping admin-client configuration responses. - Do not log or expose `configValue` when `isSensitive` is `true`. - Check `readOnly` before attempting to update a configuration entry through Kafka Admin APIs. - Treat `configSynonyms` as alternate or inherited values; use the primary `configValue` as the effective configuration value. - Use the corresponding `ConfigSource` and `ConfigSynonyms` types from `kafka.interface.ts` rather than replacing them with loose strings or objects. # ConfigSource **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L302) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `UNKNOWN` - `TOPIC_CONFIG` - `DYNAMIC_BROKER_CONFIG` - `DYNAMIC_DEFAULT_BROKER_CONFIG` - `STATIC_BROKER_CONFIG` - `DEFAULT_CONFIG` - `DYNAMIC_BROKER_LOGGER_CONFIG` # ConsumerGroupJoinEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L942) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ duration: number; groupId: string; isLeader: boolean; leaderId: string; groupProtocol: string; memberId: string; memberAssignment: IMemberAssignment; }> ``` # ConsumerReceivedUnsubscribedTopicsEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L981) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ groupId: string; generationId: number; memberId: string; assignedTopics: string[]; topicsSubscribed: string[]; topicsNotSubscribed: string[]; }> ``` # ConsumerRunConfig **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1028) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; eachBatch?: EachBatchHandler; eachMessage?: EachMessageHandler; } ``` # CoordinatorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L190) **Part of:** [Microservices](subsystem-packages-microservices) `CoordinatorMetadata` represents the result of discovering a Kafka group coordinator. It includes an `errorCode` for the lookup operation and, when successful, the coordinator broker's node ID, host, and port for subsequent group-related requests. ## Properties | Property | Type | |---|---| | `errorCode` | `number` | | `coordinator` | `{ nodeId: number; host: string; port: number; }` | ## Diagram ```mermaid graph LR Client[Kafka Client] --> Lookup[Find Group Coordinator] Lookup --> Metadata[CoordinatorMetadata] Metadata --> Error[errorCode: number] Metadata --> Coordinator[coordinator] Coordinator --> NodeId[nodeId: number] Coordinator --> Host[host: string] Coordinator --> Port[port: number] ``` ## Usage ```ts import type { CoordinatorMetadata } from './kafka.interface'; function getCoordinatorAddress(metadata: CoordinatorMetadata): string | undefined { if (metadata.errorCode !== 0) { console.error(`Coordinator lookup failed with code ${metadata.errorCode}`); return undefined; } const { host, port } = metadata.coordinator; return `${host}:${port}`; } const metadata: CoordinatorMetadata = { errorCode: 0, coordinator: { nodeId: 2, host: 'kafka-broker.internal', port: 9092, }, }; const coordinatorAddress = getCoordinatorAddress(metadata); // "kafka-broker.internal:9092" ``` ## AI Coding Instructions - Check `errorCode` before using `coordinator`; a non-zero code indicates the coordinator lookup did not succeed. - Use `coordinator.host` and `coordinator.port` together when creating requests to the coordinator broker. - Preserve the broker `nodeId` when caching or correlating coordinator connections. - Treat coordinator information as refreshable metadata, since Kafka may rebalance or move a group coordinator between brokers. ## How it works `CoordinatorMetadata` is an exported TypeScript interface in the file’s KafkaJS type declarations, rather than an implementation with runtime logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [packages/microservices/external/kafka.interface.ts:190-197](packages/microservices/external/kafka.interface.ts#L190-L197) It describes metadata with two required fields: - `errorCode`: a `number`. [packages/microservices/external/kafka.interface.ts:190-192](packages/microservices/external/kafka.interface.ts#L190-L192) - `coordinator`: a required object identifying a coordinator node through: - `nodeId`: `number` - `host`: `string` - `port`: `number` [packages/microservices/external/kafka.interface.ts:192-197](packages/microservices/external/kafka.interface.ts#L192-L197) Within this declaration file, `Cluster.findGroupCoordinatorMetadata` accepts an object containing a required `groupId: string` and returns `Promise`. [packages/microservices/external/kafka.interface.ts:199-220](packages/microservices/external/kafka.interface.ts#L199-L220) The interface declares no validation, error handling, or side effects. [packages/microservices/external/kafka.interface.ts:190-197](packages/microservices/external/kafka.interface.ts#L190-L197) # EventOrMessageListenerDefinition **Kind:** Interface **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L21) **Part of:** [Microservices](subsystem-packages-microservices) `EventOrMessageListenerDefinition` describes a discovered microservice listener method and the metadata required to register it with a transport strategy. It unifies request-response message handlers and event handlers by storing their patterns, callback target, transport, and additional transport-specific options. ## Properties | Property | Type | |---|---| | `patterns` | `PatternMetadata[]` | | `methodKey` | `string` | | `isEventHandler` | `boolean` | | `targetCallback` | `(...args: any[]) => any` | | `transport` | `Transport` | | `extras` | `Record` | ## Diagram ```mermaid graph LR Explorer[ListenerMetadataExplorer] --> Definition[EventOrMessageListenerDefinition] Definition --> Patterns[patterns: PatternMetadata[]] Definition --> Method[methodKey: string] Definition --> Event[isEventHandler: boolean] Definition --> Callback[targetCallback] Definition --> Transport[transport: Transport] Definition --> Extras[extras: Record] Patterns --> Server[Microservice Server] Callback --> Server Transport --> Server Extras --> Server ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import type { EventOrMessageListenerDefinition } from './listener-metadata-explorer'; const listener: EventOrMessageListenerDefinition = { patterns: [ { cmd: 'get_user', }, ], methodKey: 'getUser', isEventHandler: false, targetCallback: async (data: { id: string }) => { return { id: data.id, name: 'Ada Lovelace' }; }, transport: Transport.TCP, extras: { queue: 'users', }, }; // A listener explorer or server adapter can use this metadata to bind // `targetCallback` to each configured pattern for the selected transport. ``` ## AI Coding Instructions - Preserve the distinction between message handlers and event handlers: `isEventHandler: false` expects a response, while `true` represents a fire-and-forget event listener. - Treat `patterns` as the authoritative routing metadata; a single listener may support multiple patterns. - Keep `targetCallback` bound to the correct controller/provider instance before invoking it, especially when extracted from a class prototype. - Use `transport` and `extras` together when registering handlers, since `extras` may contain adapter-specific configuration such as queue or subscription options. - Avoid narrowing `extras` globally; validate or cast its values within the transport-specific integration layer. ## How it works ## `EventOrMessageListenerDefinition` `EventOrMessageListenerDefinition` is an exported TypeScript interface describing metadata extracted for one controller method marked as a microservice event or message handler. It contains the handler’s patterns, method name, handler callback, event/message classification, and optional transport-specific metadata. [`packages/microservices/listener-metadata-explorer.ts:21-28`](packages/microservices/listener-metadata-explorer.ts#L21-L28) # KafkaJSRequestTimeoutErrorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1304) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSRequestTimeoutErrorMetadata` describes diagnostic timing and routing details for a KafkaJS request that exceeded its timeout. It captures the target broker, client identity, correlation ID, and timestamps needed to calculate how long the request remained pending. ## Properties | Property | Type | |---|---| | `broker` | `string` | | `clientId` | `string` | | `correlationId` | `number` | | `createdAt` | `number` | | `sentAt` | `number` | | `pendingDuration` | `number` | ## Diagram ```mermaid graph LR Client[Kafka Client] -->|request| Broker[Kafka Broker] Client --> Metadata[KafkaJSRequestTimeoutErrorMetadata] Metadata --> B[broker: string] Metadata --> C[clientId: string] Metadata --> CID[correlationId: number] Metadata --> CA[createdAt: number] Metadata --> SA[sentAt: number] Metadata --> PD[pendingDuration: number] Broker -->|timeout| Error[Request Timeout Error] Metadata --> Error ``` ## Usage ```ts import type { KafkaJSRequestTimeoutErrorMetadata } from './kafka.interface'; function logRequestTimeout( metadata: KafkaJSRequestTimeoutErrorMetadata, ): void { console.error('Kafka request timed out', { broker: metadata.broker, clientId: metadata.clientId, correlationId: metadata.correlationId, pendingDurationMs: metadata.pendingDuration, createdAt: new Date(metadata.createdAt).toISOString(), sentAt: new Date(metadata.sentAt).toISOString(), }); } const timeoutMetadata: KafkaJSRequestTimeoutErrorMetadata = { broker: 'localhost:9092', clientId: 'orders-service', correlationId: 42, createdAt: Date.now() - 10_000, sentAt: Date.now() - 9_500, pendingDuration: 9_500, }; logRequestTimeout(timeoutMetadata); ``` ## AI Coding Instructions - Treat `createdAt`, `sentAt`, and `pendingDuration` as millisecond-based numeric timestamps/durations. - Preserve the original `broker`, `clientId`, and `correlationId` values when wrapping or rethrowing Kafka timeout errors. - Use this metadata for structured logging, tracing attributes, and timeout diagnostics rather than user-facing error messages. - Do not assume `pendingDuration` is equivalent to total application processing time; it represents the Kafka request's pending duration. # Logger **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L641) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { info: (message: string, extra?: object) => void; error: (message: string, extra?: object) => void; warn: (message: string, extra?: object) => void; debug: (message: string, extra?: object) => void; namespace: (namespace: string, logLevel?: logLevel) => Logger; setLogLevel: (logLevel: logLevel) => void; } ``` # MicroserviceOptions **Kind:** Type **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy ``` ## Relationships - IMPORTS → `InjectionToken` - IMPORTS → `Type` # PartitionMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L151) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { partitionErrorCode: number; partitionId: number; leader: number; replicas: number[]; isr: number[]; offlineReplicas?: number[]; } ``` # RedisEvents **Kind:** Type **Source:** [`packages/microservices/events/redis.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/redis.events.ts#L26) **Part of:** [Microservices](subsystem-packages-microservices) Redis events map for the Redis client. Key is the event name and value is the corresponding callback function. `RedisEvents` defines the event-to-handler map used by the Redis client integration. Each key is a Redis event name, and its value is the callback function invoked when that event is emitted, providing a typed contract for Redis lifecycle and error handling. ## Definition ```ts { connect: VoidCallback; ready: VoidCallback; error: OnErrorCallback; close: VoidCallback; reconnecting: VoidCallback; end: VoidCallback; warning: OnWarningCallback; } ``` ## Diagram ```mermaid graph LR RedisClient[Redis Client] -->|emits event| EventName[Redis event name] EventName --> RedisEvents[RedisEvents map] RedisEvents --> Callback[Registered callback function] Callback --> Application[Microservice event handling] ``` ## Usage ```ts import type { RedisEvents } from './redis.events'; const redisEvents: RedisEvents = { connect: () => { console.log('Connecting to Redis...'); }, ready: () => { console.log('Redis client is ready.'); }, error: (error) => { console.error('Redis connection error:', error); }, close: () => { console.warn('Redis connection closed.'); }, }; // Register each typed event handler on the Redis client. for (const [event, handler] of Object.entries(redisEvents)) { redisClient.on(event, handler); } ``` ## AI Coding Instructions - Keep event names aligned with the Redis client library's supported event names. - Define callbacks with parameter types expected by the corresponding Redis event, especially for `error` handlers. - Use `RedisEvents` when building Redis client configuration or listener-registration utilities. - Ensure error callbacks log or report failures without throwing unhandled exceptions. - Remove listeners during shutdown or client replacement to prevent duplicate event handling. # RedisEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/redis.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/redis.events.ts#L11) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `CONNECT` - `READY` - `ERROR` - `CLOSE` - `RECONNECTING` - `END` - `WARNING` # RetryOptions **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L253) **Part of:** [Microservices](subsystem-packages-microservices) `RetryOptions` configures retry behavior for the Kafka microservice client or consumer connection workflow. It controls retry timing, exponential backoff, retry limits, and whether the service should restart after a terminal failure. ## Properties | Property | Type | |---|---| | `maxRetryTime` | `number` | | `initialRetryTime` | `number` | | `factor` | `number` | | `multiplier` | `number` | | `retries` | `number` | | `restartOnFailure` | `(e: Error) => Promise` | ## Diagram ```mermaid graph LR A[Kafka operation fails] --> B[RetryOptions] B --> C{Retries remaining?} C -->|Yes| D[Wait initialRetryTime
with factor and multiplier] D --> E[Retry operation] E --> A C -->|No| F[restartOnFailure(error)] F -->|true| G[Restart service or connection] F -->|false| H[Propagate failure] ``` ## Usage ```ts import type { RetryOptions } from '@nestjs/microservices'; const retryOptions: RetryOptions = { retries: 5, initialRetryTime: 300, maxRetryTime: 30_000, factor: 0.2, multiplier: 2, async restartOnFailure(error: Error): Promise { console.error('Kafka connection failed:', error.message); // Restart only for recoverable infrastructure failures. return true; }, }; // Example: pass the options to Kafka transport configuration. const kafkaOptions = { client: { clientId: 'orders-service', brokers: ['localhost:9092'], retry: retryOptions, }, }; ``` ## AI Coding Instructions - Set `initialRetryTime`, `maxRetryTime`, `factor`, and `multiplier` together so backoff growth remains bounded. - Use `retries` to prevent infinite retry loops; choose a limit appropriate for the service's availability requirements. - Keep `restartOnFailure` asynchronous and return `true` only when restarting the Kafka client or process is safe. - Log or report the received `Error` in `restartOnFailure` to preserve diagnostics for terminal connection failures. - Reuse a shared retry configuration across Kafka client and consumer setup when consistent recovery behavior is required. ## How it works `RetryOptions` is an exported KafkaJS-facing TypeScript interface. Its source file states that it is intended only to represent KafkaJS package types and must not contain NestJS logic. [packages/microservices/external/kafka.interface.ts:1-6](packages/microservices/external/kafka.interface.ts#L1-L6) All of its properties are optional: - `maxRetryTime?: number` - `initialRetryTime?: number` - `factor?: number` - `multiplier?: number` - `retries?: number` - `restartOnFailure?: (e: Error) => Promise` — an optional callback that receives an `Error` and asynchronously returns a boolean. [packages/microservices/external/kafka.interface.ts:253-260](packages/microservices/external/kafka.interface.ts#L253-L260) `RetryOptions` can be assigned to the `retry` property of Kafka client configuration, producer configuration, and admin configuration. [packages/microservices/external/kafka.interface.ts:60-74](packages/microservices/external/kafka.interface.ts#L60-L74) [packages/microservices/external/kafka.interface.ts:110-119](packages/microservices/external/kafka.interface.ts#L110-L119) [packages/microservices/external/kafka.interface.ts:262-264](packages/microservices/external/kafka.interface.ts#L262-L264) Consumer configuration also accepts it through `retry`; that declaration additionally declares `restartOnFailure` with the same `Error`-to-`Promise` signature. [packages/microservices/external/kafka.interface.ts:164-181](packages/microservices/external/kafka.interface.ts#L164-L181) In Nest Kafka transport options, these configurations are exposed as `options.client`, `options.consumer`, and `options.producer`. [packages/microservices/interfaces/microservice-configuration.interface.ts:333-355](packages/microservices/interfaces/microservice-configuration.interface.ts#L333-L355) The client transport merges `options.client` into the Kafka constructor configuration, passes `options.consumer` to `client.consumer()`, and passes `options.producer` to `client.producer()`. [packages/microservices/client/client-kafka.ts:162-184](packages/microservices/client/client-kafka.ts#L162-L184) The server transport likewise merges `options.client` into the Kafka constructor configuration and passes its consumer and producer options to the respective Kafka client methods. [packages/microservices/server/server-kafka.ts:107-117](packages/microservices/server/server-kafka.ts#L107-L117) [packages/microservices/server/server-kafka.ts:155-162](packages/microservices/server/server-kafka.ts#L155-L162) This interface itself contains no validation, defaults, error handling, or runtime side effects; it only declares the optional fields and their TypeScript types. [packages/microservices/external/kafka.interface.ts:253-260](packages/microservices/external/kafka.interface.ts#L253-L260) # TcpEvents **Kind:** Type **Source:** [`packages/microservices/events/tcp.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/tcp.events.ts#L31) **Part of:** [Microservices](subsystem-packages-microservices) TCP events map for the net TCP socket. Key is the event name and value is the corresponding callback function. `TcpEvents` defines the event-to-callback map used by the microservices TCP transport. It connects Node.js `net.Socket` lifecycle and data events—such as incoming data, connection errors, and socket closure—to the handlers responsible for processing them. ## Definition ```ts { error: OnErrorCallback; connect: VoidCallback; end: VoidCallback; close: VoidCallback; timeout: VoidCallback; drain: VoidCallback; lookup: OnLookupCallback; } ``` ## Diagram ```mermaid graph LR Socket[net.Socket] -->|data| DataHandler[TcpEvents.data callback] Socket -->|error| ErrorHandler[TcpEvents.error callback] Socket -->|close| CloseHandler[TcpEvents.close callback] DataHandler --> Transport[TCP transport processing] ErrorHandler --> Transport CloseHandler --> Transport ``` ## Usage ```ts import type { Socket } from 'node:net'; import type { TcpEvents } from './tcp.events'; function registerSocketEvents(socket: Socket, events: TcpEvents): void { for (const [eventName, callback] of Object.entries(events)) { socket.on(eventName, callback); } } const events: TcpEvents = { data: (chunk: Buffer) => { console.log('Received TCP payload:', chunk.toString()); }, error: (error: Error) => { console.error('TCP socket error:', error); }, close: () => { console.log('TCP socket closed'); }, }; registerSocketEvents(socket, events); ``` ## AI Coding Instructions - Keep event keys aligned with supported Node.js `net.Socket` event names and ensure each callback matches that event's argument signature. - Always provide an `error` handler when registering TCP socket events to prevent unhandled socket errors. - Treat `data` payloads as stream chunks; buffer and frame them when application messages may span multiple chunks. - Remove listeners or release associated connection state after `close` to avoid memory leaks. - Register `TcpEvents` handlers immediately after creating or accepting a socket, before writing application data. # Acl **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L443) **Part of:** [Microservices](subsystem-packages-microservices) `Acl` defines a Kafka access control list entry used to describe which principal can perform a specific operation against a host. It combines an authenticated identity, network host, operation type, and permission type for Kafka authorization workflows. ## Properties | Property | Type | |---|---| | `principal` | `string` | | `host` | `string` | | `operation` | `AclOperationTypes` | | `permissionType` | `AclPermissionTypes` | ## Diagram ```mermaid graph LR A[Acl] --> P[principal: string] A --> H[host: string] A --> O[operation: AclOperationTypes] A --> PT[permissionType: AclPermissionTypes] P --> I[Authenticated user or service identity] H --> N[Allowed source host] O --> K[Kafka operation] PT --> R[Allow or deny permission] ``` ## Usage ```ts import { Acl, AclOperationTypes, AclPermissionTypes, } from '@nestjs/microservices'; const consumerReadAcl: Acl = { principal: 'User:analytics-service', host: '*', operation: AclOperationTypes.READ, permissionType: AclPermissionTypes.ALLOW, }; // Pass the ACL definition to Kafka administration or authorization setup. console.log(consumerReadAcl); ``` ## AI Coding Instructions - Use the `User:` principal convention expected by Kafka when defining user or service identities. - Set `host` to `'*'` only when access from all hosts is intended; prefer a specific host where possible. - Use `AclOperationTypes` and `AclPermissionTypes` enum values instead of hard-coded strings. - Pair ACL entries with the appropriate Kafka resource definition when creating or deleting broker ACLs. - Review `ALLOW` and `DENY` rules carefully, as conflicting ACLs can produce unexpected authorization behavior. # AclPermissionTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L312) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `UNKNOWN` - `ANY` - `DENY` - `ALLOW` # AdminEvents **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L389) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { CONNECT: 'admin.connect'; DISCONNECT: 'admin.disconnect'; REQUEST: 'admin.network.request'; REQUEST_TIMEOUT: 'admin.network.request_timeout'; REQUEST_QUEUE_SIZE: 'admin.network.request_queue_size'; } ``` # ApiVersions **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L660) **Part of:** [Microservices](subsystem-packages-microservices) # ClientsModuleAsyncOptions **Kind:** Type **Source:** [`packages/microservices/module/interfaces/clients-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/interfaces/clients-module.interface.ts#L33) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts | Array | { clients: Array; isGlobal?: boolean; } ``` # ClientsModuleOptions **Kind:** Type **Source:** [`packages/microservices/module/interfaces/clients-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/interfaces/clients-module.interface.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts | Array | { clients: Array; isGlobal?: boolean; } ``` # CompressionCodecs **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1137) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { [CompressionTypes.GZIP]: () => any; [CompressionTypes.Snappy]: () => any; [CompressionTypes.LZ4]: () => any; [CompressionTypes.ZSTD]: () => any; } ``` # CompressionTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1129) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `None` - `GZIP` - `Snappy` - `LZ4` - `ZSTD` # ConfigResourceTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L295) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `UNKNOWN` - `TOPIC` - `BROKER` - `BROKER_LOGGER` # ConsumerCommitOffsetsEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L933) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ groupId: string; memberId: string; groupGenerationId: number; topics: TopicOffsets[]; }> ``` # ConsumerGroup **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L838) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { groupId: string; generationId: number; memberId: string; coordinator: Broker; } ``` # ConsumerGroupState **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L854) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts | 'Unknown' | 'PreparingRebalance' | 'CompletingRebalance' | 'Stable' | 'Dead' | 'Empty' ``` # DescribeAclResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L462) **Part of:** [Microservices](subsystem-packages-microservices) `DescribeAclResponse` represents the response payload returned from a Kafka ACL describe operation. It captures request throttling and error details alongside the ACL resources that matched the query. ## Properties | Property | Type | |---|---| | `throttleTime` | `number` | | `errorCode` | `number` | | `errorMessage` | `string` | | `resources` | `DescribeAclResource[]` | ## Diagram ```mermaid graph LR A[Kafka Describe ACL Request] --> B[DescribeAclResponse] B --> C[throttleTime: number] B --> D[errorCode: number] B --> E[errorMessage: string] B --> F[resources: DescribeAclResource[]] F --> G[Matched ACL resources and entries] ``` ## Usage ```ts import type { DescribeAclResponse } from './kafka.interface'; function handleDescribeAclResponse(response: DescribeAclResponse): void { if (response.errorCode !== 0) { throw new Error( `Kafka ACL lookup failed (${response.errorCode}): ${response.errorMessage}`, ); } console.log(`Request throttled for ${response.throttleTime}ms`); for (const resource of response.resources) { console.log('ACL resource:', resource); } } // Example response received from a Kafka client or protocol handler. const response: DescribeAclResponse = { throttleTime: 0, errorCode: 0, errorMessage: '', resources: [], }; handleDescribeAclResponse(response); ``` ## AI Coding Instructions - Check `errorCode` before consuming `resources`; a non-zero code indicates the broker could not complete the request. - Preserve `throttleTime` from the Kafka response so callers can observe or react to broker throttling. - Treat `resources` as the authoritative list of ACL resources returned by the broker, including an empty array for no matches. - Keep this interface aligned with the Kafka protocol response shape and the related `DescribeAclResource` definition. ## How it works `DescribeAclResponse` is an exported TypeScript interface representing the declared result type of `Admin.describeAcls(options)`, which returns `Promise`. The method accepts an `AclFilter`; this interface itself declares no runtime logic, validation, thrown errors, or side effects. [packages/microservices/external/kafka.interface.ts:462-467](packages/microservices/external/kafka.interface.ts#L462-L467) [packages/microservices/external/kafka.interface.ts:502-561](packages/microservices/external/kafka.interface.ts#L502-L561) It has these required fields: - `throttleTime: number` [packages/microservices/external/kafka.interface.ts:462-464](packages/microservices/external/kafka.interface.ts#L462-L464) - `errorCode: number` [packages/microservices/external/kafka.interface.ts:462-465](packages/microservices/external/kafka.interface.ts#L462-L465) - `resources: DescribeAclResource[]` [packages/microservices/external/kafka.interface.ts:462-467](packages/microservices/external/kafka.interface.ts#L462-L467) It also has an optional `errorMessage?: string`, so an instance may omit that field. [packages/microservices/external/kafka.interface.ts:462-466](packages/microservices/external/kafka.interface.ts#L462-L466) Each `resources` element is a `DescribeAclResource`: an ACL resource identifier plus an `acls` array. Its inherited resource fields are: - `resourceType: AclResourceTypes` - `resourceName: string` - `resourcePatternType: ResourcePatternTypes` and it adds `acls: Acl[]`. [packages/microservices/external/kafka.interface.ts:450-460](packages/microservices/external/kafka.interface.ts#L450-L460) Each ACL in that array has a string `principal`, string `host`, `operation: AclOperationTypes`, and `permissionType: AclPermissionTypes`. [packages/microservices/external/kafka.interface.ts:443-448](packages/microservices/external/kafka.interface.ts#L443-L448) The declared enum domains include resource types such as `TOPIC`, `GROUP`, and `CLUSTER`; operation types such as `READ`, `WRITE`, and `DESCRIBE`; permission types `DENY` and `ALLOW`; and resource pattern types including `LITERAL` and `PREFIXED`. [packages/microservices/external/kafka.interface.ts:285-293](packages/microservices/external/kafka.interface.ts#L285-L293) [packages/microservices/external/kafka.interface.ts:312-341](packages/microservices/external/kafka.interface.ts#L312-L341) # Deserializer **Kind:** Interface **Source:** [`packages/microservices/interfaces/deserializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/deserializer.interface.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) # EachMessagePayload **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L994) **Part of:** [Microservices](subsystem-packages-microservices) `EachMessagePayload` represents the data delivered to a Kafka consumer handler for each consumed message. It identifies the source topic and partition while providing the raw `KafkaMessage` instance for reading keys, headers, values, and offsets. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partition` | `number` | | `message` | `KafkaMessage` | ## Diagram ```mermaid graph LR Consumer[Kafka Consumer] --> Payload[EachMessagePayload] Payload --> Topic[topic: string] Payload --> Partition[partition: number] Payload --> Message[message: KafkaMessage] Message --> Value[message.value] Message --> Headers[message.headers] Message --> Offset[message.offset] ``` ## Usage ```ts import { EachMessagePayload } from './kafka.interface'; async function handleMessage({ topic, partition, message, }: EachMessagePayload): Promise { const value = message.value?.toString('utf8'); console.log(`Received message from ${topic}[${partition}]`); console.log(`Offset: ${message.offset}`); console.log(`Payload: ${value}`); } ``` ## AI Coding Instructions - Treat `message.value` as nullable; check for `null` or `undefined` before converting or parsing it. - Use `topic` and `partition` for logging, tracing, retry diagnostics, and partition-aware processing. - Read Kafka metadata such as `offset`, `key`, and `headers` from the nested `message` object. - Avoid assuming message values are JSON; decode the buffer and validate content before parsing. - Keep message handlers idempotent because Kafka consumers may process a message more than once. ## How it works `EachMessagePayload` is a TypeScript interface representing the argument passed to a Kafka consumer’s per-message handler. The surrounding file is a declaration layer intended to represent KafkaJS types rather than Nest-specific logic. [`packages/microservices/external/kafka.interface.ts:1-8`](packages/microservices/external/kafka.interface.ts#L1-L8) It requires: - `topic: string` — the message’s topic. [`packages/microservices/external/kafka.interface.ts:994-996`](packages/microservices/external/kafka.interface.ts#L994-L996) - `partition: number` — the topic partition. [`packages/microservices/external/kafka.interface.ts:995-997`](packages/microservices/external/kafka.interface.ts#L995-L997) - `message: KafkaMessage` — the consumed message. [`packages/microservices/external/kafka.interface.ts:996-997`](packages/microservices/external/kafka.interface.ts#L996-L997) `KafkaMessage` is either a message-set entry or a record-batch entry; both include nullable `key` and `value`, a string `timestamp`, numeric `attributes`, and a string `offset`. Record-batch entries have `headers`, while message-set entries declare that `headers` cannot be present. [`packages/microservices/external/kafka.interface.ts:718-738`](packages/microservices/external/kafka.interface.ts#L718-L738) - `heartbeat(): Promise` — an asynchronous method whose declared result has no value. [`packages/microservices/external/kafka.interface.ts:997-999`](packages/microservices/external/kafka.interface.ts#L997-L999) - `pause(): () => void` — a method returning a zero-argument function with no declared return value. [`packages/microservices/external/kafka.interface.ts:998-1000`](packages/microservices/external/kafka.interface.ts#L998-L1000) `EachMessageHandler` accepts this payload and must return `Promise`. `ConsumerRunConfig.eachMessage` is optional and is typed as that handler, and `Consumer.run()` accepts this run configuration. [`packages/microservices/external/kafka.interface.ts:1025-1036`](packages/microservices/external/kafka.interface.ts#L1025-L1036) [`packages/microservices/external/kafka.interface.ts:1043-1049`](packages/microservices/external/kafka.interface.ts#L1043-L1049) In Nest’s Kafka client, `bindTopics()` passes `createResponseCallback()` as `eachMessage` when starting the consumer. [`packages/microservices/client/client-kafka.ts:196-214`](packages/microservices/client/client-kafka.ts#L196-L214) That callback mutates `payload.message` by assigning the payload’s `topic` and `partition` before parsing it; it then ignores messages without a correlation-ID header or without a matching routing callback. [`packages/microservices/client/client-kafka.ts:227-255`](packages/microservices/client/client-kafka.ts#L227-L255) In Nest’s Kafka server, `bindEvents()` similarly installs `getMessageHandler()` as `eachMessage`, and that handler forwards the payload to `handleMessage()`. [`packages/microservices/server/server-kafka.ts:165-184`](packages/microservices/server/server-kafka.ts#L165-L184) `handleMessage()` also assigns `topic` and `partition` onto `payload.message` before parsing it, then reads request-related headers and deserializes the parsed message. [`packages/microservices/server/server-kafka.ts:202-215`](packages/microservices/server/server-kafka.ts#L202-L215) The interface itself contains no implementation, runtime validation, thrown errors, or side effects; it only declares the required payload shape and method signatures. [`packages/microservices/external/kafka.interface.ts:994-1000`](packages/microservices/external/kafka.interface.ts#L994-L1000) # EmptyResponseException **Kind:** Class **Source:** [`packages/microservices/errors/empty-response.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/empty-response.exception.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `Error` # GroupDescription **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L862) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { groupId: string; members: MemberDescription[]; protocol: string; protocolType: string; state: ConsumerGroupState; } ``` # IClientSubscribeOptions **Kind:** Interface **Source:** [`packages/microservices/external/mqtt-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/mqtt-options.interface.ts#L165) **Part of:** [Microservices](subsystem-packages-microservices) `IClientSubscribeOptions` defines configuration for MQTT topic subscriptions in the microservices transport layer. It currently specifies the Quality of Service (`qos`) level used when subscribing, controlling message delivery guarantees between the MQTT broker and client. ## Properties | Property | Type | |---|---| | `qos` | `QoS` | ## Diagram ```mermaid graph LR Client[MQTT Client] -->|subscribe(topic, options)| Options[IClientSubscribeOptions] Options -->|qos| QoS[MQTT QoS Level] Client --> Broker[MQTT Broker] Broker -->|messages with delivery guarantee| Client ``` ## Usage ```ts import { QoS } from 'mqtt-packet'; import type { IClientSubscribeOptions } from './mqtt-options.interface'; const subscribeOptions: IClientSubscribeOptions = { qos: QoS.AtLeastOnce, }; mqttClient.subscribe('devices/+/status', subscribeOptions, (error) => { if (error) { console.error('Unable to subscribe to device status updates', error); } }); ``` ## AI Coding Instructions - Provide a valid MQTT `QoS` enum value for `qos`; do not use arbitrary numeric values unless supported by the MQTT client dependency. - Match the subscription QoS level to delivery requirements: lower levels favor performance, while higher levels provide stronger delivery guarantees. - Pass this interface as the options object when integrating with MQTT client `subscribe()` calls. - Keep subscription options transport-specific; avoid reusing MQTT QoS settings for non-MQTT microservice transports. # InstrumentationEvent **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L397) **Part of:** [Microservices](subsystem-packages-microservices) `InstrumentationEvent` defines the standard envelope for instrumentation data emitted through the microservices Kafka integration. It provides a unique event ID, event type, timestamp, and a generic payload so producers and consumers can exchange typed telemetry consistently. ## Properties | Property | Type | |---|---| | `id` | `string` | | `type` | `string` | | `timestamp` | `number` | | `payload` | `T` | ## Diagram ```mermaid graph LR Producer[Service / Instrumentation Producer] --> Event[InstrumentationEvent] Event --> ID[id: unique event identifier] Event --> Type[type: event category] Event --> Timestamp[timestamp: Unix time] Event --> Payload[payload: typed event data] Event --> Kafka[Kafka Topic] Kafka --> Consumer[Instrumentation Consumer] ``` ## Usage ```ts import type { InstrumentationEvent } from './kafka.interface'; interface HttpRequestPayload { method: string; path: string; statusCode: number; durationMs: number; } const event: InstrumentationEvent = { id: crypto.randomUUID(), type: 'http.request.completed', timestamp: Date.now(), payload: { method: 'GET', path: '/health', statusCode: 200, durationMs: 14, }, }; // Send the event through the configured Kafka producer. await kafkaProducer.send({ topic: 'instrumentation-events', messages: [{ key: event.type, value: JSON.stringify(event) }], }); ``` ## AI Coding Instructions - Use a specific payload type for `T`; avoid `any` so event producers and consumers remain type-safe. - Generate a unique `id` for every event, typically with `crypto.randomUUID()` or the project's ID utility. - Set `timestamp` with `Date.now()` and treat it as a Unix timestamp in milliseconds. - Use stable, descriptive `type` values such as `service.operation.completed` so consumers can route events reliably. - Serialize the complete event envelope when publishing to Kafka, and validate or parse the payload type when consuming it. # InvalidGrpcDecoratorException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-grpc-message-decorator.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-grpc-message-decorator.exception.ts#L12) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` # InvalidGrpcPackageDefinitionMissingPackageDefinitionException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-grpc-package-definition-missing-package-definition.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-grpc-package-definition-missing-package-definition.exception.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # InvalidGrpcPackageDefinitionMutexException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-grpc-package-definition-mutex.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-grpc-package-definition-mutex.exception.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # InvalidKafkaClientTopicException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-kafka-client-topic.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-kafka-client-topic.exception.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # ISocketFactoryArgs **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L76) **Part of:** [Microservices](subsystem-packages-microservices) `ISocketFactoryArgs` defines the connection parameters provided when creating a Kafka socket. It groups the broker address, TLS configuration, and connection lifecycle callback required by the microservices Kafka transport. ## Properties | Property | Type | |---|---| | `host` | `string` | | `port` | `number` | | `ssl` | `tls.ConnectionOptions` | | `onConnect` | `() => void` | ## Diagram ```mermaid graph LR SocketFactory[Kafka Socket Factory] --> Args[ISocketFactoryArgs] Args --> Host[host: string] Args --> Port[port: number] Args --> SSL[ssl: tls.ConnectionOptions] Args --> OnConnect[onConnect: () => void] SSL --> TLS[TLS-secured broker connection] OnConnect --> Ready[Connection established] ``` ## Usage ```ts import type { ConnectionOptions } from 'node:tls'; interface ISocketFactoryArgs { host: string; port: number; ssl: ConnectionOptions; onConnect: () => void; } const socketArgs: ISocketFactoryArgs = { host: 'kafka.example.com', port: 9093, ssl: { rejectUnauthorized: true, // ca, cert, and key can be provided when required by the broker. }, onConnect: () => { console.log('Connected to Kafka broker'); }, }; // Pass socketArgs to the Kafka transport socket factory. ``` ## AI Coding Instructions - Provide a valid Kafka broker hostname and port; use the TLS listener port when `ssl` is configured. - Pass `tls.ConnectionOptions` through unchanged so certificate, key, CA, and verification settings remain available to the underlying socket. - Use `onConnect` only for post-connection work, such as logging or readiness updates; avoid blocking operations. - Do not place connection error handling in `onConnect`; handle socket and transport errors through the relevant Kafka client hooks. # ITopicConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L266) **Part of:** [Microservices](subsystem-packages-microservices) `ITopicConfig` defines the configuration required to create or manage a Kafka topic in the microservices integration layer. It specifies the topic name, partitioning and replication settings, optional replica placement, and broker-level topic configuration entries. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `numPartitions` | `number` | | `replicationFactor` | `number` | | `replicaAssignment` | `object[]` | | `configEntries` | `IResourceConfigEntry[]` | ## Diagram ```mermaid graph LR A[ITopicConfig] --> B[topic: string] A --> C[numPartitions: number] A --> D[replicationFactor: number] A --> E[replicaAssignment: object[]] A --> F[configEntries: IResourceConfigEntry[]] C --> G[Kafka partitions] D --> H[Replica count] E --> I[Explicit broker assignment] F --> J[Topic-level broker settings] ``` ## Usage ```ts import type { ITopicConfig } from './kafka.interface'; const topicConfig: ITopicConfig = { topic: 'orders.created', numPartitions: 3, replicationFactor: 2, replicaAssignment: [], configEntries: [ { name: 'retention.ms', value: '604800000', // Keep messages for 7 days }, { name: 'cleanup.policy', value: 'delete', }, ], }; // Pass to the Kafka topic administration or provisioning service. await kafkaAdmin.createTopic(topicConfig); ``` ## AI Coding Instructions - Provide a unique, descriptive `topic` name that follows the application's Kafka naming conventions. - Set `numPartitions` based on expected consumer parallelism and throughput; changing partition counts later can affect message ordering assumptions. - Ensure `replicationFactor` does not exceed the number of available Kafka brokers. - Use `replicaAssignment` only when explicit partition-to-broker placement is required; otherwise provide an empty array or use the project's standard default. - Add topic-specific retention, cleanup, and compaction settings through `configEntries` using valid Kafka broker configuration keys. # KafkaJSErrorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1282) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSErrorMetadata` describes additional context attached to KafkaJS-related errors in the microservices Kafka transport. It identifies whether an operation can be retried and provides the affected topic, partition, and Kafka partition metadata needed for diagnostics or recovery logic. ## Properties | Property | Type | |---|---| | `retriable` | `boolean` | | `topic` | `string` | | `partitionId` | `number` | | `metadata` | `PartitionMetadata` | ## Diagram ```mermaid graph LR Error[KafkaJS Error] --> Metadata[KafkaJSErrorMetadata] Metadata --> Retriable[retriable: boolean] Metadata --> Topic[topic: string] Metadata --> Partition[partitionId: number] Metadata --> PartitionMetadata[metadata: PartitionMetadata] Retriable --> RetryLogic[Retry / Failure Handling] Topic --> Diagnostics[Logging and Diagnostics] Partition --> Diagnostics ``` ## Usage ```ts import type { KafkaJSErrorMetadata } from './kafka.interface'; function handleKafkaError(error: Error & Partial) { if (!error.topic || error.partitionId === undefined) { throw error; } const context: KafkaJSErrorMetadata = { retriable: error.retriable ?? false, topic: error.topic, partitionId: error.partitionId, metadata: error.metadata!, }; console.error( `Kafka error on ${context.topic}[${context.partitionId}]`, context.metadata, ); if (context.retriable) { // Retry the Kafka operation using the topic and partition context. return; } throw error; } ``` ## AI Coding Instructions - Preserve the KafkaJS naming and metadata types when mapping Kafka errors into application-level error handling. - Check `retriable` before scheduling retries; do not retry non-retriable errors automatically. - Use `topic` and `partitionId` in logs, metrics, and tracing to make partition-specific failures diagnosable. - Treat `metadata` as Kafka partition context and avoid replacing it with partial or unrelated metadata objects. # KafkaStatus **Kind:** Enum **Source:** [`packages/microservices/events/kafka.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/kafka.events.ts#L1) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECTED` - `CONNECTED` - `CRASHED` - `STOPPED` - `REBALANCING` # LogEntry **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L626) **Part of:** [Microservices](subsystem-packages-microservices) `LogEntry` defines the structured payload used to represent a log message in the Kafka microservices integration. It combines routing and classification metadata (`namespace`, `level`, and `label`) with the actual logger content in `log`, enabling consistent log publishing and consumption across services. ## Properties | Property | Type | |---|---| | `namespace` | `string` | | `level` | `logLevel` | | `label` | `string` | | `log` | `LoggerEntryContent` | ## Diagram ```mermaid graph LR A[Application or Microservice] --> B[LogEntry] B --> C[namespace: string] B --> D[level: logLevel] B --> E[label: string] B --> F[log: LoggerEntryContent] B --> G[Kafka Logging Pipeline] ``` ## Usage ```ts import type { LogEntry } from './kafka.interface'; const logEntry: LogEntry = { namespace: 'payments-service', level: 'error', label: 'payment-processing', log: { message: 'Failed to process payment', transactionId: 'txn_12345', error: 'Card authorization declined', }, }; // Example: send the structured entry through a Kafka producer. await kafkaProducer.send({ topic: 'service-logs', messages: [{ value: JSON.stringify(logEntry) }], }); ``` ## AI Coding Instructions - Populate `namespace` with a stable service or application identifier so consumers can filter logs reliably. - Use valid `logLevel` values rather than arbitrary strings when setting `level`. - Keep `label` concise and action-oriented, such as `database-query` or `payment-processing`. - Store structured context in `log` instead of serializing important metadata into a message string. - Preserve the full `LogEntry` shape when publishing to or consuming from Kafka topics. # logLevel **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L618) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `NOTHING` - `ERROR` - `WARN` - `INFO` - `DEBUG` # MemberDescription **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L845) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { clientHost: string; clientId: string; memberId: string; memberAssignment: Buffer; memberMetadata: Buffer; } ``` # Message **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L121) **Part of:** [Microservices](subsystem-packages-microservices) `Message` represents a Kafka record consumed or produced by the microservices transport layer. It stores the message payload, optional key, partition metadata, headers, and the Kafka-provided timestamp so downstream code can process records consistently. ## Properties | Property | Type | |---|---| | `key` | `Buffer | string | null` | | `value` | `Buffer | string | null` | | `partition` | `number` | | `headers` | `IHeaders` | | `timestamp` | `string` | ## Diagram ```mermaid graph LR Producer[Kafka Producer] --> Message[Message] Message --> Key[key: Buffer | string | null] Message --> Value[value: Buffer | string | null] Message --> Partition[partition: number] Message --> Headers[headers: IHeaders] Message --> Timestamp[timestamp: string] Message --> Consumer[Kafka Consumer] ``` ## Usage ```ts import type { Message } from './kafka.interface'; function handleKafkaMessage(message: Message): void { const payload = message.value === null ? null : Buffer.isBuffer(message.value) ? message.value.toString('utf8') : message.value; console.log({ key: message.key?.toString(), partition: message.partition, timestamp: new Date(message.timestamp), headers: message.headers, payload, }); } ``` ## AI Coding Instructions - Treat `key` and `value` as nullable; check for `null` before decoding or parsing them. - Support both `Buffer` and `string` payloads, using `Buffer.isBuffer()` before calling buffer-specific methods. - Preserve `partition`, `headers`, and `timestamp` when forwarding or transforming a message. - Parse `timestamp` only when needed; Kafka timestamps are represented as strings in this interface. - Use `headers` for cross-cutting metadata such as tracing, correlation IDs, and content type. # MicroserviceEntrypointMetadata **Kind:** Type **Source:** [`packages/microservices/interfaces/microservice-entrypoint-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-entrypoint-metadata.interface.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { transportId: keyof typeof Transport | symbol; patterns: PatternMetadata[]; isEventHandler: boolean; extras?: Record; } ``` # MqttRecord **Kind:** Class **Source:** [`packages/microservices/record-builders/mqtt.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/mqtt.record-builder.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) # MqttStatus **Kind:** Enum **Source:** [`packages/microservices/events/mqtt.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/mqtt.events.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECTED` - `RECONNECTING` - `CONNECTED` - `CLOSED` # NatsRecord **Kind:** Class **Source:** [`packages/microservices/record-builders/nats.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/nats.record-builder.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) # ProducerBatch **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L764) **Part of:** [Microservices](subsystem-packages-microservices) `ProducerBatch` defines the configuration and payload for sending multiple Kafka topic messages in a single producer operation. It combines delivery guarantees (`acks`), request timing (`timeout`), compression settings, and one or more topic-specific message groups. ## Properties | Property | Type | |---|---| | `acks` | `number` | | `timeout` | `number` | | `compression` | `CompressionTypes` | | `topicMessages` | `TopicMessages[]` | ## Diagram ```mermaid graph LR PB[ProducerBatch] PB --> A[acks: number] PB --> T[timeout: number] PB --> C[compression: CompressionTypes] PB --> TM[topicMessages: TopicMessages[]] TM --> Topic[Kafka topic] TM --> Messages[Messages to publish] ``` ## Usage ```ts import { CompressionTypes, ProducerBatch } from '@nestjs/microservices'; const batch: ProducerBatch = { acks: -1, timeout: 30_000, compression: CompressionTypes.GZIP, topicMessages: [ { topic: 'orders.created', messages: [ { key: 'order-123', value: JSON.stringify({ orderId: '123', status: 'created' }), }, ], }, { topic: 'audit.events', messages: [ { value: JSON.stringify({ action: 'order.created', orderId: '123' }), }, ], }, ], }; await producer.sendBatch(batch); ``` ## AI Coding Instructions - Use `topicMessages` to group messages by Kafka topic when publishing a batch. - Set `acks` according to the required delivery guarantee; use `-1` when all in-sync replicas must acknowledge writes. - Keep `timeout` appropriate for broker latency and retry expectations, especially for larger batches. - Select a `CompressionTypes` value supported by the configured Kafka client and brokers. - Ensure message keys and values are serialized consistently with consumers before adding them to `topicMessages`. ## How it works `ProducerBatch` is an exported TypeScript interface representing the argument accepted by the Kafka producer batch-send API. It is part of a file intended to represent KafkaJS package types only, rather than NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) All of its properties are optional: - `acks?: number` - `timeout?: number` - `compression?: CompressionTypes` - `topicMessages?: TopicMessages[]` [packages/microservices/external/kafka.interface.ts:764-769](packages/microservices/external/kafka.interface.ts#L764-L769) `topicMessages`, when present, is an array of objects with a required `topic: string` and required `messages: Message[]`. [packages/microservices/external/kafka.interface.ts:759-762](packages/microservices/external/kafka.interface.ts#L759-L762) Each `Message` requires a `value` of `Buffer`, `string`, or `null`; it can also include a key, partition, headers, and timestamp. [packages/microservices/external/kafka.interface.ts:121-127](packages/microservices/external/kafka.interface.ts#L121-L127) The `compression` field accepts the `CompressionTypes` enum: `None` (`0`), `GZIP` (`1`), `Snappy` (`2`), `LZ4` (`3`), or `ZSTD` (`4`). [packages/microservices/external/kafka.interface.ts:1129-1135](packages/microservices/external/kafka.interface.ts#L1129-L1135) A `Producer` and a `Transaction` both inherit the `Sender` type, whose `sendBatch(batch: ProducerBatch)` method returns `Promise`. [packages/microservices/external/kafka.interface.ts:785-788](packages/microservices/external/kafka.interface.ts#L785-L788) [packages/microservices/external/kafka.interface.ts:798-829](packages/microservices/external/kafka.interface.ts#L798-L829) [packages/microservices/external/kafka.interface.ts:831-836](packages/microservices/external/kafka.interface.ts#L831-L836) Each returned metadata entry includes the topic name, partition, and error code, with optional offset and timestamp-related fields. [packages/microservices/external/kafka.interface.ts:748-757](packages/microservices/external/kafka.interface.ts#L748-L757) This interface declares no runtime validation, thrown errors, or direct side effects. Its members are type declarations only. [packages/microservices/external/kafka.interface.ts:764-769](packages/microservices/external/kafka.interface.ts#L764-L769) # ProducerEvents **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L790) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { CONNECT: 'producer.connect'; DISCONNECT: 'producer.disconnect'; REQUEST: 'producer.network.request'; REQUEST_TIMEOUT: 'producer.network.request_timeout'; REQUEST_QUEUE_SIZE: 'producer.network.request_queue_size'; } ``` # ProducerRecord **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L740) **Part of:** [Microservices](subsystem-packages-microservices) `ProducerRecord` defines the payload and delivery options for publishing one or more messages to an Apache Kafka topic. It groups the target topic, message batch, acknowledgement behavior, request timeout, and compression strategy used by the Kafka producer. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `messages` | `Message[]` | | `acks` | `number` | | `timeout` | `number` | | `compression` | `CompressionTypes` | ## Diagram ```mermaid graph LR ProducerRecord[ProducerRecord] Topic[topic: string] Messages[messages: Message[]] Acks[acks: number] Timeout[timeout: number] Compression[compression: CompressionTypes] ProducerRecord --> Topic ProducerRecord --> Messages ProducerRecord --> Acks ProducerRecord --> Timeout ProducerRecord --> Compression Messages --> Kafka[Kafka topic] ``` ## Usage ```ts import { CompressionTypes } from 'kafkajs'; import type { ProducerRecord } from '@nestjs/microservices'; const record: ProducerRecord = { topic: 'orders.created', messages: [ { key: 'order-123', value: JSON.stringify({ orderId: 'order-123', customerId: 'customer-456', total: 99.95, }), headers: { eventType: 'order.created', }, }, ], acks: -1, timeout: 30_000, compression: CompressionTypes.GZIP, }; await producer.send(record); ``` ## AI Coding Instructions - Provide a valid Kafka topic name and include at least one item in `messages`. - Serialize structured message values with `JSON.stringify()` unless the producer integration handles serialization. - Use `acks: -1` when durability is important; lower acknowledgement settings can improve throughput but reduce delivery guarantees. - Set `timeout` according to expected broker/network latency, especially for larger message batches. - Select a `CompressionTypes` value supported by the configured Kafka client and cluster. ## How it works `ProducerRecord` is an exported TypeScript interface in the KafkaJS type-only declaration surface; the file explicitly says it represents KafkaJS package types and should not contain NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) It describes the record object passed to a Kafka `Producer` or `Transaction` sender: - `topic` is required and has type `string`. [packages/microservices/external/kafka.interface.ts:740-742](packages/microservices/external/kafka.interface.ts#L740-L742) - `messages` is required and is an array of `Message` objects. [packages/microservices/external/kafka.interface.ts:740-742](packages/microservices/external/kafka.interface.ts#L740-L742) A `Message` requires a `value` of `Buffer | string | null`; it can also carry an optional `key`, `partition`, `headers`, and `timestamp`. [packages/microservices/external/kafka.interface.ts:121-127](packages/microservices/external/kafka.interface.ts#L121-L127) - `acks`, `timeout`, and `compression` are optional record-level fields. `acks` and `timeout` are numbers; `compression` is typed as `CompressionTypes`. [packages/microservices/external/kafka.interface.ts:740-746](packages/microservices/external/kafka.interface.ts#L740-L746) `ProducerRecord` is the argument to `Sender.send()`, which returns a `Promise`. [packages/microservices/external/kafka.interface.ts:785-788](packages/microservices/external/kafka.interface.ts#L785-L788) `Producer` and `Transaction` both include that sender contract. [packages/microservices/external/kafka.interface.ts:798-829](packages/microservices/external/kafka.interface.ts#L798-L836) Each returned metadata entry includes a topic name, partition, and error code, with optional offset and timestamp-related fields. [packages/microservices/external/kafka.interface.ts:748-757](packages/microservices/external/kafka.interface.ts#L748-L757) For Nest Kafka transport configuration, `KafkaOptions.options.send` accepts `ProducerRecord` fields except `topic` and `messages`. [packages/microservices/interfaces/microservice-configuration.interface.ts:333-355](packages/microservices/interfaces/microservice-configuration.interface.ts#L333-L355) The Kafka client constructs records with a normalized pattern as `topic` and serialized event data as `messages`, merges `options.send` into that object, then calls `producer.send()`. [packages/microservices/client/client-kafka.ts:339-360](packages/microservices/client/client-kafka.ts#L339-L360) The same construction occurs for individual events and request messages. [packages/microservices/client/client-kafka.ts:363-376](packages/microservices/client/client-kafka.ts#L363-L376) [packages/microservices/client/client-kafka.ts:407-424](packages/microservices/client/client-kafka.ts#L407-L424) Server replies likewise form a record from the reply topic and serialized message, merge `options.send`, and send it. [packages/microservices/server/server-kafka.ts:304-326](packages/microservices/server/server-kafka.ts#L304-L326) This interface contains no runtime validation, error handling, or side-effecting implementation; it only declares the object shape. [packages/microservices/external/kafka.interface.ts:740-746](packages/microservices/external/kafka.interface.ts#L740-L746) # ResourcePatternTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L335) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `UNKNOWN` - `ANY` - `MATCH` - `LITERAL` - `PREFIXED` # RmqEvents **Kind:** Type **Source:** [`packages/microservices/events/rmq.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/rmq.events.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) RabbitMQ events map for the ampqlip client. Key is the event name and value is the corresponding callback function. `RmqEvents` defines the event-to-callback map used by the RabbitMQ (`amqplib`) client integration. Each key is an event name emitted by the client, and its value is the callback that should run when that event occurs. This type centralizes event handling configuration for RabbitMQ connection and lifecycle events. ## Definition ```ts { error: OnErrorCallback; disconnect: VoidCallback; connect: VoidCallback; blocked: OnBlockedCallback; unblocked: VoidCallback; } ``` ## Diagram ```mermaid graph LR Client[RabbitMQ / amqplib Client] -->|emits event| EventName[Event name] EventName --> EventsMap[RmqEvents map] EventsMap --> Callback[Registered callback] Callback --> App[Application handling / logging / recovery] ``` ## Usage ```ts import type { RmqEvents } from './rmq.events'; const events: RmqEvents = { connect: () => { console.log('RabbitMQ connection established'); }, disconnect: () => { console.warn('RabbitMQ connection closed'); }, error: (error: Error) => { console.error('RabbitMQ client error:', error); }, }; // Register the configured handlers with the RabbitMQ client. for (const [eventName, callback] of Object.entries(events)) { rmqClient.on(eventName, callback); } ``` ## AI Coding Instructions - Add event handlers as key-value entries, where the key matches the event name emitted by the RabbitMQ client. - Keep callbacks focused on event-specific concerns such as logging, reconnecting, cleanup, or notifying application services. - Ensure error handlers capture and log useful context; unhandled RabbitMQ errors can terminate the process. - Register the `RmqEvents` map when initializing the RabbitMQ client so handlers are attached before publishing or consuming messages. - Avoid placing long-running business logic directly in event callbacks; delegate substantial work to application services or background workflows. # RmqEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/rmq.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/rmq.events.ts#L12) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `ERROR` - `DISCONNECT` - `CONNECT` - `BLOCKED` - `UNBLOCKED` # RmqRecord **Kind:** Class **Source:** [`packages/microservices/record-builders/rmq.record-builder.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/record-builders/rmq.record-builder.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) # RmqStatus **Kind:** Enum **Source:** [`packages/microservices/events/rmq.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/rmq.events.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECTED` - `CONNECTED` - `BLOCKED` - `UNBLOCKED` # Transaction **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L831) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Sender & { sendOffsets(offsets: Offsets & { consumerGroupId: string }): Promise; commit(): Promise; abort(): Promise; isActive(): boolean; } ``` # WritePacket **Kind:** Interface **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) `WritePacket` represents the result of writing or handling a microservice packet response. It carries either a successful typed `response` or an `err`, along with lifecycle and status information used to determine whether the underlying request has completed or been disposed. ## Properties | Property | Type | |---|---| | `err` | `any` | | `response` | `T` | | `isDisposed` | `boolean` | | `status` | `string` | ## Diagram ```mermaid graph LR Request[Microservice Request] --> Handler[Packet Handler] Handler --> Packet[WritePacket] Packet --> Response[response: T] Packet --> Error[err: any] Packet --> Status[status: string] Packet --> Disposed[isDisposed: boolean] ``` ## Usage ```ts import type { WritePacket } from './interfaces/packet.interface'; interface UserProfile { id: string; name: string; } const packet: WritePacket = { err: null, response: { id: 'user_123', name: 'Ada Lovelace', }, isDisposed: false, status: 'success', }; if (packet.err) { console.error('Microservice request failed:', packet.err); } else if (!packet.isDisposed) { console.log(`Received ${packet.status} response:`, packet.response); } ``` ## AI Coding Instructions - Use `WritePacket` with a concrete response type so consumers can safely access `response`. - Check `err` before processing `response`, since error packets may not contain meaningful response data. - Respect `isDisposed` when handling asynchronous responses; avoid writing to or consuming packets after disposal. - Keep `status` values consistent with the surrounding microservice transport or packet-handling conventions. - Preserve packet metadata when forwarding or transforming responses between microservice layers. # AclResource **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L450) **Part of:** [Microservices](subsystem-packages-microservices) `AclResource` describes a Kafka resource targeted by an access control list (ACL) rule. It identifies the resource category, its name, and the pattern Kafka should use when matching the resource name during authorization. ## Properties | Property | Type | |---|---| | `resourceType` | `AclResourceTypes` | | `resourceName` | `string` | | `resourcePatternType` | `ResourcePatternTypes` | ## Diagram ```mermaid graph LR ACL[Kafka ACL Rule] --> Resource[AclResource] Resource --> Type[resourceType: AclResourceTypes] Resource --> Name[resourceName: string] Resource --> Pattern[resourcePatternType: ResourcePatternTypes] Type --> KafkaResource[Kafka resource category] Pattern --> Matching[Kafka resource matching behavior] ``` ## Usage ```ts import { AclResource, AclResourceTypes, ResourcePatternTypes, } from './kafka.interface'; const topicResource: AclResource = { resourceType: AclResourceTypes.TOPIC, resourceName: 'orders', resourcePatternType: ResourcePatternTypes.LITERAL, }; // Use the resource definition when creating or filtering Kafka ACLs. await admin.createAcls({ acl: { resource: topicResource, principal: 'User:order-service', host: '*', operation: 'READ', permissionType: 'ALLOW', }, }); ``` ## AI Coding Instructions - Provide all three fields when constructing an `AclResource`; they define how Kafka locates the protected resource. - Use `AclResourceTypes` and `ResourcePatternTypes` enum values instead of hard-coded strings. - Use `LITERAL` matching for a single, exact topic or consumer group name; use prefix matching only when broader access is intentional. - Ensure `resourceName` matches the Kafka resource naming convention used by the target cluster. - Pass this interface as the `resource` portion of Kafka ACL create, delete, or filter operations. # ConfigSynonyms **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L359) **Part of:** [Microservices](subsystem-packages-microservices) `ConfigSynonyms` represents a Kafka broker configuration entry together with its resolved value and origin. It is used when inspecting or describing Kafka configuration synonyms, allowing consumers to identify both the effective setting and the `ConfigSource` that supplied it. ## Properties | Property | Type | |---|---| | `configName` | `string` | | `configValue` | `string` | | `configSource` | `ConfigSource` | ## Diagram ```mermaid graph LR A[Kafka Configuration Response] --> B[ConfigSynonyms] B --> C[configName: string] B --> D[configValue: string] B --> E[configSource: ConfigSource] E --> F[Kafka Config Origin] ``` ## Usage ```ts import { ConfigSource, type ConfigSynonyms } from './kafka.interface'; const brokerConfig: ConfigSynonyms = { configName: 'log.retention.hours', configValue: '168', configSource: ConfigSource.DEFAULT_CONFIG, }; function describeConfig(config: ConfigSynonyms): string { return `${config.configName}=${config.configValue} (${config.configSource})`; } console.log(describeConfig(brokerConfig)); ``` ## AI Coding Instructions - Preserve `configName` and `configValue` as strings, even when the configuration value represents a number or boolean. - Always provide a valid `ConfigSource` enum value to identify where Kafka resolved the setting from. - Use this interface when mapping Kafka Admin API configuration synonym responses into application-level types. - Do not assume `configValue` is parsed or normalized; convert it explicitly before performing numeric or boolean operations. # ConsumerCrashEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L972) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ error: Error; groupId: string; restart: boolean; }> ``` # ConsumerFetchEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L952) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ numberOfBatches: number; duration: number; nodeId: number; }> ``` # ConsumerHeartbeatEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L928) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ groupId: string; memberId: string; groupGenerationId: number; }> ``` # CorruptedPacketLengthException **Kind:** Class **Source:** [`packages/microservices/errors/corrupted-packet-length.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/corrupted-packet-length.exception.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `Error` # DEFAULT_GRPC_CALLBACK_METADATA **Kind:** Constant **Source:** [`packages/microservices/context/rpc-metadata-constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-metadata-constants.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { [`${RpcParamtype.CONTEXT}:1`]: { index: 1, data: undefined, pipes: [] }, [`${RpcParamtype.GRPC_CALL}:2`]: { index: 2, data: undefined, pipes: [] }, ...DEFAULT_CALLBACK_METADATA, } ``` ## Value ```ts { [`${RpcParamtype.CONTEXT}:1`]: { index: 1, data: undefined, pipes: [] }, [`${RpcParamtype.GRPC_CALL}:2`]: { index: 2, data: undefined, pipes: [] }, ...DEFAULT_CALLBACK_METADATA, } ``` # DeleteAclFilterResponses **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L491) **Part of:** [Microservices](subsystem-packages-microservices) `DeleteAclFilterResponses` represents the result of deleting Kafka ACL entries that match a requested filter. It provides the operation status through `errorCode` and `errorMessage`, and returns the ACL records that matched the filter in `matchingAcls`. ## Properties | Property | Type | |---|---| | `errorCode` | `number` | | `errorMessage` | `string` | | `matchingAcls` | `MatchingAcl[]` | ## Diagram ```mermaid graph LR Request[Kafka ACL delete filter] --> Response[DeleteAclFilterResponses] Response --> ErrorCode[errorCode: number] Response --> ErrorMessage[errorMessage: string] Response --> Matches[matchingAcls: MatchingAcl[]] Matches --> Acl1[Matching ACL] Matches --> AclN[Matching ACL] ``` ## Usage ```ts import type { DeleteAclFilterResponses } from './kafka.interface'; function handleDeleteAclResponse(response: DeleteAclFilterResponses): void { if (response.errorCode !== 0) { throw new Error( `Unable to delete matching ACLs: ${response.errorMessage}`, ); } console.log(`Deleted ${response.matchingAcls.length} matching ACL(s).`); for (const acl of response.matchingAcls) { console.log('Deleted ACL:', acl); } } // Example response returned by a Kafka ACL deletion operation const response: DeleteAclFilterResponses = { errorCode: 0, errorMessage: '', matchingAcls: [], }; handleDeleteAclResponse(response); ``` ## AI Coding Instructions - Treat `errorCode === 0` as the successful operation state; handle non-zero values before consuming `matchingAcls`. - Preserve `errorMessage` when surfacing Kafka ACL deletion failures to logs, callers, or exceptions. - Use `matchingAcls` to identify the ACLs affected by the filter, rather than assuming every requested ACL was deleted. - Keep this response type aligned with the Kafka client/admin API response mapping and the `MatchingAcl` interface definition. # DeleteGroupsResult **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L904) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { groupId: string; errorCode?: number; error?: KafkaJSProtocolError; } ``` # GrpcMethodStreamingType **Kind:** Enum **Source:** [`packages/microservices/decorators/message-pattern.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/message-pattern.decorator.ts#L22) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `NO_STREAMING` - `RX_STREAMING` - `PT_STREAMING` ## Relationships - IMPORTS → `isNil` - IMPORTS → `isNumber` - IMPORTS → `isObject` - IMPORTS → `isSymbol` # InvalidGrpcPackageException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-grpc-package.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-grpc-package.exception.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # InvalidGrpcServiceException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-grpc-service.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-grpc-service.exception.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # InvalidJSONFormatException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-json-format.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-json-format.exception.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `Error` # InvalidMessageException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-message.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-message.exception.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # InvalidProtoDefinitionException **Kind:** Class **Source:** [`packages/microservices/errors/invalid-proto-definition.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-proto-definition.exception.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # IResourceConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L381) **Part of:** [Microservices](subsystem-packages-microservices) `IResourceConfig` defines the configuration payload for a Kafka resource, such as a topic, broker, or other configurable Kafka entity. It combines the resource type and name with a collection of individual configuration entries that should be applied or managed by the external Kafka integration. ## Properties | Property | Type | |---|---| | `type` | `ConfigResourceTypes` | | `name` | `string` | | `configEntries` | `IResourceConfigEntry[]` | ## Diagram ```mermaid graph LR A[IResourceConfig] --> B[type: ConfigResourceTypes] A --> C[name: string] A --> D[configEntries: IResourceConfigEntry[]] D --> E[Kafka resource configuration values] ``` ## Usage ```ts import type { IResourceConfig, ConfigResourceTypes, } from './kafka.interface'; const topicConfig: IResourceConfig = { type: ConfigResourceTypes.TOPIC, name: 'orders.events', configEntries: [ { name: 'retention.ms', value: '604800000', }, { name: 'cleanup.policy', value: 'delete', }, ], }; // Pass the resource configuration to the Kafka administration layer. await kafkaAdmin.updateResourceConfig(topicConfig); ``` ## AI Coding Instructions - Set `type` to the Kafka resource category represented by `ConfigResourceTypes`; ensure it matches the target resource being configured. - Use the exact Kafka resource identifier in `name`, such as a topic name, because configuration updates are applied to that named resource. - Populate `configEntries` with valid `IResourceConfigEntry` objects and Kafka-supported configuration keys. - Keep configuration values in the expected serialized format, typically strings, to match Kafka Admin API conventions. - Route `IResourceConfig` objects through the existing Kafka administration or external microservice integration rather than applying configuration changes directly. # ITopicPartitionConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L274) **Part of:** [Microservices](subsystem-packages-microservices) `ITopicPartitionConfig` defines Kafka topic partitioning configuration for microservice deployments. It specifies the topic name, total partition count, and optional explicit replica assignments used when creating or configuring Kafka topics. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `count` | `number` | | `assignments` | `Array>` | ## Diagram ```mermaid graph LR Config[ITopicPartitionConfig] Config --> Topic[topic: string] Config --> Count[count: number] Config --> Assignments[assignments: number[][]] Assignments --> Partition0[Partition replica broker IDs] Assignments --> PartitionN[Additional partition replica broker IDs] ``` ## Usage ```ts import type { ITopicPartitionConfig } from './kafka.interface'; const ordersTopicConfig: ITopicPartitionConfig = { topic: 'orders.created', count: 3, assignments: [ [1, 2, 3], [2, 3, 1], [3, 1, 2], ], }; // Pass the configuration to the Kafka topic provisioning layer. await kafkaAdmin.createTopics({ topics: [ { topic: ordersTopicConfig.topic, numPartitions: ordersTopicConfig.count, replicaAssignment: ordersTopicConfig.assignments, }, ], }); ``` ## AI Coding Instructions - Keep `count` aligned with the number of entries in `assignments` when explicit assignments are provided. - Represent each partition assignment as an array of Kafka broker IDs; ordering typically determines the preferred replica leader. - Use a unique, stable Kafka topic name in `topic`, following the project's topic naming conventions. - Validate that every broker ID in `assignments` exists in the target Kafka cluster before provisioning. - Integrate this interface with Kafka admin/topic-creation code rather than consumer or producer runtime configuration. # KafkaJSDeleteGroupsErrorGroups **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1265) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSDeleteGroupsErrorGroups` represents an error returned for a specific Kafka consumer group during a delete-groups operation. It identifies the affected group and provides both the Kafka protocol error code and the associated `KafkaJSError` details for handling or logging failures. ## Properties | Property | Type | |---|---| | `groupId` | `string` | | `errorCode` | `number` | | `error` | `KafkaJSError` | ## Diagram ```mermaid graph LR DeleteGroups[Kafka delete groups response] --> GroupError[KafkaJSDeleteGroupsErrorGroups] GroupError --> GroupId[groupId: string] GroupError --> ErrorCode[errorCode: number] GroupError --> Error[error: KafkaJSError] ``` ## Usage ```ts import { KafkaJSError } from 'kafkajs'; import { KafkaJSDeleteGroupsErrorGroups } from './kafka.interface'; function handleDeleteGroupError( groupError: KafkaJSDeleteGroupsErrorGroups, ): void { console.error( `Failed to delete consumer group "${groupError.groupId}" ` + `(Kafka error code: ${groupError.errorCode})`, groupError.error, ); if (groupError.error instanceof KafkaJSError) { // Retry, alert, or map the Kafka error to an application-level response. } } ``` ## AI Coding Instructions - Treat each interface instance as the failure result for one consumer group, even when a delete operation targets multiple groups. - Use `groupId` when logging or reporting failures so operators can identify the affected consumer group. - Preserve both `errorCode` and `error`; the numeric code supports protocol-level handling, while `KafkaJSError` contains diagnostic context. - Handle delete-group failures individually rather than assuming the entire batch operation succeeded or failed uniformly. # KafkaJSDeleteTopicRecordsErrorPartition **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1276) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSDeleteTopicRecordsErrorPartition` describes a failed partition result returned while deleting Kafka topic records. It identifies the affected `partition`, the requested deletion `offset`, and the underlying `KafkaJSError` so callers can inspect and handle partition-specific failures. ## Properties | Property | Type | |---|---| | `partition` | `number` | | `offset` | `string` | | `error` | `KafkaJSError` | ## Diagram ```mermaid graph LR Request[Delete topic records request] --> PartitionResult[KafkaJSDeleteTopicRecordsErrorPartition] PartitionResult --> Partition[partition: number] PartitionResult --> Offset[offset: string] PartitionResult --> Error[error: KafkaJSError] Error --> Handling[Retry, log, or surface failure] ``` ## Usage ```ts import type { KafkaJSError } from 'kafkajs'; import type { KafkaJSDeleteTopicRecordsErrorPartition } from './kafka.interface'; function handleDeleteRecordsFailure( failure: KafkaJSDeleteTopicRecordsErrorPartition, ) { console.error( `Unable to delete records through offset ${failure.offset} ` + `for partition ${failure.partition}: ${failure.error.message}`, ); // Use the partition and offset to retry or report the failed operation. return { partition: failure.partition, offset: failure.offset, retryable: failure.error.retriable, }; } const failure: KafkaJSDeleteTopicRecordsErrorPartition = { partition: 2, offset: '1840', error: new Error('Broker unavailable') as KafkaJSError, }; handleDeleteRecordsFailure(failure); ``` ## AI Coding Instructions - Treat `offset` as a string; Kafka offsets may exceed JavaScript's safe integer range. - Preserve the original `KafkaJSError` rather than replacing it with a generic error, since it contains Kafka-specific diagnostics and retry metadata. - Handle failures per partition instead of assuming a delete-records operation succeeds or fails for the entire topic. - Include the partition and offset in logs, metrics, and retry context to make partial failures traceable. # KafkaRequest **Kind:** Interface **Source:** [`packages/microservices/serializers/kafka-request.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/kafka-request.serializer.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaRequest` defines the normalized message shape consumed by the Kafka request serializer. It separates the Kafka message key, payload value, and headers so transport-specific metadata can be preserved when publishing or handling messages. ## Properties | Property | Type | |---|---| | `key` | `Buffer | string | null` | | `value` | `T` | | `headers` | `Record` | ## Diagram ```mermaid graph LR Request[KafkaRequest] Key[key: Buffer | string | null] Value[value: T] Headers[headers: Record] Request --> Key Request --> Value Request --> Headers ``` ## Usage ```ts import { KafkaRequest } from './kafka-request.serializer'; interface UserCreatedEvent { userId: string; email: string; } const request: KafkaRequest = { key: 'user-123', value: { userId: 'user-123', email: 'user@example.com', }, headers: { correlationId: 'req-8f2a', eventType: 'user.created', }, }; // Pass `request` to the Kafka serializer or client publish operation. ``` ## AI Coding Instructions - Use `key` for Kafka partitioning; provide a stable string or `Buffer` when related messages must remain ordered. - Set `key` to `null` when no partitioning key is required; do not use `undefined` unless the surrounding API explicitly supports it. - Keep `value` strongly typed with `KafkaRequest` so event payload contracts are preserved. - Store transport metadata such as correlation IDs, tracing values, and event types in `headers`. - Ensure header values are compatible with the configured Kafka client serialization behavior before publishing. ## Relationships - IMPORTS → `isNil` - IMPORTS → `isObject` - IMPORTS → `isPlainObject` - IMPORTS → `isString` - IMPORTS → `isUndefined` # LoggerEntryContent **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L633) **Part of:** [Microservices](subsystem-packages-microservices) `LoggerEntryContent` defines the core payload stored for a log entry in the Kafka microservices integration. It pairs a timestamp with a human-readable message, providing a consistent structure for log serialization, transport, and consumption. ## Properties | Property | Type | |---|---| | `timestamp` | `string` | | `message` | `string` | ## Diagram ```mermaid graph LR A[Application Event] --> B[LoggerEntryContent] B --> C[timestamp: string] B --> D[message: string] B --> E[Kafka Log Message] E --> F[Log Consumer / Monitoring] ``` ## Usage ```ts import type { LoggerEntryContent } from './kafka.interface'; const logEntry: LoggerEntryContent = { timestamp: new Date().toISOString(), message: 'Kafka consumer connected successfully', }; // Use as the content of a Kafka logging payload. console.log(JSON.stringify(logEntry)); ``` ## AI Coding Instructions - Always provide `timestamp` as a consistently formatted string; prefer `new Date().toISOString()`. - Keep `message` concise, descriptive, and useful for debugging or operational monitoring. - Do not add undeclared fields when a Kafka consumer expects the `LoggerEntryContent` contract. - Serialize the interface payload appropriately before publishing it to Kafka or another transport layer. # MaxPacketLengthExceededException **Kind:** Class **Source:** [`packages/microservices/errors/max-packet-length-exceeded.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/max-packet-length-exceeded.exception.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `Error` # MemberAssignment **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L607) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { version: number; assignment: Assignment; userData: Buffer; } ``` # MemberMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L601) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { version: number; topics: string[]; userData: Buffer; } ``` # NatsEvents **Kind:** Type **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) Nats events map for the Nats client. Key is the event name and value is the corresponding callback function. `NatsEvents` defines the event-to-callback map used by the NATS client. Each key identifies a NATS event, while its value is the handler invoked when that event is emitted, allowing applications to react to connection lifecycle changes or client errors. ## Definition ```ts { disconnect: DefaultCallback; reconnect: DefaultCallback; update: (data?: string | number | ServersChangedEvent) => any; } ``` ## Diagram ```mermaid graph LR A[NATS Client] -->|emits event| B[NatsEvents map] B -->|event name lookup| C[Registered callback] C --> D[Application handling] ``` ## Usage ```ts import type { NatsEvents } from './nats.events'; const events: NatsEvents = { connect: () => { console.info('Connected to NATS'); }, reconnect: () => { console.info('Reconnected to NATS'); }, error: (error) => { console.error('NATS client error:', error); }, }; // Pass the event map to the NATS client configuration or registration layer. createNatsClient({ servers: ['nats://localhost:4222'], events, }); ``` ## AI Coding Instructions - Use event names supported by the configured NATS client and provide a callback for each event that requires application-level handling. - Keep callbacks lightweight; delegate expensive work to application services, queues, or asynchronous workflows. - Always handle connection and error-related events to improve observability and recovery behavior. - Preserve the event-name-to-callback map structure when extending this type; do not invoke handlers directly outside the NATS event integration layer. # NatsEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L14) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECT` - `RECONNECT` - `UPDATE` # NatsStatus **Kind:** Enum **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECTED` - `RECONNECTING` - `CONNECTED` # NetSocketClosedException **Kind:** Class **Source:** [`packages/microservices/errors/net-socket-closed.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/net-socket-closed.exception.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `Error` # PartitionAssigner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L184) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts (config: { cluster: Cluster; groupId: string; logger: Logger; }) => Assigner ``` # PartitionerArgs **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L129) **Part of:** [Microservices](subsystem-packages-microservices) `PartitionerArgs` describes the inputs provided to a Kafka partitioning strategy when selecting a partition for an outgoing message. It combines the target topic, available partition metadata, and the message being published so custom partitioners can make deterministic routing decisions. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partitionMetadata` | `PartitionMetadata[]` | | `message` | `Message` | ## Diagram ```mermaid graph LR P[PartitionerArgs] --> T[topic: string] P --> PM[partitionMetadata: PartitionMetadata[]] P --> M[message: Message] T --> K[Kafka topic] PM --> AP[Available partitions] M --> PS[Custom partitioning strategy] AP --> PS K --> PS ``` ## Usage ```ts import type { PartitionerArgs } from '@nestjs/microservices'; function selectPartition({ topic, partitionMetadata, message, }: PartitionerArgs): number { const key = message.key?.toString() ?? topic; let hash = 0; for (const character of key) { hash = (hash * 31 + character.charCodeAt(0)) >>> 0; } const availablePartitions = partitionMetadata.filter( (partition) => partition.leader !== -1, ); return hash % availablePartitions.length; } ``` ## AI Coding Instructions - Use `message.key` when possible to ensure messages with the same key are consistently routed to the same partition. - Filter or account for unavailable partitions in `partitionMetadata` before returning a partition index. - Return a valid partition index based on the available metadata; avoid hardcoding partition counts. - Keep custom partitioning deterministic, since non-deterministic routing can break ordering guarantees. - Ensure the partitioner is registered through the Kafka client or producer configuration where custom partitioning is supported. ## How it works `PartitionerArgs` is an exported TypeScript interface representing the argument passed to the function returned by an `ICustomPartitioner`. The surrounding file is explicitly a KafkaJS type representation and says it must not contain NestJS logic. [`packages/microservices/external/kafka.interface.ts:1-8`](packages/microservices/external/kafka.interface.ts#L1-L8) [`packages/microservices/external/kafka.interface.ts:129-135`](packages/microservices/external/kafka.interface.ts#L129-L135) It requires three fields: - `topic`: a `string`. [`packages/microservices/external/kafka.interface.ts:129-131`](packages/microservices/external/kafka.interface.ts#L129-L131) - `partitionMetadata`: an array of `PartitionMetadata`, whose entries include a partition ID, leader, replicas, in-sync replicas, and an optional offline-replica list. [`packages/microservices/external/kafka.interface.ts:131`](packages/microservices/external/kafka.interface.ts#L131) [`packages/microservices/external/kafka.interface.ts:151-158`](packages/microservices/external/kafka.interface.ts#L151-L158) - `message`: a `Message` with a required `value`; it may also contain a key, explicit partition, headers, and timestamp. [`packages/microservices/external/kafka.interface.ts:132`](packages/microservices/external/kafka.interface.ts#L132) [`packages/microservices/external/kafka.interface.ts:121-127`](packages/microservices/external/kafka.interface.ts#L121-L127) A custom partitioner has the shape `() => (args: PartitionerArgs) => number`; therefore, its returned function receives this object and returns a numeric partition selection. `ProducerConfig.createPartitioner` optionally accepts that custom-partitioner factory. [`packages/microservices/external/kafka.interface.ts:110-119`](packages/microservices/external/kafka.interface.ts#L110-L119) [`packages/microservices/external/kafka.interface.ts:135-137`](packages/microservices/external/kafka.interface.ts#L135-L137) For example, an integration controller destructures `message` from `PartitionerArgs` and returns the numeric value of the `toPartition` message header; it assigns that function to `producer.createPartitioner`. [`integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts:18-22`](integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts#L18-L22) [`integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts:39-41`](integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts#L39-L41) `PartitionerArgs` itself declares no methods, validation, thrown errors, or runtime side effects. [`packages/microservices/external/kafka.interface.ts:129-133`](packages/microservices/external/kafka.interface.ts#L129-L133) # RedisStatus **Kind:** Enum **Source:** [`packages/microservices/events/redis.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/redis.events.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECTED` - `RECONNECTING` - `CONNECTED` # RequestQueueSizeEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L432) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ broker: string; clientId: string; queueSize: number; }> ``` # ResourceConfigQuery **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L343) **Part of:** [Microservices](subsystem-packages-microservices) `ResourceConfigQuery` defines a request for retrieving configuration values from a Kafka resource. It identifies the Kafka resource type and name, then specifies which configuration keys should be returned. ## Properties | Property | Type | |---|---| | `type` | `ConfigResourceTypes` | | `name` | `string` | | `configNames` | `string[]` | ## Diagram ```mermaid graph LR Query[ResourceConfigQuery] --> Type[type: ConfigResourceTypes] Query --> Name[name: string] Query --> ConfigNames[configNames: string[]] Type --> Resource[Kafka resource type] Name --> Target[Target resource name] ConfigNames --> Keys[Requested configuration keys] ``` ## Usage ```ts import type { ResourceConfigQuery } from './kafka.interface'; import { ConfigResourceTypes } from './kafka.interface'; const topicConfigQuery: ResourceConfigQuery = { type: ConfigResourceTypes.TOPIC, name: 'orders.created', configNames: [ 'retention.ms', 'cleanup.policy', 'min.insync.replicas', ], }; // Pass the query to the Kafka admin/configuration service. const configs = await kafkaConfigService.describeResourceConfig(topicConfigQuery); ``` ## AI Coding Instructions - Set `type` to the matching `ConfigResourceTypes` value for the target Kafka resource, such as a topic or broker. - Provide the exact Kafka resource identifier in `name`; topic names and broker identifiers must match the cluster configuration. - Include only the configuration keys needed in `configNames` to avoid unnecessary admin API requests. - Keep this interface aligned with the Kafka admin client integration that resolves resource configurations. - Validate or handle missing configuration keys when consuming the returned configuration response. ## How it works `ResourceConfigQuery` is an exported TypeScript interface in a file declared to represent KafkaJS package types only; it contains no executable implementation. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [packages/microservices/external/kafka.interface.ts:343-347](packages/microservices/external/kafka.interface.ts#L343-L347) - It describes one resource entry for `Admin.describeConfigs`. That method requires a `resources` array of these entries and an `includeSynonyms` boolean, then returns `Promise`. [packages/microservices/external/kafka.interface.ts:502-503](packages/microservices/external/kafka.interface.ts#L502-L503) [packages/microservices/external/kafka.interface.ts:548-551](packages/microservices/external/kafka.interface.ts#L548-L551) - Each query must contain: - `type`: a `ConfigResourceTypes` enum value. The declared values are `UNKNOWN` (`0`), `TOPIC` (`2`), `BROKER` (`4`), and `BROKER_LOGGER` (`8`). [packages/microservices/external/kafka.interface.ts:295-300](packages/microservices/external/kafka.interface.ts#L295-L300) [packages/microservices/external/kafka.interface.ts:343-345](packages/microservices/external/kafka.interface.ts#L343-L345) - `name`: a string. [packages/microservices/external/kafka.interface.ts:343-346](packages/microservices/external/kafka.interface.ts#L343-L346) - It may contain `configNames`, an optional string array. [packages/microservices/external/kafka.interface.ts:343-347](packages/microservices/external/kafka.interface.ts#L343-L347) - The corresponding response contains resource results with `configEntries`, an `errorCode`, an `errorMessage`, a resource name and type, plus a `throttleTime`. Individual entries include their name, value, source, default/sensitive/read-only flags, and synonyms. [packages/microservices/external/kafka.interface.ts:349-374](packages/microservices/external/kafka.interface.ts#L349-L374) - No runtime validation, error throwing, network action, or other side effect is implemented by `ResourceConfigQuery` itself in this file; it is only a structural type declaration. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [packages/microservices/external/kafka.interface.ts:343-347](packages/microservices/external/kafka.interface.ts#L343-L347) # RpcDecoratorMetadata **Kind:** Interface **Source:** [`packages/microservices/errors/invalid-grpc-message-decorator.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/errors/invalid-grpc-message-decorator.exception.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) `RpcDecoratorMetadata` describes the metadata required for an RPC decorator in the microservices layer. It identifies the target gRPC service, RPC method, and streaming mode so validation and error handling can report invalid decorator configurations consistently. ## Properties | Property | Type | |---|---| | `service` | `string` | | `rpc` | `string` | | `streaming` | `string` | ## Diagram ```mermaid graph LR Decorator[RPC Decorator] --> Metadata[RpcDecoratorMetadata] Metadata --> Service[service: gRPC service name] Metadata --> Rpc[rpc: RPC method name] Metadata --> Streaming[streaming: streaming mode] Metadata --> Validation[Decorator validation / error reporting] ``` ## Usage ```ts import type { RpcDecoratorMetadata } from './errors/invalid-grpc-message-decorator.exception'; const metadata: RpcDecoratorMetadata = { service: 'UsersService', rpc: 'GetUser', streaming: 'unary', }; function validateRpcDecorator(config: RpcDecoratorMetadata) { if (!config.service || !config.rpc) { throw new Error('RPC decorators must define a service and RPC method.'); } return config; } validateRpcDecorator(metadata); ``` ## AI Coding Instructions - Provide all three fields—`service`, `rpc`, and `streaming`—when creating `RpcDecoratorMetadata`. - Keep `service` and `rpc` aligned with the names defined in the associated gRPC `.proto` contract. - Use a consistent streaming value that matches the RPC method type, such as unary, client-streaming, server-streaming, or bidirectional streaming. - Use this interface when constructing validation errors for invalid gRPC message decorators rather than passing untyped metadata objects. ## Relationships - IMPORTS → `RuntimeException` # RpcHandlerMetadata **Kind:** Interface **Source:** [`packages/microservices/context/rpc-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-context-creator.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) `RpcHandlerMetadata` describes the runtime metadata required to invoke an RPC handler in the microservices context. It tracks the handler argument count, reflected parameter types, and provides a module-aware resolver for RPC parameter metadata. ## Properties | Property | Type | |---|---| | `argsLength` | `number` | | `paramtypes` | `any[]` | | `getParamsMetadata` | `(moduleKey: string) => RpcParamProperties[]` | ## Diagram ```mermaid graph LR A[RPC Request] --> B[RpcContextCreator] B --> C[RpcHandlerMetadata] C --> D[argsLength] C --> E[paramtypes] C --> F[getParamsMetadata(moduleKey)] F --> G[RpcParamProperties[]] D --> H[Resolved Handler Arguments] E --> H G --> H H --> I[RPC Handler] ``` ## Usage ```ts import type { RpcHandlerMetadata } from './rpc-context-creator'; import type { RpcParamProperties } from './rpc-params-factory'; const handlerMetadata: RpcHandlerMetadata = { argsLength: 2, paramtypes: [String, Object], getParamsMetadata(moduleKey: string): RpcParamProperties[] { // Resolve metadata registered for the handler within this module. return getRegisteredRpcParams(moduleKey); }, }; function createHandlerArgs( metadata: RpcHandlerMetadata, moduleKey: string, payload: unknown, context: unknown, ) { const args = new Array(metadata.argsLength); const params = metadata.getParamsMetadata(moduleKey); params.forEach(({ index, type }) => { args[index] = type === 'payload' ? payload : context; }); return args; } ``` ## AI Coding Instructions - Keep `argsLength` aligned with the target RPC handler's declared parameter count so argument arrays are created at the correct size. - Preserve `paramtypes` from reflection metadata; consumers may use these types for transformation, validation, or dependency resolution. - Implement `getParamsMetadata` as module-aware logic, since the same handler metadata may be resolved differently across module contexts. - Return `RpcParamProperties[]` in parameter-index order or ensure each item includes the correct target index before constructing handler arguments. - Avoid caching parameter metadata globally without including `moduleKey` in the cache key. ## How it works ## `RpcHandlerMetadata` `RpcHandlerMetadata` is an exported TypeScript interface describing cached, per-RPC-handler parameter metadata used by `RpcContextCreator`. Its three fields are `argsLength`, `paramtypes`, and `getParamsMetadata(moduleKey)`. [packages/microservices/context/rpc-context-creator.ts:35-39] - **`argsLength: number`** is calculated from the reflected parameter-metadata keys as the highest parameter index plus one, or `0` when there are no keys. [packages/microservices/context/rpc-context-creator.ts:184-185] [packages/core/helpers/context-utils.ts:52-56] - **`paramtypes: any[]`** holds the reflected design-time parameter types for the controller method. [packages/microservices/context/rpc-context-creator.ts:186-189] [packages/core/helpers/context-utils.ts:29-34] - **`getParamsMetadata(moduleKey)`** is a closure that converts the reflected RPC parameter entries into `RpcParamProperties[]` for a specified module key. [packages/microservices/context/rpc-context-creator.ts:195-202] `RpcParamProperties` extends `ParamProperties` with an optional `metatype`; each resulting parameter record includes its index, type, data, pipe list, and an `extractValue` function. [packages/microservices/context/rpc-context-creator.ts:34-39] [packages/core/helpers/context-utils.ts:15-21] `RpcContextCreator.getMetadata()` first looks up this object in a `HandlerMetadataStorage` cache by controller instance and method name. If cached metadata exists, it returns that object; otherwise, it reflects parameter metadata, constructs the interface object, stores it, and returns it. [packages/microservices/context/rpc-context-creator.ts:44-45] [packages/microservices/context/rpc-context-creator.ts:174-210] The storage key combines the controller constructor’s assigned ID or name with the method name. [packages/core/helpers/handler-metadata-storage.ts:50-64] When creating an RPC callback wrapper, `RpcContextCreator.create()` reads all three fields: it creates an `undefined`-filled argument array with `argsLength`, converts parameter metadata using the supplied module key, and merges each parameter’s reflected type into its metadata when parameter types exist. [packages/microservices/context/rpc-context-creator.ts:68-73] [packages/microservices/context/rpc-context-creator.ts:104-108] [packages/microservices/context/rpc-context-creator.ts:125-136] [packages/core/helpers/context-utils.ts:58-61] [packages/core/helpers/context-utils.ts:64-75] Calling `getParamsMetadata()` sets the pipes context’s module context and creates concrete pipe instances for each parameter entry. For standard RPC parameter types, its extraction function reads payload from argument `0`—optionally selecting a payload property from `data`—context from argument `1`, or the gRPC call from argument `2`; unsupported types return `null`. [packages/microservices/context/rpc-context-creator.ts:213-242] [packages/microservices/factories/rpc-params-factory.ts:4-21] For custom route-argument metadata, it instead creates an extractor that invokes the metadata factory with the parameter data and an RPC-typed `ExecutionContextHost`; a non-function factory yields `null`. [packages/microservices/context/rpc-context-creator.ts:228-235] [packages/core/helpers/context-utils.ts:77-97] If no reflected RPC parameter metadata is found, `getMetadata()` uses its `defaultCallMetadata` argument. The ordinary default defines parameter `0` as the payload; listener registration switches to a gRPC default that also defines context at index `1` and gRPC call at index `2` when the server is a `ServerGrpc`. [packages/microservices/context/rpc-context-creator.ts:178-184] [packages/microservices/context/rpc-metadata-constants.ts:3-10] [packages/microservices/listeners-controller.ts:71-74] The interface itself declares no validation, errors, or side effects. In the visible construction path, there is no explicit error handling around metadata reflection or conversion. [packages/microservices/context/rpc-context-creator.ts:168-210] ## Relationships - IMPORTS → `CUSTOM_ROUTE_ARGS_METADATA` - IMPORTS → `PARAMTYPES_METADATA` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `PipeTransform` - IMPORTS → `isEmpty` - IMPORTS → `FORBIDDEN_MESSAGE` - IMPORTS → `GuardsConsumer` - IMPORTS → `GuardsContextCreator` - IMPORTS → `ContextUtils` - IMPORTS → `ParamProperties` - IMPORTS → `ExecutionContextHost` - IMPORTS → `HandlerMetadataStorage` - IMPORTS → `ParamsMetadata` - IMPORTS → `STATIC_CONTEXT` - IMPORTS → `InterceptorsConsumer` - IMPORTS → `InterceptorsContextCreator` - IMPORTS → `PipesConsumer` - IMPORTS → `PipesContextCreator` # RpcParamtype **Kind:** Enum **Source:** [`packages/microservices/enums/rpc-paramtype.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/enums/rpc-paramtype.enum.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `PAYLOAD` - `CONTEXT` - `GRPC_CALL` ## Relationships - IMPORTS → `RouteParamtypes` # AssignerProtocol **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L613) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { MemberMetadata: ISerializer; MemberAssignment: ISerializer; } ``` # AsyncMicroserviceOptions **Kind:** Type **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L37) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { inject: InjectionToken[]; useFactory: (...args: any[]) => MicroserviceOptions; } ``` # AsyncOptions **Kind:** Type **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L42) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { inject: InjectionToken[]; useFactory: (...args: any[]) => T; } ``` # ClientProperties **Kind:** Interface **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L16) **Part of:** [Microservices](subsystem-packages-microservices) `ClientProperties` describes a discovered microservice client configuration within listener metadata. It pairs the property name used to access the client on a class or instance with the corresponding NestJS `ClientOptions` configuration used to create or identify that client. ## Properties | Property | Type | |---|---| | `property` | `string` | | `metadata` | `ClientOptions` | ## Diagram ```mermaid graph LR A[Listener Metadata Explorer] --> B[ClientProperties] B --> C[property: string] B --> D[metadata: ClientOptions] C --> E[Client property on provider] D --> F[Microservice transport configuration] ``` ## Usage ```ts import type { ClientOptions } from '@nestjs/microservices'; interface ClientProperties { property: string; metadata: ClientOptions; } const clientProperties: ClientProperties = { property: 'paymentsClient', metadata: { transport: 0, // Transport.TCP options: { host: 'localhost', port: 3001, }, }, }; // Example: use the property name to locate the configured client. console.log(`Discovered client property: ${clientProperties.property}`); console.log(clientProperties.metadata); ``` ## AI Coding Instructions - Use `property` as the exact property key declared for the microservice client on the provider or controller. - Provide valid NestJS `ClientOptions` values in `metadata`, including an appropriate `transport` and transport-specific options. - Preserve both fields when transforming listener metadata; the property name and client configuration must remain associated. - Avoid treating `property` as a client instance—it is a string identifier used to locate or describe the client. - Integrate this interface with metadata exploration logic that discovers `@Client()`-configured microservice clients. ## Relationships - IMPORTS → `Controller` - IMPORTS → `isFunction` - IMPORTS → `isUndefined` - IMPORTS → `MetadataScanner` # ConsumerDeserializer **Kind:** Type **Source:** [`packages/microservices/interfaces/deserializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/deserializer.interface.ts#L18) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Deserializer< any, IncomingRequest | IncomingEvent > ``` # ConsumerRebalancingEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L977) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ groupId: string; memberId: string; }> ``` # ConsumerSubscribeTopics **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1038) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { topics: (string | RegExp)[]; fromBeginning?: boolean; } ``` # CustomClientOptions **Kind:** Interface **Source:** [`packages/microservices/interfaces/client-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/client-metadata.interface.ts#L29) **Part of:** [Microservices](subsystem-packages-microservices) `CustomClientOptions` defines the metadata required to register or create a custom microservice client implementation. It pairs a `ClientProxy` class with an arbitrary options object that is passed to or used by the custom client during initialization. ## Properties | Property | Type | |---|---| | `customClass` | `Type` | | `options` | `Record` | ## Diagram ```mermaid graph LR A[CustomClientOptions] --> B[customClass: Type] A --> C[options: Record] B --> D[Custom ClientProxy Implementation] C --> D ``` ## Usage ```ts import { ClientProxy } from '@nestjs/microservices'; import type { CustomClientOptions } from '@nestjs/microservices'; class CustomClient extends ClientProxy { // Implement required ClientProxy methods... } const clientOptions: CustomClientOptions = { customClass: CustomClient, options: { endpoint: 'https://api.example.com', apiKey: process.env.API_KEY, timeout: 5000, }, }; // Use clientOptions when registering or constructing // a custom microservice client integration. ``` ## AI Coding Instructions - Set `customClass` to a class that extends `ClientProxy` and implements its required transport behavior. - Pass client-specific configuration through `options`; avoid relying on undeclared global configuration. - Keep option keys aligned with the custom client's constructor or initialization logic. - Validate required values in the custom client implementation, since `options` accepts arbitrary key-value pairs. - Use this interface when integrating non-standard transports or custom client proxy implementations. # CustomStrategy **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L50) **Part of:** [Microservices](subsystem-packages-microservices) `CustomStrategy` defines the configuration required to register a custom NestJS microservice transport. It pairs a `CustomTransportStrategy` implementation with an `options` object containing transport-specific settings passed to that strategy during initialization. ## Properties | Property | Type | |---|---| | `strategy` | `CustomTransportStrategy` | | `options` | `Record` | ## Diagram ```mermaid graph LR A[Microservice Configuration] --> B[CustomStrategy] B --> C[strategy: CustomTransportStrategy] B --> D[options: Record<string, any>] C --> E[Custom Transport Implementation] D --> E E --> F[Microservice Message Transport] ``` ## Usage ```ts import { CustomTransportStrategy, NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; class RedisTransportStrategy implements CustomTransportStrategy { listen(callback: () => void) { // Initialize the custom transport listener. callback(); } close() { // Close transport connections and release resources. } } async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { strategy: new RedisTransportStrategy(), options: { host: 'localhost', port: 6379, channel: 'orders', }, }); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Implement `strategy` as a valid `CustomTransportStrategy` with lifecycle methods such as `listen()` and `close()`. - Keep `options` specific to the custom transport; validate required values such as connection URLs, ports, or credentials inside the strategy. - Pass this object to `NestFactory.createMicroservice()` when using a non-standard transport implementation. - Ensure `close()` cleans up open sockets, subscriptions, timers, and other transport resources. - Avoid assuming a fixed shape for `options`; safely narrow or validate option values before use. # DeleteAclResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L497) **Part of:** [Microservices](subsystem-packages-microservices) `DeleteAclResponse` represents the Kafka broker response returned after a delete-ACL request. It includes the broker-applied throttle duration and a result entry for each ACL filter submitted in the request. ## Properties | Property | Type | |---|---| | `throttleTime` | `number` | | `filterResponses` | `DeleteAclFilterResponses[]` | ## Diagram ```mermaid graph LR Client[Kafka Client] --> Request[Delete ACL Request] Request --> Broker[Kafka Broker] Broker --> Response[DeleteAclResponse] Response --> Throttle[throttleTime: number] Response --> Filters[filterResponses: DeleteAclFilterResponses[]] Filters --> FilterResult[Per-filter deletion results] ``` ## Usage ```ts import type { DeleteAclResponse } from './kafka.interface'; function handleDeleteAclResponse(response: DeleteAclResponse): void { console.log(`Broker throttle time: ${response.throttleTime}ms`); for (const filterResponse of response.filterResponses) { console.log('Processed ACL deletion filter:', filterResponse); } } // Example response returned by a Kafka ACL deletion operation const response: DeleteAclResponse = await kafkaAdmin.deleteAcls({ filters: [ { resourceType: 2, resourceName: 'orders', patternType: 3, }, ], }); handleDeleteAclResponse(response); ``` ## AI Coding Instructions - Treat `filterResponses` as a per-filter result list; preserve its ordering when correlating results with the original delete-ACL filters. - Use `throttleTime` to respect Kafka broker rate limiting before issuing subsequent administrative requests. - Inspect each `DeleteAclFilterResponses` entry for filter-specific errors rather than assuming the overall request succeeded. - Keep this interface aligned with the Kafka Delete ACLs protocol response schema when upgrading Kafka client or protocol support. ## How it works `DeleteAclResponse` is an exported TypeScript interface in a file intended to represent KafkaJS package types rather than NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) It describes the resolved value of `Admin.deleteAcls`, whose argument is an object containing a required `filters: AclFilter[]` property. [packages/microservices/external/kafka.interface.ts:497-500](packages/microservices/external/kafka.interface.ts#L497-L500) [packages/microservices/external/kafka.interface.ts:502-560](packages/microservices/external/kafka.interface.ts#L502-L560) - `throttleTime` is a required `number`. [packages/microservices/external/kafka.interface.ts:497-499](packages/microservices/external/kafka.interface.ts#L497-L499) - `filterResponses` is a required array of `DeleteAclFilterResponses`. [packages/microservices/external/kafka.interface.ts:497-500](packages/microservices/external/kafka.interface.ts#L497-L500) - Each filter response contains a required numeric `errorCode`, an optional `errorMessage`, and a required `matchingAcls` array. [packages/microservices/external/kafka.interface.ts:491-495](packages/microservices/external/kafka.interface.ts#L491-L495) - Each matching ACL records its resource type, resource name, resource-pattern type, principal, host, operation, permission type, numeric error code, and optional error message. [packages/microservices/external/kafka.interface.ts:479-489](packages/microservices/external/kafka.interface.ts#L479-L489) The deletion filters require `resourceType`, `resourcePatternType`, `operation`, and `permissionType`; `resourceName`, `principal`, and `host` are optional. [packages/microservices/external/kafka.interface.ts:469-477](packages/microservices/external/kafka.interface.ts#L469-L477) This interface contains no runtime implementation, validation, thrown-error declaration, or side-effect logic; it only declares the response shape. [packages/microservices/external/kafka.interface.ts:1-8](packages/microservices/external/kafka.interface.ts#L1-L8) [packages/microservices/external/kafka.interface.ts:497-500](packages/microservices/external/kafka.interface.ts#L497-L500) # GroupMemberAssignment **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L236) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { memberId: string; memberAssignment: Buffer; } ``` # GroupOverview **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L899) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { groupId: string; protocolType: string; } ``` # IResourceConfigEntry **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L376) **Part of:** [Microservices](subsystem-packages-microservices) `IResourceConfigEntry` represents a single Kafka resource configuration property as a name/value pair. It is used when defining or reading resource-level settings, such as topic, broker, or consumer configuration entries. ## Properties | Property | Type | |---|---| | `name` | `string` | | `value` | `string` | ## Diagram ```mermaid graph LR Config[IResourceConfigEntry] --> Name[name: string] Config --> Value[value: string] Config --> Kafka[Kafka resource configuration] ``` ## Usage ```ts import type { IResourceConfigEntry } from './kafka.interface'; const topicConfig: IResourceConfigEntry = { name: 'retention.ms', value: '604800000', }; // Example: include the entry in a Kafka topic configuration request const resourceConfig: IResourceConfigEntry[] = [ topicConfig, { name: 'cleanup.policy', value: 'delete', }, ]; ``` ## AI Coding Instructions - Use `name` for the exact Kafka configuration key, such as `retention.ms` or `cleanup.policy`. - Store configuration values as strings, even when the underlying Kafka setting represents a number or boolean. - Prefer typed `IResourceConfigEntry[]` collections when passing multiple resource settings to Kafka administration APIs. - Do not add extra fields to configuration entries; consumers expect only `name` and `value`. - Validate Kafka-specific configuration names and allowed values before submitting changes to a broker or topic. # ISerializer **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L596) **Part of:** [Microservices](subsystem-packages-microservices) # ITopicMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L280) **Part of:** [Microservices](subsystem-packages-microservices) `ITopicMetadata` describes Kafka topic metadata returned or consumed by the microservices Kafka integration. It identifies a topic by name and provides metadata for each of its partitions, enabling clients to inspect topic topology and partition-level state. ## Properties | Property | Type | |---|---| | `name` | `string` | | `partitions` | `PartitionMetadata[]` | ## Diagram ```mermaid graph LR TopicMetadata["ITopicMetadata"] Name["name: string"] Partitions["partitions: PartitionMetadata[]"] TopicMetadata --> Name TopicMetadata --> Partitions Partitions --> Partition1["PartitionMetadata"] Partitions --> PartitionN["PartitionMetadata"] ``` ## Usage ```ts import type { ITopicMetadata } from './kafka.interface'; const topicMetadata: ITopicMetadata = { name: 'orders.created', partitions: [ { partitionId: 0, leader: 1, replicas: [1, 2, 3], isr: [1, 2, 3], }, ], }; console.log( `Topic "${topicMetadata.name}" has ${topicMetadata.partitions.length} partition(s).`, ); ``` ## AI Coding Instructions - Always provide a non-empty, valid Kafka topic name in `name`. - Populate `partitions` with `PartitionMetadata` objects returned by or compatible with the Kafka metadata client. - Treat partition metadata as a snapshot; refresh it when leader, replica, or partition assignments may have changed. - Do not assume partition array indexes match partition IDs; use the partition identifier exposed by each `PartitionMetadata` entry. - Keep this interface aligned with the Kafka adapter's metadata response shape when upgrading Kafka client dependencies. # KafkaJSConnectionErrorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1299) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSConnectionErrorMetadata` describes connection-specific metadata reported when a KafkaJS broker connection fails. It identifies the affected broker endpoint and the associated Kafka error code, allowing microservice error handling and logging to provide actionable diagnostics. ## Properties | Property | Type | |---|---| | `broker` | `string` | | `code` | `string` | ## Diagram ```mermaid graph LR A[KafkaJS broker connection attempt] --> B{Connection error} B --> C[KafkaJSConnectionErrorMetadata] C --> D[broker: string] C --> E[code: string] C --> F[Logging / retry / error handling] ``` ## Usage ```ts import type { KafkaJSConnectionErrorMetadata } from './kafka.interface'; function logKafkaConnectionError( metadata: KafkaJSConnectionErrorMetadata, ): void { console.error( `Kafka connection failed for broker ${metadata.broker} (${metadata.code})`, ); } const connectionError: KafkaJSConnectionErrorMetadata = { broker: 'localhost:9092', code: 'ECONNREFUSED', }; logKafkaConnectionError(connectionError); ``` ## AI Coding Instructions - Always provide both `broker` and `code` when creating this metadata object. - Use the broker value to identify the exact Kafka endpoint, typically in `host:port` format. - Preserve the original KafkaJS or Node.js connection error code where possible; do not replace it with a generic message. - Integrate this metadata into structured logs, retry decisions, and exception diagnostics. - Avoid storing credentials or sensitive connection details in the `broker` field. # KafkaJSDeleteTopicRecordsErrorTopic **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1271) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSDeleteTopicRecordsErrorTopic` describes delete-record failures for a single Kafka topic. It groups the topic name with partition-level error details, allowing callers to identify which partitions could not be truncated during a KafkaJS delete-records operation. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partitions` | `KafkaJSDeleteTopicRecordsErrorPartition[]` | ## Diagram ```mermaid graph LR A[KafkaJS deleteRecords response] --> B[KafkaJSDeleteTopicRecordsErrorTopic] B --> C[topic: string] B --> D[partitions: KafkaJSDeleteTopicRecordsErrorPartition[]] D --> E[Partition-specific error details] ``` ## Usage ```ts import type { KafkaJSDeleteTopicRecordsErrorTopic, } from './kafka.interface'; const topicError: KafkaJSDeleteTopicRecordsErrorTopic = { topic: 'user-events', partitions: [ { partition: 0, error: new Error('Offset is out of range'), }, ], }; console.error( `Failed to delete records for topic "${topicError.topic}"`, topicError.partitions, ); ``` ## AI Coding Instructions - Use this interface when representing delete-record errors grouped by Kafka topic. - Always provide the exact Kafka topic name in `topic`; do not use a wildcard or consumer-group name. - Populate `partitions` with partition-level error objects so failures can be retried or logged precisely. - Handle partial failures: one partition may fail while other partitions in the same topic succeed. - Keep this type aligned with the KafkaJS delete-records response structure and its partition error type. # KafkaJSNumberOfRetriesExceededMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1294) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSNumberOfRetriesExceededMetadata` describes retry details when a KafkaJS operation exceeds its configured retry limit. It records the number of retry attempts made and the total retry time, allowing error handlers and observability tooling to report retry exhaustion accurately. ## Properties | Property | Type | |---|---| | `retryCount` | `number` | | `retryTime` | `number` | ## Diagram ```mermaid graph LR A[KafkaJS operation] --> B{Retry attempt fails?} B -->|Yes| C[Increment retryCount] C --> D[Accumulate retryTime] D --> E{Retries exceeded?} E -->|No| A E -->|Yes| F[KafkaJSNumberOfRetriesExceededMetadata] F --> G[Error handling / logging] ``` ## Usage ```ts import type { KafkaJSNumberOfRetriesExceededMetadata } from './kafka.interface'; function logRetryExhaustion( metadata: KafkaJSNumberOfRetriesExceededMetadata, ) { console.error( `Kafka retries exhausted after ${metadata.retryCount} attempts ` + `and ${metadata.retryTime}ms.`, ); } const retryMetadata: KafkaJSNumberOfRetriesExceededMetadata = { retryCount: 5, retryTime: 12_000, }; logRetryExhaustion(retryMetadata); ``` ## AI Coding Instructions - Populate `retryCount` with the total number of retry attempts that occurred before failure. - Store `retryTime` as a duration in milliseconds; do not use timestamps or seconds. - Use this interface when handling KafkaJS retry-exhaustion errors to keep logging and error reporting type-safe. - Avoid mutating retry metadata after it is attached to an error; treat it as a snapshot of the failed operation. # KafkaJSOffsetOutOfRangeMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1289) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSOffsetOutOfRangeMetadata` describes the Kafka topic and partition associated with an offset-out-of-range condition. It is used by the microservices Kafka integration to identify the exact partition that requires offset recovery, reset, or error handling. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partition` | `number` | ## Diagram ```mermaid graph LR A[Kafka Consumer] --> B[Offset Out of Range Error] B --> C[KafkaJSOffsetOutOfRangeMetadata] C --> D[topic: string] C --> E[partition: number] C --> F[Offset Recovery / Retry Handling] ``` ## Usage ```ts import type { KafkaJSOffsetOutOfRangeMetadata } from './kafka.interface'; function handleOffsetOutOfRange( metadata: KafkaJSOffsetOutOfRangeMetadata, ) { console.warn( `Offset is out of range for ${metadata.topic}[${metadata.partition}]`, ); // Use the topic and partition to seek to a valid offset or apply recovery logic. } handleOffsetOutOfRange({ topic: 'orders.created', partition: 2, }); ``` ## AI Coding Instructions - Provide a valid Kafka topic name in `topic`; do not use a consumer group ID or broker address. - Use the numeric Kafka partition index in `partition`, typically starting at `0`. - Preserve both fields when forwarding offset-out-of-range errors to recovery or logging code. - Use this metadata with Kafka consumer offset reset or seek logic rather than treating it as a message payload. # KafkaJSServerDoesNotSupportApiKeyMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1322) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSServerDoesNotSupportApiKeyMetadata` describes a Kafka API operation that is not supported by the connected KafkaJS server or broker. It pairs the numeric Kafka API key with its human-readable API name, enabling capability checks, diagnostics, and compatibility handling. ## Properties | Property | Type | |---|---| | `apiKey` | `number` | | `apiName` | `string` | ## Diagram ```mermaid graph LR Client[KafkaJS Client] --> CapabilityCheck[Broker API Capability Check] CapabilityCheck --> Unsupported[KafkaJSServerDoesNotSupportApiKeyMetadata] Unsupported --> ApiKey[apiKey: number] Unsupported --> ApiName[apiName: string] Unsupported --> Handling[Compatibility Handling / Error Reporting] ``` ## Usage ```ts import type { KafkaJSServerDoesNotSupportApiKeyMetadata } from './kafka.interface'; function formatUnsupportedApi( metadata: KafkaJSServerDoesNotSupportApiKeyMetadata, ): string { return `Kafka broker does not support ${metadata.apiName} (API key ${metadata.apiKey}).`; } const unsupportedApi: KafkaJSServerDoesNotSupportApiKeyMetadata = { apiKey: 68, apiName: 'ConsumerGroupHeartbeat', }; console.warn(formatUnsupportedApi(unsupportedApi)); ``` ## AI Coding Instructions - Use this interface only for Kafka APIs confirmed as unsupported by the connected broker or KafkaJS server. - Preserve both `apiKey` and `apiName`; the numeric key supports protocol-level handling, while the name improves logs and error messages. - Keep `apiKey` aligned with Kafka protocol API key values rather than application-specific identifiers. - Use the metadata when building compatibility errors, fallback behavior, or broker capability diagnostics. # KafkaJSStaleTopicMetadataAssignmentMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1317) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSStaleTopicMetadataAssignmentMetadata` describes stale Kafka topic metadata detected during partition assignment. It identifies the affected topic and lists partitions whose metadata is unknown or outdated, allowing the microservice transport layer to refresh topic metadata before retrying assignment or consumption operations. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `unknownPartitions` | `PartitionMetadata[]` | ## Diagram ```mermaid graph LR A[KafkaJSStaleTopicMetadataAssignmentMetadata] --> B[topic: string] A --> C[unknownPartitions: PartitionMetadata[]] C --> D[Partition 0 metadata] C --> E[Partition 1 metadata] C --> F[Additional unknown partitions] ``` ## Usage ```ts import type { KafkaJSStaleTopicMetadataAssignmentMetadata, PartitionMetadata, } from './kafka.interface'; const staleMetadata: KafkaJSStaleTopicMetadataAssignmentMetadata = { topic: 'orders.created', unknownPartitions: [ { partitionId: 2, leader: -1, replicas: [], isr: [], } as PartitionMetadata, ], }; async function refreshStaleTopicMetadata( metadata: KafkaJSStaleTopicMetadataAssignmentMetadata, ) { console.warn( `Refreshing metadata for ${metadata.topic}; ` + `unknown partitions: ${metadata.unknownPartitions.map( ({ partitionId }) => partitionId, ).join(', ')}`, ); // Refresh Kafka client/admin metadata before retrying assignment. } ``` ## AI Coding Instructions - Populate `topic` with the exact Kafka topic name used by the producer or consumer configuration. - Include only partitions with missing, unknown, or stale metadata in `unknownPartitions`. - Treat this interface as diagnostic and retry metadata refresh or assignment after handling it. - Preserve the `PartitionMetadata` structure returned by KafkaJS; avoid creating partial partition objects unless explicitly supported. - Handle empty `unknownPartitions` safely when logging or deciding whether a metadata refresh is required. # MessageRequestProperties **Kind:** Interface **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L30) **Part of:** [Microservices](subsystem-packages-microservices) `MessageRequestProperties` describes the request and reply message patterns associated with a microservice listener. It groups the inbound `requestPattern` with the corresponding outbound `replyPattern`, allowing metadata exploration tools to identify request-response communication contracts. ## Properties | Property | Type | |---|---| | `requestPattern` | `PatternMetadata` | | `replyPattern` | `PatternMetadata` | ## Diagram ```mermaid graph LR Listener[Microservice Listener Metadata] --> Properties[MessageRequestProperties] Properties --> Request[requestPattern: PatternMetadata] Properties --> Reply[replyPattern: PatternMetadata] Request --> Incoming[Incoming request message] Reply --> Outgoing[Reply message] ``` ## Usage ```ts import type { MessageRequestProperties } from './listener-metadata-explorer'; const messageRequest: MessageRequestProperties = { requestPattern: { pattern: 'users.get', }, replyPattern: { pattern: 'users.get.reply', }, }; // Use the metadata when inspecting or documenting listener contracts. console.log( `Request pattern: ${messageRequest.requestPattern.pattern}`, ); console.log( `Reply pattern: ${messageRequest.replyPattern.pattern}`, ); ``` ## AI Coding Instructions - Keep `requestPattern` and `replyPattern` paired when representing request-response message handlers. - Use valid `PatternMetadata` objects for both fields; do not substitute raw strings unless the metadata type explicitly permits them. - Preserve the distinction between request and reply patterns when inspecting listener metadata or generating documentation. - Update consumers of listener metadata if the shape or semantics of either pattern changes. # NatsCodec **Kind:** Interface **Source:** [`packages/microservices/external/nats-codec.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/nats-codec.interface.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) # PartitionOffset **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L771) **Part of:** [Microservices](subsystem-packages-microservices) `PartitionOffset` represents a Kafka consumer position within a specific topic partition. It pairs a numeric partition identifier with a string offset, allowing Kafka-related integrations to track, commit, or seek to an exact message position. ## Properties | Property | Type | |---|---| | `partition` | `number` | | `offset` | `string` | ## Diagram ```mermaid graph LR Consumer[Kafka Consumer] --> PartitionOffset PartitionOffset --> Partition[partition: number] PartitionOffset --> Offset[offset: string] PartitionOffset --> Commit[Commit or seek consumer position] ``` ## Usage ```ts import type { PartitionOffset } from './kafka.interface'; const checkpoint: PartitionOffset = { partition: 2, offset: '1542', }; // Example: use the position when committing processed messages. await consumer.commitOffsets([ { topic: 'orders', partition: checkpoint.partition, offset: checkpoint.offset, }, ]); ``` ## AI Coding Instructions - Keep `partition` as a zero-based numeric Kafka partition index. - Store `offset` as a string; Kafka client libraries commonly use string offsets to avoid integer precision issues. - Use this interface when passing partition-specific checkpoints between consumer, retry, seek, or commit logic. - Do not treat the offset as the currently processed message unless the surrounding Kafka client API explicitly defines it that way; commit semantics often expect the next offset to consume. ## How it works `PartitionOffset` is an exported TypeScript interface representing an offset for one Kafka partition. It has two required properties: - `partition`: a `number` identifying the partition. [packages/microservices/external/kafka.interface.ts:771-773] - `offset`: a `string` representing that partition’s offset. [packages/microservices/external/kafka.interface.ts:771-774] It is a type-only declaration in a file intended to represent KafkaJS package types, not NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8] The interface contains no runtime implementation, validation, error handling, or side effects. [packages/microservices/external/kafka.interface.ts:771-774] The type is used in several offset-oriented shapes: - `TopicOffsets.partitions` is an array of `PartitionOffset` values, grouped under a topic string. [packages/microservices/external/kafka.interface.ts:776-783] - `SeekEntry` is an alias of `PartitionOffset`. [packages/microservices/external/kafka.interface.ts:438] - `FetchOffsetsPartition` extends it with required `metadata: string | null`. [packages/microservices/external/kafka.interface.ts:440-442] - `Admin.fetchTopicOffsets()` returns entries containing these fields plus `high` and `low` string fields; `fetchTopicOffsetsByTimestamp()` returns `SeekEntry` values. [packages/microservices/external/kafka.interface.ts:526-532] - `Admin.setOffsets()` and `Admin.deleteTopicRecords()` accept arrays of `SeekEntry` values in their `partitions` options. [packages/microservices/external/kafka.interface.ts:538-542] [packages/microservices/external/kafka.interface.ts:562-565] # PatternHandler **Kind:** Enum **Source:** [`packages/microservices/enums/pattern-handler.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/enums/pattern-handler.enum.ts#L1) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `MESSAGE` - `EVENT` # ProducerSerializer **Kind:** Type **Source:** [`packages/microservices/interfaces/serializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/serializer.interface.ts#L14) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Serializer< OutgoingEvent | OutgoingRequest, any > ``` # ReadPacket **Kind:** Interface **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) `ReadPacket` represents a normalized incoming microservice message. It carries the routing `pattern` used to identify the handler and the typed `data` payload passed to that handler. ## Properties | Property | Type | |---|---| | `pattern` | `any` | | `data` | `T` | ## Diagram ```mermaid graph LR Client[Microservice Client] --> Packet[ReadPacket] Packet --> Pattern[pattern: message route] Packet --> Data[data: T payload] Pattern --> Handler[Matching Message Handler] Data --> Handler ``` ## Usage ```ts import type { ReadPacket } from './interfaces/packet.interface'; interface CreateUserPayload { email: string; name: string; } const packet: ReadPacket = { pattern: 'users.create', data: { email: 'ada@example.com', name: 'Ada Lovelace', }, }; function handleCreateUser(message: ReadPacket) { if (message.pattern !== 'users.create') { return; } return createUser(message.data); } ``` ## AI Coding Instructions - Use a generic type parameter for `data` so message payloads remain strongly typed. - Treat `pattern` as the message-routing identifier; ensure it matches the corresponding microservice handler pattern. - Validate or transform `data` at the application boundary before relying on its fields. - Avoid assuming a specific `pattern` type, because it is intentionally declared as `any`. ## How it works `ReadPacket` is a generic TypeScript interface representing the input portion of a microservice packet: a required `pattern` field typed as `any` and a required `data` field typed as `T`. If no type argument is supplied, `data` is `any`. It declares no methods, validation, error handling, or runtime side effects itself. [packet.interface.ts:5-8] It is the base type for both request and event packet aliases. `OutgoingRequest` and `IncomingRequest` add a string `id` through intersection with `PacketId`; `OutgoingEvent` and `IncomingEvent` are `ReadPacket` directly. [packet.interface.ts:1-3] [packet.interface.ts:17-20] `ClientProxy.send()` and `emit()` construct packets as `{ pattern, data }` only after rejecting `null` or `undefined` values for either argument with `InvalidMessageException`. [client-proxy.ts:86-101] [client-proxy.ts:111-120] For request flows, `assignPacketId()` mutates the passed packet with a generated `id` and returns it as `ReadPacket & PacketId`. [client-proxy.ts:160-163] The interface is exported from the microservices interfaces barrel. [interfaces/index.ts:1-12] # SaslAuthenticateArgs **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L41) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { request: SaslAuthenticationRequest; response?: SaslAuthenticationResponse; } ``` # ServersChangedEvent **Kind:** Type **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { added: string[]; deleted: string[]; } ``` # TcpStatus **Kind:** Enum **Source:** [`packages/microservices/events/tcp.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/tcp.events.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) ## Values - `DISCONNECTED` - `CONNECTED` # TopicMessages **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L759) **Part of:** [Microservices](subsystem-packages-microservices) `TopicMessages` groups a collection of Kafka `Message` objects under a single topic name. It is used when producing or handling batches of messages that should be sent to the same Kafka topic within the microservices integration layer. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `messages` | `Message[]` | ## Diagram ```mermaid graph LR T[TopicMessages] --> Topic[topic: string] T --> Messages[messages: Message[]] Messages --> M1[Kafka Message] Messages --> M2[Kafka Message] ``` ## Usage ```ts import type { Message } from 'kafkajs'; import type { TopicMessages } from './kafka.interface'; const messages: Message[] = [ { key: 'user-123', value: JSON.stringify({ event: 'user.created', userId: 'user-123', }), }, ]; const topicMessages: TopicMessages = { topic: 'user-events', messages, }; // Example: pass grouped messages to a Kafka producer operation. await producer.send({ topic: topicMessages.topic, messages: topicMessages.messages, }); ``` ## AI Coding Instructions - Always provide a non-empty `topic` that matches the configured Kafka topic naming conventions. - Populate `messages` with Kafka-compatible `Message` objects, including serialized `value` payloads where required. - Group only messages targeting the same topic in a single `TopicMessages` object. - Preserve message keys when ordering, partition affinity, or consumer routing depends on them. - Validate payload serialization and topic configuration before passing this object to producer APIs. ## How it works `TopicMessages` is an exported TypeScript interface in a file intended to represent KafkaJS package types rather than NestJS logic. [packages/microservices/external/kafka.interface.ts:1-4](packages/microservices/external/kafka.interface.ts#L1-L4) [packages/microservices/external/kafka.interface.ts:759-762](packages/microservices/external/kafka.interface.ts#L759-L762) It describes one topic’s set of producer messages: - `topic` is required and has type `string`. [packages/microservices/external/kafka.interface.ts:759-761](packages/microservices/external/kafka.interface.ts#L759-L761) - `messages` is required and has type `Message[]`. [packages/microservices/external/kafka.interface.ts:759-762](packages/microservices/external/kafka.interface.ts#L759-L762) - Each `Message` requires a `value` of `Buffer`, `string`, or `null`; it can also contain an optional key, partition, headers, and timestamp. [packages/microservices/external/kafka.interface.ts:121-127](packages/microservices/external/kafka.interface.ts#L121-L127) `ProducerBatch.topicMessages` optionally accepts an array of `TopicMessages`, and `sendBatch` accepts that `ProducerBatch` and returns `Promise`. [packages/microservices/external/kafka.interface.ts:764-769](packages/microservices/external/kafka.interface.ts#L764-L769) [packages/microservices/external/kafka.interface.ts:785-788](packages/microservices/external/kafka.interface.ts#L785-L788) This interface declares no runtime validation, thrown errors, or side effects. [packages/microservices/external/kafka.interface.ts:759-762](packages/microservices/external/kafka.interface.ts#L759-L762) # TopicOffsets **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L776) **Part of:** [Microservices](subsystem-packages-microservices) `TopicOffsets` represents Kafka offset information for a single topic across one or more partitions. It is typically used when committing offsets, seeking to a position, or reporting consumer progress within the microservices Kafka integration. ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partitions` | `PartitionOffset[]` | ## Diagram ```mermaid graph LR T[TopicOffsets] --> Topic[topic: string] T --> Partitions[partitions: PartitionOffset[]] Partitions --> P1[Partition offset] Partitions --> P2[Partition offset] ``` ## Usage ```ts import type { TopicOffsets } from './kafka.interface'; const offsets: TopicOffsets = { topic: 'orders.created', partitions: [ { partition: 0, offset: '125' }, { partition: 1, offset: '98' }, ], }; // Example: pass topic partition offsets to a Kafka consumer operation. await consumer.commitOffsets(offsets.partitions); ``` ## AI Coding Instructions - Provide a valid Kafka topic name in `topic` and include offsets only for partitions belonging to that topic. - Use the `PartitionOffset` shape expected by the Kafka client; offsets are commonly represented as strings to preserve large integer values. - Keep partition offsets grouped under one `TopicOffsets` object when handling topic-level consumer state. - Validate partition numbers and offsets before committing or seeking, especially when offsets originate from external storage. - When integrating with consumer APIs, check whether the API expects `PartitionOffset[]` directly or a topic-aware wrapper such as `TopicOffsets`. ## How it works `TopicOffsets` is an exported TypeScript interface that groups offset entries under one Kafka topic. It declares two required fields: `topic`, a string, and `partitions`, an array of `PartitionOffset` objects. [packages/microservices/external/kafka.interface.ts:776-779] Each `PartitionOffset` requires a numeric `partition` and a string `offset`; therefore, every entry in `partitions` identifies one partition and its offset as a string. [packages/microservices/external/kafka.interface.ts:771-774] The surrounding file declares types intended to represent the KafkaJS package rather than NestJS logic. [packages/microservices/external/kafka.interface.ts:1-8] `TopicOffsets` has no implementation, validation, error declaration, or direct side effect in this file. [packages/microservices/external/kafka.interface.ts:776-779] It appears in several Kafka-facing type signatures: - `Cluster.fetchTopicsOffset(...)` resolves to `Promise`. [packages/microservices/external/kafka.interface.ts:221-230] - `Broker.offsetCommit(...)` accepts `topics: TopicOffsets[]`. [packages/microservices/external/kafka.interface.ts:674-680] - `Broker.offsetFetch(...)` accepts `topics: TopicOffsets[]` and returns `responses: TopicOffsets[]`. [packages/microservices/external/kafka.interface.ts:681-683] - The consumer commit-offset instrumentation payload contains `topics: TopicOffsets[]`. [packages/microservices/external/kafka.interface.ts:928-938] - `Offsets` and `OffsetsByTopicPartition` each wrap a `topics: TopicOffsets[]` array; `EachBatchPayload.commitOffsetsIfNecessary` accepts an optional `Offsets`, and `uncommittedOffsets` returns `OffsetsByTopicPartition`. [packages/microservices/external/kafka.interface.ts:781-783] [packages/microservices/external/kafka.interface.ts:990-1008] # TopicPartition **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L876) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { topic: string; partition: number; } ``` # AdminConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L262) **Part of:** [Microservices](subsystem-packages-microservices) `AdminConfig` defines configuration options for the Kafka admin client integration. It currently exposes retry behavior through `RetryOptions`, allowing administrative Kafka operations to handle transient failures consistently. ## Properties | Property | Type | |---|---| | `retry` | `RetryOptions` | ## Diagram ```mermaid graph LR AdminConfig[AdminConfig] --> Retry[retry: RetryOptions] Retry --> AdminClient[Kafka Admin Client Operations] AdminClient --> KafkaCluster[Kafka Cluster] ``` ## Usage ```ts import type { AdminConfig } from './kafka.interface'; const adminConfig: AdminConfig = { retry: { retries: 5, initialRetryTime: 300, maxRetryTime: 30_000, }, }; // Pass the configuration when creating or configuring Kafka admin services. const kafkaOptions = { admin: adminConfig, }; ``` ## AI Coding Instructions - Provide a valid `RetryOptions` object for `retry`; do not omit it when constructing an `AdminConfig`. - Keep retry values appropriate for Kafka administrative operations, which may fail temporarily during broker elections or network interruptions. - Reuse the project's existing retry configuration conventions instead of introducing incompatible option names. - Ensure values passed to `retry` match the `RetryOptions` type expected by the Kafka integration. # ClientProviderOptions **Kind:** Type **Source:** [`packages/microservices/module/interfaces/clients-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/interfaces/clients-module.interface.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ClientProvider & { name: string | symbol; } ``` # ConsumerEndBatchProcessEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L969) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent< IBatchProcessEvent & { duration: number } > ``` # DEFAULT_CALLBACK_METADATA **Kind:** Constant **Source:** [`packages/microservices/context/rpc-metadata-constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-metadata-constants.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { [`${RpcParamtype.PAYLOAD}:0`]: { index: 0, data: undefined, pipes: [] }, } ``` ## Value ```ts { [`${RpcParamtype.PAYLOAD}:0`]: { index: 0, data: undefined, pipes: [] }, } ``` # DescribeAclResource **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L458) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts AclResource & { acls: Acl[]; } ``` # FetchOffsetsPartition **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L440) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts PartitionOffset & { metadata: string | null; } ``` # GroupDescriptions **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L870) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { groups: GroupDescription[]; } ``` # IClientProxyFactory **Kind:** Interface **Source:** [`packages/microservices/client/client-proxy-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-proxy-factory.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) # IHeaders **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L160) **Part of:** [Microservices](subsystem-packages-microservices) # IMemberAssignment **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L939) **Part of:** [Microservices](subsystem-packages-microservices) # JsonSocketOptions **Kind:** Interface **Source:** [`packages/microservices/helpers/json-socket.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/json-socket.ts#L9) **Part of:** [Microservices](subsystem-packages-microservices) `JsonSocketOptions` configures buffering behavior for the JSON socket helper used by the microservices transport layer. Its `maxBufferSize` property defines the maximum amount of incoming data that may be buffered while assembling and parsing JSON messages. ## Properties | Property | Type | |---|---| | `maxBufferSize` | `number` | ## Diagram ```mermaid graph LR Client[Socket Client] --> Socket[JSON Socket] Socket --> Buffer[Incoming Data Buffer] Buffer --> Limit[maxBufferSize] Limit --> Parser[JSON Message Parser] Parser --> Handler[Microservice Handler] ``` ## Usage ```ts import { JsonSocketOptions } from './helpers/json-socket'; const socketOptions: JsonSocketOptions = { // Limit buffered incoming socket data to 1 MB. maxBufferSize: 1024 * 1024, }; // Pass the options when creating or configuring the JSON socket. const jsonSocket = new JsonSocket(socket, socketOptions); ``` ## AI Coding Instructions - Set `maxBufferSize` to a value appropriate for expected message sizes and available memory. - Treat this limit as a safety boundary against malformed, incomplete, or excessively large socket payloads. - Keep the value in bytes and document any non-default limits used by a transport configuration. - Ensure socket integrations handle buffer-limit failures by closing, resetting, or reporting invalid connections as appropriate. # KafkaJSBrokerNotFound **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1224) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSDeleteTopicRecordsError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1261) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSGroupCoordinatorNotFound **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1236) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSLockTimeout **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1248) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSMetadataNotLoaded **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1194) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSNonRetriableError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1154) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSNotImplemented **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1240) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSPartialMessageError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1228) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSSASLAuthenticationError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1232) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSTimeout **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1244) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaJSTopicMetadataNotLoadedMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1313) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaJSTopicMetadataNotLoadedMetadata` identifies a Kafka topic whose metadata has not yet been loaded by the KafkaJS integration. It is used as lightweight context for metadata-loading errors, retries, or diagnostic logging within the microservices Kafka transport layer. ## Properties | Property | Type | |---|---| | `topic` | `string` | ## Diagram ```mermaid graph LR A[Kafka Client Operation] --> B{Topic metadata loaded?} B -->|Yes| C[Use topic metadata] B -->|No| D[KafkaJSTopicMetadataNotLoadedMetadata] D --> E[topic: string] D --> F[Error handling, retry, or logging] ``` ## Usage ```ts import type { KafkaJSTopicMetadataNotLoadedMetadata } from './kafka.interface'; function reportMissingTopicMetadata( metadata: KafkaJSTopicMetadataNotLoadedMetadata, ): void { console.warn( `Kafka metadata has not been loaded for topic: ${metadata.topic}`, ); } const missingMetadata: KafkaJSTopicMetadataNotLoadedMetadata = { topic: 'orders.created', }; reportMissingTopicMetadata(missingMetadata); ``` ## AI Coding Instructions - Provide a non-empty Kafka topic name through the required `topic` field. - Use this interface only for contexts where topic metadata is unavailable or not yet initialized. - Preserve the exact topic name used by Kafka; avoid transforming or normalizing it before logging or error reporting. - Integrate instances with KafkaJS metadata lookup, retry, and diagnostic error-handling paths. # KafkaJSUnsupportedMagicByteInMessageSet **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1252) **Part of:** [Microservices](subsystem-packages-microservices) **Extends:** `KafkaJSError` # KafkaParserConfig **Kind:** Interface **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L326) **Part of:** [Microservices](subsystem-packages-microservices) `KafkaParserConfig` defines parser behavior for Kafka message payloads within the microservices configuration layer. Its `keepBinary` flag controls whether incoming Kafka values remain in their binary form instead of being converted during parsing. ## Properties | Property | Type | |---|---| | `keepBinary` | `boolean` | ## Diagram ```mermaid graph LR A[Kafka Consumer] --> B[Kafka Message Value] B --> C[KafkaParserConfig] C -->|keepBinary: true| D[Preserve Binary Payload] C -->|keepBinary: false| E[Parse/Convert Payload] D --> F[Microservice Handler] E --> F ``` ## Usage ```ts import type { KafkaParserConfig } from './interfaces/microservice-configuration.interface'; const parserConfig: KafkaParserConfig = { keepBinary: true, }; // Use this when configuring a Kafka consumer/parser that must receive // raw Buffer payloads, such as protobuf, Avro, or encrypted messages. ``` ## AI Coding Instructions - Set `keepBinary: true` when handlers need access to the raw Kafka `Buffer` payload. - Use `keepBinary: false` when message values should be parsed or converted before reaching application handlers. - Ensure downstream handlers match the configured payload type; binary payloads should not be treated as JSON strings without decoding. - Keep this configuration aligned with the message serializer and deserializer used by Kafka producers and consumers. # MsObjectPattern **Kind:** Interface **Source:** [`packages/microservices/interfaces/pattern.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern.interface.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) # OauthbearerProviderResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L85) **Part of:** [Microservices](subsystem-packages-microservices) `OauthbearerProviderResponse` defines the response returned by an OAuth bearer token provider for Kafka authentication. It contains the bearer token value that Kafka clients use when establishing authenticated connections to a broker. ## Properties | Property | Type | |---|---| | `value` | `string` | ## Diagram ```mermaid graph LR Provider[OAuth Bearer Token Provider] --> Response[OauthbearerProviderResponse] Response --> Token[value: string] Token --> KafkaClient[Kafka Client Authentication] KafkaClient --> Broker[Kafka Broker] ``` ## Usage ```ts import type { OauthbearerProviderResponse } from './kafka.interface'; async function getKafkaOAuthToken(): Promise { const accessToken = await fetchAccessTokenFromIdentityProvider(); return { value: accessToken, }; } async function fetchAccessTokenFromIdentityProvider(): Promise { // Replace with your identity provider integration. return process.env.KAFKA_OAUTH_TOKEN ?? ''; } ``` ## AI Coding Instructions - Return an object with a `value` property containing the OAuth bearer token string. - Keep token acquisition logic separate from the response shape; this interface only represents the provider result. - Avoid logging the `value` field, as it contains sensitive authentication credentials. - Ensure the token is valid and refreshed before Kafka clients request authentication. - Integrate the provider with the Kafka client configuration expected by the microservices package. # Offsets **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L781) **Part of:** [Microservices](subsystem-packages-microservices) `Offsets` represents a collection of Kafka topic offset definitions. It is used when working with consumer position management, allowing callers to provide offset information for one or more topics through the `topics` array. ## Properties | Property | Type | |---|---| | `topics` | `TopicOffsets[]` | ## Diagram ```mermaid graph LR Offsets[Offsets] --> Topics[topics: TopicOffsets[]] Topics --> TopicOffset1[TopicOffsets] Topics --> TopicOffset2[TopicOffsets] TopicOffset1 --> Kafka[Kafka topic/partition offsets] TopicOffset2 --> Kafka ``` ## Usage ```ts import { Offsets, TopicOffsets } from './kafka.interface'; const topicOffsets: TopicOffsets[] = [ { topic: 'orders', partitions: [ { partition: 0, offset: '125' }, { partition: 1, offset: '98' }, ], }, ]; const offsets: Offsets = { topics: topicOffsets, }; // Pass offsets to the Kafka client operation that accepts topic offsets. await kafkaConsumer.seek(offsets); ``` ## AI Coding Instructions - Populate `topics` with valid `TopicOffsets` objects; do not pass raw topic names or partition offsets directly. - Preserve Kafka offsets as strings when the underlying client API expects string-based offsets. - Include all relevant partitions when resetting or seeking consumer positions for a topic. - Validate topic names and partition numbers against the Kafka cluster metadata before applying offsets. - Use this interface with Kafka consumer offset-management operations such as seeking, committing, or resetting positions. # OffsetsByTopicPartition **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L990) **Part of:** [Microservices](subsystem-packages-microservices) `OffsetsByTopicPartition` groups Kafka offset information by topic and partition. It is used when reading, committing, or reporting consumer positions across one or more Kafka topics in the microservices Kafka integration. ## Properties | Property | Type | |---|---| | `topics` | `TopicOffsets[]` | ## Diagram ```mermaid graph LR A[OffsetsByTopicPartition] --> B[topics: TopicOffsets[]] B --> C[Topic offset entry] C --> D[Kafka topic] C --> E[Partition offsets] ``` ## Usage ```ts import type { OffsetsByTopicPartition } from './kafka.interface'; const offsets: OffsetsByTopicPartition = { topics: [ { topic: 'orders', partitions: [ { partition: 0, offset: '142' }, { partition: 1, offset: '98' }, ], }, { topic: 'payments', partitions: [{ partition: 0, offset: '51' }], }, ], }; // Pass the grouped offsets to Kafka consumer offset handling logic. await consumer.commitOffsets(offsets.topics.flatMap((topic) => topic.partitions)); ``` ## AI Coding Instructions - Populate `topics` with `TopicOffsets` entries; do not place partition offsets directly on `OffsetsByTopicPartition`. - Preserve Kafka offsets as strings when required by the underlying client to avoid JavaScript integer precision issues. - Group offsets by their Kafka topic before constructing this interface. - Validate that each partition belongs to the topic named by its corresponding `TopicOffsets` entry. - Use this type at Kafka consumer integration boundaries for offset commit, seek, or lag-reporting workflows. # PacketId **Kind:** Interface **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L1) **Part of:** [Microservices](subsystem-packages-microservices) `PacketId` defines the minimal identifier shape for a microservice packet. It provides a string `id` field that can be used to correlate packets, route responses, and track requests across transport boundaries. ## Properties | Property | Type | |---|---| | `id` | `string` | ## Diagram ```mermaid graph LR Client[Client or Service] --> Packet[Packet] Packet --> PacketId["PacketId
id: string"] Packet --> Transport[Microservice Transport] Transport --> Handler[Message Handler] ``` ## Usage ```ts import type { PacketId } from './interfaces/packet.interface'; function createPacketId(id: string): PacketId { return { id }; } const packetId: PacketId = createPacketId('request-8f4c2a'); console.log(packetId.id); // request-8f4c2a ``` ## AI Coding Instructions - Use `PacketId` whenever a packet requires a stable string identifier for correlation or tracking. - Generate IDs that are unique within the relevant transport or request lifecycle, such as UUIDs or trace IDs. - Preserve the original `id` when forwarding, retrying, or responding to a packet unless a new correlation scope is intended. - Do not add packet payload or routing fields to `PacketId`; compose it with other packet interfaces or types instead. # Serializer **Kind:** Interface **Source:** [`packages/microservices/interfaces/serializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/serializer.interface.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) # TopicPartitionOffset **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L880) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts TopicPartition & { offset: string; } ``` # TopicPartitionOffsetAndMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L883) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts TopicPartitionOffset & { metadata?: string | null; } ``` # CONNECTION_FAILED_MESSAGE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L59) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'Connection to transport failed. Trying to reconnect...' ``` ## Value ```ts 'Connection to transport failed. Trying to reconnect...' ``` # ConsumerStartBatchProcessEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L967) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent ``` # CONTEXT **Kind:** Constant **Source:** [`packages/microservices/tokens.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/tokens.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts REQUEST ``` ## Value ```ts REQUEST ``` ## Relationships - IMPORTS → `REQUEST` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NatsService` — `integration/microservices/src/nats/nats.service.ts`:4 # AclEntry **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L456) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Acl & AclResource ``` # Assignment **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L232) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { [topic: string]: number[] } ``` # BrokersFunction **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L27) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts () => string[] | Promise ``` # CLIENT_CONFIGURATION_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L36) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:client' ``` ## Value ```ts 'microservices:client' ``` # CLIENT_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L38) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:is_client_instance' ``` ## Value ```ts 'microservices:is_client_instance' ``` # ClientProvider **Kind:** Type **Source:** [`packages/microservices/module/interfaces/clients-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/interfaces/clients-module.interface.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ClientOptions | CustomClientOptions ``` ## Relationships - IMPORTS → `Type` - IMPORTS → `Provider` - IMPORTS → `ModuleMetadata` # CONN_ERR **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L29) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'CONN_ERR' ``` ## Value ```ts 'CONN_ERR' ``` # ConnectEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L406) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent ``` # ConsumerEachBatchPayload **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1023) **Part of:** [Microservices](subsystem-packages-microservices) Type alias to keep compatibility with `ConsumerEachBatchPayload` is a compatibility type alias for the payload supplied to Kafka consumer `eachBatch` handlers. It provides access to the received batch, message offset controls, heartbeat handling, and consumer lifecycle state when processing Kafka records in batches. ## Definition ```ts EachBatchPayload ``` ## Diagram ```mermaid graph LR Consumer[Kafka Consumer] --> Handler[eachBatch Handler] Handler --> Payload[ConsumerEachBatchPayload] Payload --> Batch[batch.messages] Payload --> Offset[resolveOffset] Payload --> Heartbeat[heartbeat] Payload --> State[isRunning / isStale] ``` ## Usage ```ts import type { ConsumerEachBatchPayload } from '@nestjs/microservices'; async function processKafkaBatch({ batch, resolveOffset, heartbeat, isRunning, isStale, }: ConsumerEachBatchPayload) { for (const message of batch.messages) { if (!isRunning() || isStale()) { break; } const value = message.value?.toString(); console.log(`Processing message: ${value}`); // Process the message before marking its offset as resolved. resolveOffset(message.offset); // Keep the Kafka consumer session alive during long-running work. await heartbeat(); } } ``` ## AI Coding Instructions - Use this type for Kafka `eachBatch` callbacks to preserve compatibility with the underlying Kafka consumer payload. - Check `isRunning()` and `isStale()` while iterating through large batches to avoid processing invalid or revoked work. - Call `resolveOffset()` only after a message has been processed successfully. - Invoke `heartbeat()` during long-running batch processing to prevent consumer session timeouts. - Treat `batch.messages` as ordered Kafka records and handle message values that may be `null`. # ConsumerEachMessagePayload **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1017) **Part of:** [Microservices](subsystem-packages-microservices) Type alias to keep compatibility with `ConsumerEachMessagePayload` is a compatibility type alias for the payload passed to a Kafka consumer's `eachMessage` handler. It provides typed access to the consumed topic, partition, message, heartbeat function, and partition-pausing controls while preserving compatibility with KafkaJS consumer APIs. ## Definition ```ts EachMessagePayload ``` ## Diagram ```mermaid graph LR A[Kafka Consumer] --> B[eachMessage Handler] B --> C[ConsumerEachMessagePayload] C --> D[topic] C --> E[partition] C --> F[message] C --> G[heartbeat] C --> H[pause] ``` ## Usage ```ts import { ConsumerEachMessagePayload } from '@nestjs/microservices'; async function handleKafkaMessage( payload: ConsumerEachMessagePayload, ): Promise { const { topic, partition, message, heartbeat } = payload; const value = message.value?.toString(); console.log({ topic, partition, offset: message.offset, value, }); // Call during long-running message processing to keep the consumer alive. await heartbeat(); } ``` ## AI Coding Instructions - Use `ConsumerEachMessagePayload` when typing handlers that receive KafkaJS `eachMessage` callback data. - Treat `message.value` as nullable; check for `null` or use optional chaining before decoding it. - Preserve access to `heartbeat()` in long-running handlers to avoid consumer session timeouts. - Use the provided `topic`, `partition`, and `message.offset` values for logging, tracing, and idempotency handling. - Keep this alias in place for KafkaJS compatibility instead of replacing it with a manually recreated payload shape. # ConsumerFetchStartEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L951) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent<{ nodeId: number }> ``` # ConsumerSerializer **Kind:** Type **Source:** [`packages/microservices/interfaces/serializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/serializer.interface.ts#L18) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Serializer ``` # DefaultPartitioner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L136) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ICustomPartitioner ``` # DISCONNECTED_RMQ_MESSAGE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L58) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts `Disconnected from RMQ. Trying to reconnect.` ``` ## Value ```ts `Disconnected from RMQ. Trying to reconnect.` ``` # DisconnectEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L407) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts InstrumentationEvent ``` # EachBatchHandler **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1025) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts (payload: EachBatchPayload) => Promise ``` # EachMessageHandler **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1026) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts (payload: EachMessagePayload) => Promise ``` # EADDRINUSE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L30) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'EADDRINUSE' ``` ## Value ```ts 'EADDRINUSE' ``` # ECONNREFUSED **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L28) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'ECONNREFUSED' ``` ## Value ```ts 'ECONNREFUSED' ``` # ENOTFOUND **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L31) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'ENOTFOUND' ``` ## Value ```ts 'ENOTFOUND' ``` # GroupMember **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L234) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { memberId: string; memberMetadata: Buffer } ``` # GroupState **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L241) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { name: string; metadata: Buffer } ``` # GRPC_DEFAULT_PROTO_LOADER **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L53) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '@grpc/proto-loader' ``` ## Value ```ts '@grpc/proto-loader' ``` # GRPC_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L9) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'localhost:5000' ``` ## Value ```ts 'localhost:5000' ``` # GrpcService **Kind:** Constant **Source:** [`packages/microservices/decorators/grpc-service.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/grpc-service.decorator.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) Defines the GrpcService. The service can inject dependencies through constructor. Those dependencies have to belong to the same module. `GrpcService` marks a class as a gRPC service that can be registered and exposed by the microservices layer. The decorated service may receive constructor-injected dependencies, provided those dependencies are registered within the same module. ## Definition ```ts Controller ``` ## Value ```ts Controller ``` ## Diagram ```mermaid graph LR M[Application Module] --> S[@GrpcService class] M --> D[Module-scoped Dependency] D -->|constructor injection| S S --> G[gRPC Server] G --> C[gRPC Clients] ``` ## Usage ```ts import { GrpcService } from '@your-package/microservices'; class UserRepository { async findById(id: string) { return { id, name: 'Ada Lovelace' }; } } @GrpcService() export class UserGrpcService { constructor(private readonly userRepository: UserRepository) {} async getUser(request: { id: string }) { return this.userRepository.findById(request.id); } } ``` ## AI Coding Instructions - Decorate classes that implement gRPC-facing behavior with `@GrpcService()`. - Keep constructor dependencies registered in the same module as the gRPC service. - Prefer injecting domain services or repositories rather than placing business logic directly in transport handlers. - Do not inject providers from unrelated modules unless they are explicitly made available through the module configuration. - Ensure gRPC method names and request/response shapes remain aligned with the associated `.proto` contract. ## Relationships - IMPORTS → `Controller` # ICustomPartitioner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L135) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts () => (args: PartitionerArgs) => number ``` # IncomingEvent **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L20) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ReadPacket ``` # IncomingRequest **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L18) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ReadPacket & PacketId ``` # IncomingResponse **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L21) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts WritePacket & PacketId ``` # ISocketFactory **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L83) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts (args: ISocketFactoryArgs) => net.Socket ``` # KAFKA_DEFAULT_BROKER **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L11) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'localhost:9092' ``` ## Value ```ts 'localhost:9092' ``` # KAFKA_DEFAULT_CLIENT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L12) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'nestjs-consumer' ``` ## Value ```ts 'nestjs-consumer' ``` # KAFKA_DEFAULT_GROUP **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L13) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'nestjs-group' ``` ## Value ```ts 'nestjs-group' ``` # KafkaMessage **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L738) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts MessageSetEntry | RecordBatchEntry ``` # LegacyPartitioner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L137) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ICustomPartitioner ``` # logCreator **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L639) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts (logLevel: logLevel) => (entry: LogEntry) => void ``` # MQTT_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L8) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'mqtt://localhost:1883' ``` ## Value ```ts 'mqtt://localhost:1883' ``` # MQTT_SEPARATOR **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L14) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '/' ``` ## Value ```ts '/' ``` # MQTT_WILDCARD_ALL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L16) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '#' ``` ## Value ```ts '#' ``` # MQTT_WILDCARD_SINGLE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L15) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '+' ``` ## Value ```ts '+' ``` # MsFundamentalPattern **Kind:** Type **Source:** [`packages/microservices/interfaces/pattern.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern.interface.ts#L1) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts string | number ``` # MsPattern **Kind:** Type **Source:** [`packages/microservices/interfaces/pattern.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern.interface.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts MsObjectPattern | MsFundamentalPattern ``` # NATS_DEFAULT_GRACE_PERIOD **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L65) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 10000 ``` ## Value ```ts 10000 ``` # NATS_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L7) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'nats://localhost:4222' ``` ## Value ```ts 'nats://localhost:4222' ``` # NO_MESSAGE_HANDLER **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L57) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts `There is no matching message handler defined in the remote service.` ``` ## Value ```ts `There is no matching message handler defined in the remote service.` ``` # normalizedPattern **Kind:** API Endpoint **Source:** [`packages/microservices/server/server.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server.ts#L150) **Part of:** [Microservices](subsystem-packages-microservices) ## Endpoint `GET /` # OutgoingEvent **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L19) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ReadPacket ``` # OutgoingRequest **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L17) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ReadPacket & PacketId ``` # OutgoingResponse **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L22) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts WritePacket & PacketId ``` # PARAM_ARGS_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L39) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts ROUTE_ARGS_METADATA ``` ## Value ```ts ROUTE_ARGS_METADATA ``` # PartitionAssigners **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L594) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { roundRobin: PartitionAssigner } ``` # PATTERN_EXTRAS_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L34) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:pattern_extras' ``` ## Value ```ts 'microservices:pattern_extras' ``` # PATTERN_HANDLER_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L37) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:handler_type' ``` ## Value ```ts 'microservices:handler_type' ``` # PATTERN_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L33) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:pattern' ``` ## Value ```ts 'microservices:pattern' ``` # PatternMetadata **Kind:** Type **Source:** [`packages/microservices/interfaces/pattern-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern-metadata.interface.ts#L1) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Record | string ``` # ProducerDeserializer **Kind:** Type **Source:** [`packages/microservices/interfaces/deserializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/deserializer.interface.ts#L17) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Deserializer ``` # QoS **Kind:** Type **Source:** [`packages/microservices/external/mqtt-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/mqtt-options.interface.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 0 | 1 | 2 ``` # REDIS_DEFAULT_HOST **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L6) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'localhost' ``` ## Value ```ts 'localhost' ``` # REDIS_DEFAULT_PORT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L5) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 6379 ``` ## Value ```ts 6379 ``` # RemoveInstrumentationEventListener **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L404) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts () => void ``` # REPLY_PATTERN_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L41) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:reply_pattern' ``` ## Value ```ts 'microservices:reply_pattern' ``` # REQUEST_PATTERN_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L40) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:request_pattern' ``` ## Value ```ts 'microservices:request_pattern' ``` # RMQ_SEPARATOR **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L24) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '.' ``` ## Value ```ts '.' ``` # RMQ_WILDCARD_ALL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L26) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '#' ``` ## Value ```ts '#' ``` # RMQ_WILDCARD_SINGLE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L25) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '*' ``` ## Value ```ts '*' ``` # route **Kind:** API Endpoint **Source:** [`packages/microservices/server/server.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server.ts#L168) **Part of:** [Microservices](subsystem-packages-microservices) ## Endpoint `GET /` ## Relationships - IMPORTS → `Logger` - IMPORTS → `LoggerService` - IMPORTS → `loadPackage` # RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L19) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts false ``` ## Value ```ts false ``` # RQM_DEFAULT_NO_ASSERT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L23) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts false ``` ## Value ```ts false ``` # RQM_DEFAULT_NOACK **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L21) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts true ``` ## Value ```ts true ``` # RQM_DEFAULT_PERSISTENT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L22) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts false ``` ## Value ```ts false ``` # RQM_DEFAULT_PREFETCH_COUNT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L18) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 0 ``` ## Value ```ts 0 ``` # RQM_DEFAULT_QUEUE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L17) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts '' ``` ## Value ```ts '' ``` # RQM_DEFAULT_QUEUE_OPTIONS **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L20) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts {} ``` ## Value ```ts {} ``` # RQM_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L10) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'amqp://localhost' ``` ## Value ```ts 'amqp://localhost' ``` # SASLMechanism **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L104) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts keyof SASLMechanismOptionsMap ``` # SASLOptions **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L108) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts SASLMechanismOptions ``` # SeekEntry **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L438) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts PartitionOffset ``` # TCP_DEFAULT_HOST **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L4) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'localhost' ``` ## Value ```ts 'localhost' ``` # TCP_DEFAULT_PORT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L3) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 3000 ``` ## Value ```ts 3000 ``` ## Relationships - IMPORTS → `ROUTE_ARGS_METADATA` # TopicPartitions **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L874) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts { topic: string; partitions: number[] } ``` # TRANSPORT_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'microservices:transport' ``` ## Value ```ts 'microservices:transport' ``` # TransportId **Kind:** Type **Source:** [`packages/microservices/interfaces/microservice-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/microservice-configuration.interface.ts#L35) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts Transport | symbol ``` # UNBLOCKED_RMQ_MESSAGE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L63) **Part of:** [Microservices](subsystem-packages-microservices) ## Definition ```ts 'RMQ broker has unblocked the connection.' ``` ## Value ```ts 'RMQ broker has unblocked the connection.' ``` # Module **Kind:** Function **Source:** [`packages/common/decorators/modules/module.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/modules/module.decorator.ts#L18) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a [module](https://docs.nestjs.com/modules). Modules are used by Nest to organize the application structure into scopes. Controllers and Providers are scoped by the module they are declared in. Modules and their classes (Controllers and Providers) form a graph that determines how Nest performs [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). `Module()` is a class decorator that marks a class as a NestJS module and attaches module metadata to it. Modules define application boundaries by grouping controllers, providers, imports, and exports into dependency-injection scopes. ## Signature ```ts function Module(metadata: ModuleMetadata): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `metadata` | `ModuleMetadata` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR AppModule["@Module() AppModule"] --> Controllers["Controllers"] AppModule --> Providers["Providers"] AppModule --> Imports["Imported Modules"] AppModule --> Exports["Exported Providers"] Controllers --> Scope["Module DI Scope"] Providers --> Scope Imports --> Scope Scope --> Nest["Nest Dependency Injection Container"] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { UsersController } from './users.controller'; import { UsersService } from './users.service'; import { DatabaseModule } from '../database/database.module'; @Module({ imports: [DatabaseModule], controllers: [UsersController], providers: [UsersService], exports: [UsersService], }) export class UsersModule {} ``` ## AI Coding Instructions - Apply `@Module()` only to classes intended to act as NestJS module boundaries. - Register controllers in `controllers` and injectable services, repositories, and factories in `providers`. - Add dependent modules to `imports`; do not add their providers directly unless they are explicitly exported. - Use `exports` to make selected providers available to modules that import this module. - Avoid circular module imports; use NestJS `forwardRef()` only when a circular dependency cannot be redesigned. ## Used by 181 references from 181 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (181) - `ROUTES` — `packages/core/router/router-module.ts`:9 - `AppModule` — `integration/cors/src/app.module.ts`:4 - `AppModule` — `integration/discovery/src/app.module.ts`:6 - `MyWebhookModule` — `integration/discovery/src/my-webhook/my-webhook.module.ts`:5 - `AppModule` — `integration/graphql-code-first/src/app.module.ts`:7 - `RecipesModule` — `integration/graphql-code-first/src/recipes/recipes.module.ts`:8 - `AppModule` — `integration/graphql-schema-first/src/app.module.ts`:7 - `AsyncClassApplicationModule` — `integration/graphql-schema-first/src/async-options-class.module.ts`:15 …and 173 more. # Logger **Kind:** Service **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as ⚙️ Logger client->>+p1: Logger p1-->client: return response ``` ## Used by 52 references from 49 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Injected or called by (2) - `RequestLogger` — `integration/scopes/src/inject-inquirer/hello-request/request-logger.service.ts`:4 - `TransientLogger` — `integration/scopes/src/inject-inquirer/hello-transient/transient-logger.service.ts`:4 ### Provided by (1) - `HelloModule` — `integration/scopes/src/inject-inquirer/hello.module.ts`:8 ### Imported by (49) - `LegacyRouteConverter` — `packages/core/router/legacy-route-converter.ts`:6 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `CustomHeader` — `packages/core/router/router-response-controller.ts`:18 - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `Transient2Service` — `integration/injector/src/scoped/transient2.service.ts`:3 - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaMessagesController` — `integration/microservices/src/kafka/kafka.messages.controller.ts`:9 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 …and 41 more. # ConsoleLogger **Kind:** Service **Source:** [`packages/common/services/console-logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/console-logger.service.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as ⚙️ ConsoleLogger client->>+p1: ConsoleLogger p1-->client: return response ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `TestingLogger` — `packages/testing/services/testing-logger.service.ts`:6 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `ReplLogger` — `packages/core/repl/repl-logger.ts`:6 # ClassSerializerInterceptor **Kind:** Service **Source:** [`packages/common/serializer/class-serializer.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/common/serializer/class-serializer.interceptor.ts#L34) **Part of:** [Common](subsystem-packages-common) `ClassSerializerInterceptor` is a NestJS interceptor that transforms controller responses into plain JavaScript objects using `class-transformer`. It applies serialization rules such as `@Exclude()`, `@Expose()`, groups, versioning, and custom transformation options before the response is sent to the client. It can read serializer options from global configuration or route-level metadata. ## Methods | Method | Signature | Returns | Description | |---|---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | | | `serialize` | `serialize(response: PlainLiteralObject | Array, options: ClassSerializerContextOptions)` | `PlainLiteralObject | Array` | Serializes responses that are non-null objects nor streamable files. | | `transformToPlain` | `transformToPlain(plainOrClass: any, options: ClassSerializerContextOptions)` | `PlainLiteralObject` | | | `getContextOptions` | `getContextOptions(context: ExecutionContext)` | `ClassSerializerContextOptions | undefined` | | ## Dependencies - `ClassSerializerInterceptorOptions` _(optional)_ ## Where it refuses work - `ClassSerializerInterceptor` stops the work with an early return when `!isObject(response) || response instanceof StreamableFile`. - `ClassSerializerInterceptor` stops the work with an early return when `!plainOrClass`. - `ClassSerializerInterceptor` stops the work with an early return when `!options.type`. - `ClassSerializerInterceptor` stops the work with an early return when `plainOrClass instanceof options.type`. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant Interceptor as ClassSerializerInterceptor participant Reflector participant Transformer as class-transformer Client->>Interceptor: HTTP request Interceptor->>Reflector: Read route/class serializer options Interceptor->>Controller: next.handle() Controller-->>Interceptor: Response entity or entity array Interceptor->>Transformer: instanceToPlain() / classToPlain() Transformer-->>Interceptor: Serialized plain object Interceptor-->>Client: HTTP response ``` ## Usage ```ts import { ClassSerializerInterceptor, Controller, Get, UseInterceptors, } from '@nestjs/common'; import { Exclude, Expose } from 'class-transformer'; class UserResponseDto { @Expose() id: string; @Expose() email: string; @Exclude() password: string; } @Controller('users') @UseInterceptors(ClassSerializerInterceptor) export class UsersController { @Get('me') getCurrentUser(): UserResponseDto { return { id: 'user_123', email: 'developer@example.com', password: 'internal-secret', }; } } ``` ## AI Coding Instructions - Return class instances or DTO instances with `class-transformer` decorators; plain objects may not apply `@Exclude()` and `@Expose()` metadata as expected. - Apply `ClassSerializerInterceptor` globally, at the controller level, or per route depending on the desired serialization scope. - Use `@SerializeOptions()` when a route requires custom groups, versioning, or other `ClassSerializerContextOptions`. - Do not expose sensitive entity fields by default; explicitly exclude fields such as passwords, tokens, secrets, and internal identifiers. - Preserve observable behavior in `intercept()` by transforming the value returned from `next.handle()` rather than manually subscribing. ## Relationships - DEPENDS_ON → `ClassSerializerInterceptorOptions` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AppController` — `sample/21-serializer/src/app.controller.ts`:10 # Get **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L57) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP GET requests to the specified path. `Get` is a route handler decorator that maps an HTTP `GET` request to a controller method. Use it to expose read-oriented endpoints, optionally providing a path that is combined with the controller's base route. ## Definition ```ts createMappingDecorator(RequestMethod.GET) ``` ## Value ```ts createMappingDecorator(RequestMethod.GET) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|GET /users/:id| Controller[Controller Base Path: /users] Controller --> Get["@Get(':id')"] Get --> Handler[Controller Method] Handler --> Response[HTTP Response] ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id, name: 'Ada Lovelace', }; } @Get() findAll() { return []; } } ``` ## AI Coding Instructions - Apply `@Get()` only to controller methods that handle HTTP `GET` requests. - Provide a relative route path such as `':id'` or `'search'`; it is combined with the enclosing `@Controller()` path. - Use parameter decorators such as `@Param()`, `@Query()`, and `@Headers()` to access request data instead of manually parsing the request where possible. - Keep `GET` handlers read-oriented and avoid side effects; use `@Post()`, `@Patch()`, or `@Delete()` for state-changing operations. ## Used by 77 references from 77 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (77) - `AppController` — `integration/cors/src/app.controller.ts`:3 - `ErrorsController` — `integration/hello-world/src/errors/errors.controller.ts`:3 - `HelloController` — `integration/hello-world/src/hello/hello.controller.ts`:6 - `HostController` — `integration/hello-world/src/host/host.controller.ts`:6 - `HostArrayController` — `integration/hello-world/src/host-array/host-array.controller.ts`:6 - `AppV1Controller` — `integration/inspector/src/app-v1.controller.ts`:3 - `AppV2Controller` — `integration/inspector/src/app-v2.controller.ts`:3 - `CatsController` — `integration/inspector/src/cats/cats.controller.ts`:8 …and 69 more. # Scope **Kind:** Enum **Source:** [`packages/common/interfaces/scope-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/scope-options.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Values - `DEFAULT` - `TRANSIENT` - `REQUEST` ## Used by 69 references from 69 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (69) - `requestProvider` — `packages/core/router/request/request-providers.ts`:5 - `CatsRequestScopedService` — `integration/graphql-schema-first/src/cats/cats-request-scoped.service.ts`:4 - `CatsModule` — `integration/graphql-schema-first/src/cats/cats.module.ts`:6 - `AModule` — `integration/injector/src/multiple-providers/a.module.ts`:3 - `BModule` — `integration/injector/src/multiple-providers/b.module.ts`:3 - `CModule` — `integration/injector/src/multiple-providers/c.module.ts`:3 - `ScopedController` — `integration/injector/src/scoped/scoped.controller.ts`:3 - `ScopedModule` — `integration/injector/src/scoped/scoped.module.ts`:12 …and 61 more. # Inject **Kind:** Function **Source:** [`packages/common/decorators/core/inject.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/inject.decorator.ts#L38) **Part of:** [Common](subsystem-packages-common) Decorator that marks a constructor parameter as a target for [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). Any injected provider must be visible within the module scope (loosely speaking, the containing module) of the class it is being injected into. This can be done by: - defining the provider in the same module scope - exporting the provider from one module scope and importing that module into the module scope of the class being injected into - exporting the provider from a module that is marked as global using the `@Global()` decorator #### Injection tokens Can be *types* (class names), *strings* or *symbols*. This depends on how the provider with which it is associated was defined. Providers defined with the `@Injectable()` decorator use the class name. Custom Providers may use strings or symbols as the injection token. `@Inject()` marks a constructor parameter as a dependency to be resolved by Nest's dependency injection container. Use it when injecting providers by an explicit token, especially for custom providers registered with string or symbol tokens. The referenced provider must be visible in the module scope where the consuming class is declared. ## Signature ```ts function Inject(token: InjectionToken | ForwardReference): PropertyDecorator & ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `token` | `InjectionToken | ForwardReference` | **Returns:** `PropertyDecorator & ParameterDecorator` ## Diagram ```mermaid graph LR A[Module Provider Registration] -->|class, string, or symbol token| B[Nest DI Container] C[Consumer Constructor
@Inject(TOKEN)] --> B B -->|resolves matching provider| D[Injected Dependency] ``` ## Usage ```ts import { Injectable, Inject } from '@nestjs/common'; export const CACHE_CLIENT = Symbol('CACHE_CLIENT'); interface CacheClient { get(key: string): Promise; } @Injectable() export class UserService { constructor( @Inject(CACHE_CLIENT) private readonly cache: CacheClient, ) {} async findCachedUser(id: string) { return this.cache.get(`user:${id}`); } } ``` ```ts import { Module } from '@nestjs/common'; @Module({ providers: [ UserService, { provide: CACHE_CLIENT, useValue: { get: async (key: string) => null, }, }, ], }) export class UsersModule {} ``` ## AI Coding Instructions - Use `@Inject(TOKEN)` when the provider uses a string or symbol token; class-based `@Injectable()` providers can usually be injected by type. - Ensure the provider is declared in the same module, or exported from an imported module. - Keep injection tokens in shared constants to avoid mismatched string literals or duplicate symbols. - Prefer interfaces paired with explicit tokens for dependencies that have multiple implementations. - Do not inject providers that are unavailable in the consuming module's scope; global modules should be used sparingly. ## Used by 64 references from 64 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (64) - `ROUTES` — `packages/core/router/router-module.ts`:9 - `CircularService` — `integration/injector/src/circular/circular.service.ts`:4 - `InputService` — `integration/injector/src/circular/input.service.ts`:4 - `CircularService` — `integration/injector/src/circular-modules/circular.service.ts`:4 - `InputService` — `integration/injector/src/circular-modules/input.service.ts`:4 - `CircularService` — `integration/injector/src/circular-properties/circular.service.ts`:4 - `InputService` — `integration/injector/src/circular-properties/input.service.ts`:4 - `DefaultsService` — `integration/injector/src/defaults/defaults.service.ts`:4 …and 56 more. # Type **Kind:** Interface **Source:** [`packages/common/interfaces/type.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/type.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Used by 62 references from 62 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (62) - `RouteTree` — `packages/core/router/interfaces/routes.interface.ts`:3 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `ROUTES` — `packages/core/router/router-module.ts`:9 - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `flattenRoutePaths` — `packages/core/router/utils/flatten-route-paths.util.ts`:5 - `CreateDecoratorOptions` — `packages/core/services/reflector.service.ts`:8 - `ClientsModule` — `packages/microservices/module/clients.module.ts`:17 - `AnyFilesInterceptor` — `packages/platform-express/multer/interceptors/any-files.interceptor.ts`:24 …and 54 more. # ExecutionContext **Kind:** Interface **Source:** [`packages/common/interfaces/features/execution-context.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/execution-context.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) Interface describing details about the current request pipeline. `ExecutionContext` describes the state and metadata available while a request moves through the application's execution pipeline. It provides a shared context for pipeline features, allowing them to read request-scoped information and coordinate processing without relying on global state. ## Diagram ```mermaid graph LR Request[Incoming Request] --> Pipeline[Request Pipeline] Pipeline --> Context[ExecutionContext] Context --> FeatureA[Feature / Middleware A] Context --> FeatureB[Feature / Middleware B] FeatureA --> Result[Response or Execution Result] FeatureB --> Result ``` ## Usage ```ts import type { ExecutionContext } from '@common/interfaces/features/execution-context.interface'; function processFeature(context: ExecutionContext): void { // Read request-scoped details from the context and perform // feature-specific processing. console.log('Processing request with execution context:', context); } function runPipeline(context: ExecutionContext): void { processFeature(context); // Pass the same context to subsequent pipeline features so they // operate on the same request-scoped execution state. // validateFeature(context); // authorizationFeature(context); } ``` ## AI Coding Instructions - Treat `ExecutionContext` as request-scoped data; do not reuse one instance across unrelated requests. - Pass the existing context through pipeline stages instead of creating disconnected context objects. - Keep feature-specific logic in pipeline handlers rather than adding unrelated behavior to the interface. - When extending the context, ensure new fields are available to every pipeline integration that depends on them. ## Used by 48 references from 48 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (48) - `AuthGuard` — `integration/graphql-code-first/src/common/guards/auth.guard.ts`:9 - `DataInterceptor` — `integration/graphql-code-first/src/common/interceptors/data.interceptor.ts`:10 - `CatsGuard` — `integration/graphql-schema-first/src/cats/cats.guard.ts`:4 - `Guard` — `integration/inspector/src/circular-hello/guards/request-scoped.guard.ts`:9 - `Interceptor` — `integration/inspector/src/circular-hello/interceptors/logging.interceptor.ts`:10 - `RolesGuard` — `integration/inspector/src/common/guards/roles.guard.ts`:4 - `TimeoutInterceptor` — `integration/inspector/src/common/interceptors/timeout.interceptor.ts`:10 - `LoggingInterceptor` — `integration/inspector/src/core/interceptors/logging.interceptor.ts`:10 …and 40 more. # NestInterceptor **Kind:** Interface **Source:** [`packages/common/interfaces/features/nest-interceptor.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/nest-interceptor.interface.ts#L27) **Part of:** [Common](subsystem-packages-common) Interface describing implementation of an interceptor. `NestInterceptor` defines a hook for wrapping and transforming request handling in NestJS. Implementations receive the current `ExecutionContext` and a `CallHandler`, allowing them to run logic before or after the route handler, modify responses, handle errors, or measure execution time. ## Diagram ```mermaid graph LR A[Incoming Request] --> B[Interceptor.intercept] B --> C[ExecutionContext] B --> D[CallHandler] D --> E[Route Handler] E --> F[Observable Response] F --> G[Interceptor Response Transformation] G --> H[Client Response] ``` ## Usage ```ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() export class ResponseEnvelopeInterceptor implements NestInterceptor { intercept( context: ExecutionContext, next: CallHandler, ): Observable<{ data: unknown }> { return next.handle().pipe( map((data) => ({ data })), ); } } // Register globally or attach to a controller/route: // @UseInterceptors(ResponseEnvelopeInterceptor) ``` ## AI Coding Instructions - Implement `intercept(context, next)` and always return an `Observable` from `next.handle()` unless intentionally short-circuiting the request. - Use RxJS operators such as `map`, `catchError`, `tap`, and `finalize` to transform responses, handle errors, or perform side effects. - Use `ExecutionContext` to access transport-specific details, such as `context.switchToHttp().getRequest()` for HTTP requests. - Register interceptors with `@UseInterceptors()`, as global interceptors, or through dependency injection when they require application services. - Avoid subscribing to `next.handle()` inside the interceptor; return the observable so Nest can manage the response lifecycle. ## Used by 36 references from 36 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (36) - `DataInterceptor` — `integration/graphql-code-first/src/common/interceptors/data.interceptor.ts`:10 - `Interceptor` — `integration/inspector/src/circular-hello/interceptors/logging.interceptor.ts`:10 - `TimeoutInterceptor` — `integration/inspector/src/common/interceptors/timeout.interceptor.ts`:10 - `LoggingInterceptor` — `integration/inspector/src/core/interceptors/logging.interceptor.ts`:10 - `TransformInterceptor` — `integration/inspector/src/core/interceptors/transform.interceptor.ts`:14 - `LoggingInterceptor` — `integration/inspector/src/request-chain/interceptors/logging.interceptor.ts`:10 - `PassthroughInterceptor` — `integration/nest-application/sse/src/app.controller.ts`:28 - `Interceptor` — `integration/scopes/src/circular-hello/interceptors/logging.interceptor.ts`:10 …and 28 more. # Post **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L48) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP POST requests to the specified path. `Post` is a route handler decorator that maps an HTTP `POST` request to a controller method. Use it to define endpoints that create resources, submit commands, or accept request payloads at a specified path within the application's HTTP routing system. ## Definition ```ts createMappingDecorator(RequestMethod.POST) ``` ## Value ```ts createMappingDecorator(RequestMethod.POST) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|POST /users| Router[HTTP Router] Router -->|Matches @Post path| Controller[Controller Method] Controller --> Service[Application Service] Service --> Response[HTTP Response] ``` ## Usage ```ts import { Controller, Body, Post } from '@nestjs/common'; @Controller('users') export class UsersController { @Post() createUser(@Body() input: CreateUserDto) { return { id: 'user_123', email: input.email, }; } @Post('invite') inviteUser(@Body() input: InviteUserDto) { return this.usersService.invite(input); } } ``` ## AI Coding Instructions - Apply `@Post()` to controller methods that should handle HTTP `POST` requests; provide a path such as `@Post('invite')` for nested routes. - Keep route handlers focused on HTTP concerns and delegate business logic to services or use-case classes. - Validate and transform request payloads using DTOs, pipes, or validation middleware before processing them. - Avoid using `@Post()` for idempotent read operations; prefer `@Get()` for retrieval endpoints. - Ensure the controller-level route prefix and the `@Post()` path combine into the intended public endpoint. ## Used by 37 references from 37 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (37) - `CatsController` — `integration/inspector/src/cats/cats.controller.ts`:8 - `DatabaseController` — `integration/inspector/src/database/database.controller.ts`:14 - `DogsController` — `integration/inspector/src/dogs/dogs.controller.ts`:14 - `UsersController` — `integration/inspector/src/users/users.controller.ts`:14 - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `DisconnectedClientController` — `integration/microservices/src/disconnected.controller.ts`:12 - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 - `AdvancedGrpcController` — `integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`:14 …and 29 more. # CallHandler **Kind:** Interface **Source:** [`packages/common/interfaces/features/nest-interceptor.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/nest-interceptor.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) Interface providing access to the response stream. `CallHandler` represents the downstream execution pipeline in a NestJS interceptor. It provides access to the response stream through `handle()`, allowing interceptors to transform, observe, or replace values returned by route handlers. ## Diagram ```mermaid graph LR Client[Client Request] --> Interceptor[Nest Interceptor] Interceptor --> Handler[CallHandler] Handler --> Controller[Route Handler] Controller --> Stream[Observable Response Stream] Stream --> Interceptor Interceptor --> Client ``` ## Usage ```ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable, map } from 'rxjs'; @Injectable() export class ResponseWrapperInterceptor implements NestInterceptor { intercept( context: ExecutionContext, next: CallHandler, ): Observable<{ data: unknown }> { return next.handle().pipe( map((response) => ({ data: response, })), ); } } ``` ## AI Coding Instructions - Call `next.handle()` to continue execution to the controller or next interceptor and receive an `Observable` response stream. - Use RxJS operators such as `map`, `tap`, `catchError`, and `timeout` to modify or monitor responses without subscribing manually. - Return the transformed `Observable`; do not call `subscribe()` inside an interceptor. - Treat `CallHandler` as the boundary between interceptor logic and the downstream route handler execution. ## Used by 32 references from 32 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (32) - `DataInterceptor` — `integration/graphql-code-first/src/common/interceptors/data.interceptor.ts`:10 - `Interceptor` — `integration/inspector/src/circular-hello/interceptors/logging.interceptor.ts`:10 - `TimeoutInterceptor` — `integration/inspector/src/common/interceptors/timeout.interceptor.ts`:10 - `LoggingInterceptor` — `integration/inspector/src/core/interceptors/logging.interceptor.ts`:10 - `TransformInterceptor` — `integration/inspector/src/core/interceptors/transform.interceptor.ts`:14 - `LoggingInterceptor` — `integration/inspector/src/request-chain/interceptors/logging.interceptor.ts`:10 - `PassthroughInterceptor` — `integration/nest-application/sse/src/app.controller.ts`:28 - `Interceptor` — `integration/scopes/src/circular-hello/interceptors/logging.interceptor.ts`:10 …and 24 more. # DynamicModule **Kind:** Interface **Source:** [`packages/common/interfaces/modules/dynamic-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/dynamic-module.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) Interface defining a Dynamic Module. `DynamicModule` describes the metadata returned when a module is configured dynamically at runtime. It identifies the module class through `module` and can mark the module as application-wide through the optional `global` flag. ## Properties | Property | Type | |---|---| | `module` | `Type` | | `global` | `boolean` | ## Diagram ```mermaid graph LR A[Dynamic module factory] --> B[DynamicModule metadata] B --> C[module: Type] B --> D[global: boolean] C --> E[Framework module loader] D --> F[Global module availability] ``` ## Usage ```ts import { DynamicModule, Module } from '@nestjs/common'; @Module({}) export class DatabaseModule { static forRoot(connectionUri: string): DynamicModule { return { module: DatabaseModule, global: true, providers: [ { provide: 'DATABASE_URI', useValue: connectionUri, }, ], exports: ['DATABASE_URI'], }; } } // AppModule imports DatabaseModule.forRoot(...) ``` ## AI Coding Instructions - Return the concrete module class in the `module` property, typically the class that owns the static factory method. - Set `global: true` only when the module's exported providers should be available without repeated imports. - Use dynamic module factory methods such as `forRoot()` or `register()` to create configuration-specific module metadata. - Include providers, imports, controllers, and exports as needed alongside the required `module` property. - Avoid using `any` for application-level configuration values; define typed options interfaces for factory method arguments. ## Used by 29 references from 29 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (29) - `ROUTES` — `packages/core/router/router-module.ts`:9 - `CatsModule` — `integration/graphql-schema-first/src/cats/cats.module.ts`:6 - `CircularModule` — `integration/injector/src/circular-structure-dynamic-module/circular.module.ts`:4 - `NestDynamicModule` — `integration/injector/src/dynamic/dynamic.module.ts`:11 - `HelloModule` — `integration/inspector/src/circular-hello/hello.module.ts`:6 - `DatabaseModule` — `integration/repl/src/database/database.module.ts`:4 - `HelloModule` — `integration/scopes/src/circular-hello/hello.module.ts`:6 - `HelloModule` — `integration/scopes/src/circular-transient/hello.module.ts`:7 …and 21 more. # PipeTransform **Kind:** Interface **Source:** [`packages/common/interfaces/features/pipe-transform.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/pipe-transform.interface.ts#L37) **Part of:** [Common](subsystem-packages-common) Interface describing implementation of a pipe. `PipeTransform` defines the contract for pipes that transform or validate incoming values before they reach a route handler or other consumer. Implementations receive the raw value and argument metadata, then return a transformed value or throw an exception when validation fails. ## Diagram ```mermaid graph LR A[Incoming request value] --> B[PipeTransform.transform] C[ArgumentMetadata] --> B B -->|Valid / transformed value| D[Route handler parameter] B -->|Validation error| E[Exception response] ``` ## Usage ```ts import { ArgumentMetadata, BadRequestException, PipeTransform, } from '@nestjs/common'; export class ParsePositiveIntPipe implements PipeTransform { transform(value: string, metadata: ArgumentMetadata): number { const parsedValue = Number(value); if (!Number.isInteger(parsedValue) || parsedValue <= 0) { throw new BadRequestException( `${metadata.data ?? 'value'} must be a positive integer`, ); } return parsedValue; } } // Example route usage: // @Get(':id') // findOne(@Param('id', ParsePositiveIntPipe) id: number) { // return this.usersService.findOne(id); // } ``` ## AI Coding Instructions - Implement `transform(value, metadata)` and return the value type expected by the consuming handler. - Use `ArgumentMetadata` to tailor validation behavior or error messages based on the parameter source and name. - Throw framework HTTP exceptions, such as `BadRequestException`, for invalid input instead of returning invalid or partially transformed values. - Keep pipes focused on input transformation and validation; delegate business rules and persistence checks to services. - Ensure asynchronous pipes return a `Promise` and are registered where the value is bound, such as route parameters, request bodies, or global pipe configuration. ## Used by 30 references from 30 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (30) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `UserByIdPipe` — `integration/hello-world/src/hello/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/hello-world/src/host/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/hello-world/src/host-array/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/inspector/src/circular-hello/users/user-by-id.pipe.ts`:4 - `ParseIntPipe` — `integration/inspector/src/common/pipes/parse-int.pipe.ts`:8 - `UserByIdPipe` — `integration/scopes/src/circular-hello/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/scopes/src/circular-transient/users/user-by-id.pipe.ts`:8 …and 22 more. # isUndefined **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isUndefined(obj: any): obj is undefined ``` ## Parameters | Name | Type | |---|---| | `obj` | `any` | **Returns:** `obj is undefined` ## Used by 29 references from 29 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (29) - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `AdditionalHeaders` — `packages/core/router/sse-stream.ts`:38 - `handler` — `packages/core/middleware/middleware-module.ts`:287 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 - `isClassProvider` — `packages/core/injector/helpers/provider-classifier.ts`:9 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 …and 21 more. # isFunction **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L43) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isFunction(val: any): val is Function ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is Function` ## Used by 28 references from 28 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (28) - `anonymousMiddleware` — `packages/core/middleware/utils.ts`:77 - `InvalidClassScopeException` — `packages/core/errors/exceptions/invalid-class-scope.exception.ts`:6 - `BaseExceptionFilterContext` — `packages/core/exceptions/base-exception-filter-context.ts`:11 - `GuardsContextCreator` — `packages/core/guards/guards-context-creator.ts`:12 - `ParamProperties` — `packages/core/helpers/context-utils.ts`:15 - `callBeforeAppShutdownHook` — `packages/core/hooks/before-app-shutdown.hook.ts`:49 - `callModuleBootstrapHook` — `packages/core/hooks/on-app-bootstrap.hook.ts`:43 - `callAppShutdownHook` — `packages/core/hooks/on-app-shutdown.hook.ts`:45 …and 20 more. # isNil **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L48) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isNil(val: any): val is null | undefined ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is null | undefined` ## Used by 26 references from 26 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (26) - `AdditionalHeaders` — `packages/core/router/sse-stream.ts`:38 - `UNKNOWN_DEPENDENCIES_MESSAGE` — `packages/core/errors/messages.ts`:63 - `callBeforeAppShutdownHook` — `packages/core/hooks/before-app-shutdown.hook.ts`:49 - `callModuleBootstrapHook` — `packages/core/hooks/on-app-bootstrap.hook.ts`:43 - `callAppShutdownHook` — `packages/core/hooks/on-app-shutdown.hook.ts`:45 - `callModuleDestroyHook` — `packages/core/hooks/on-module-destroy.hook.ts`:41 - `callModuleInitHook` — `packages/core/hooks/on-module-init.hook.ts`:37 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 …and 18 more. # isObject **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isObject(fn: any): fn is object ``` ## Parameters | Name | Type | |---|---| | `fn` | `any` | **Returns:** `fn is object` ## Used by 26 references from 26 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (26) - `CustomHeader` — `packages/core/router/router-response-controller.ts`:18 - `AdditionalHeaders` — `packages/core/router/sse-stream.ts`:38 - `CreateDecoratorOptions` — `packages/core/services/reflector.service.ts`:8 - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 - `createContextId` — `packages/core/helpers/context-id-factory.ts`:5 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `Module` — `packages/core/injector/module.ts`:44 - `NestApplication` — `packages/core/nest-application.ts`:54 …and 18 more. # forwardRef **Kind:** Function **Source:** [`packages/common/utils/forward-ref.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/forward-ref.util.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function forwardRef(fn: () => any): ForwardReference ``` ## Parameters | Name | Type | |---|---| | `fn` | `() => any` | **Returns:** `ForwardReference` ## Used by 25 references from 17 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `CircularModule` — `integration/injector/src/circular-modules/circular.module.ts`:5 - `InputModule` — `integration/injector/src/circular-modules/input.module.ts`:5 - `CircularPropertiesModule` — `integration/injector/src/circular-properties/circular-properties.module.ts`:5 - `InputPropertiesModule` — `integration/injector/src/circular-properties/input-properties.module.ts`:5 - `CircularModule` — `integration/inspector/src/circular-modules/circular.module.ts`:5 - `InputModule` — `integration/inspector/src/circular-modules/input.module.ts`:5 - `AModule` — `integration/testing-module-override/circular-dependency/a.module.ts`:7 - `BModule` — `integration/testing-module-override/circular-dependency/b.module.ts`:7 ### Imported by (17) - `CircularService` — `integration/injector/src/circular/circular.service.ts`:4 - `InputService` — `integration/injector/src/circular/input.service.ts`:4 - `CircularModule` — `integration/injector/src/circular-modules/circular.module.ts`:5 - `CircularService` — `integration/injector/src/circular-modules/circular.service.ts`:4 - `InputModule` — `integration/injector/src/circular-modules/input.module.ts`:5 - `InputService` — `integration/injector/src/circular-modules/input.service.ts`:4 - `CircularPropertiesModule` — `integration/injector/src/circular-properties/circular-properties.module.ts`:5 - `CircularService` — `integration/injector/src/circular-properties/circular.service.ts`:4 …and 9 more. # HttpException **Kind:** Class **Source:** [`packages/common/exceptions/http.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts#L27) **Part of:** [Common](subsystem-packages-common) Defines the base Nest HTTP exception, which is handled by the default Exceptions Handler. `HttpException` is Nest’s base error type for representing HTTP failures with a response payload and status code. When thrown from application code, it is processed by Nest’s default exceptions handler to produce a structured HTTP error response. **Extends:** `IntrinsicException` ## Methods | Method | Signature | Returns | |---|---|---| | `initCause` | `initCause()` | `void` | | `initMessage` | `initMessage()` | `void` | | `initName` | `initName()` | `void` | | `getResponse` | `getResponse()` | `string | object` | | `getStatus` | `getStatus()` | `number` | | `createBody` | `createBody(nil: null | '', message: HttpExceptionBodyMessage, statusCode: number)` | `HttpExceptionBody` | | `createBody` | `createBody(message: HttpExceptionBodyMessage, error: string, statusCode: number)` | `HttpExceptionBody` | | `createBody` | `createBody(custom: Body)` | `Body` | | `createBody` | `createBody(arg0: null | HttpExceptionBodyMessage | Body, arg1: HttpExceptionBodyMessage | string, statusCode: number)` | `HttpExceptionBody | Body` | | `getDescriptionFrom` | `getDescriptionFrom(descriptionOrOptions: string | HttpExceptionOptions)` | `string` | | `getHttpExceptionOptionsFrom` | `getHttpExceptionOptionsFrom(descriptionOrOptions: string | HttpExceptionOptions)` | `HttpExceptionOptions` | | `extractDescriptionAndOptionsFrom` | `extractDescriptionAndOptionsFrom(descriptionOrOptions: string | HttpExceptionOptions)` | `DescriptionAndOptions` | ## Properties | Property | Type | |---|---| | `cause` | `unknown` | ## Where it refuses work - `HttpException` stops the work with an early return when `!arg0`. - `HttpException` stops the work with an early return when `isString(arg0) || Array.isArray(arg0) || isNumber(arg0)`. ## Diagram ```mermaid graph LR A[Controller / Service] -->|throw new HttpException| B[HttpException] B --> C[getStatus()] B --> D[getResponse()] B --> E[Default Exceptions Handler] C --> E D --> E E --> F[HTTP Error Response] ``` ## Usage ```ts import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common'; @Controller('reports') export class ReportsController { @Get() getReport() { const reportAvailable = false; if (!reportAvailable) { throw new HttpException( { statusCode: HttpStatus.NOT_FOUND, message: 'Report not found', error: 'Not Found', }, HttpStatus.NOT_FOUND, ); } return { id: 'report-123' }; } } ``` ## AI Coding Instructions - Throw `HttpException` when a request should end with a specific HTTP status and response body. - Use Nest’s `HttpStatus` enum instead of hard-coded numeric status codes. - Pass either a string or a structured object as the response; `getResponse()` returns the original payload. - Prefer specialized exceptions such as `NotFoundException` or `BadRequestException` when they match the intended status. - Use `HttpException.createBody()` when building standardized error response payloads for custom exceptions. ## Used by 10 references from 10 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (10) - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `ErrorsInterceptor` — `sample/01-cats-app/src/common/interceptors/exception.interceptor.ts`:12 - `ExceptionInterceptor` — `sample/10-fastify/src/common/interceptors/exception.interceptor.ts`:12 - `ErrorsInterceptor` — `sample/36-hmr-esm/src/common/interceptors/exception.interceptor.ts`:12 - `HttpExceptionFilter` — `integration/inspector/src/common/filters/http-exception.filter.ts`:8 - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 - `ExceptionsHandler` — `packages/core/exceptions/exceptions-handler.ts`:9 - `transformException` — `packages/platform-express/multer/multer/multer.utils.ts`:10 …and 2 more. # CanActivate **Kind:** Interface **Source:** [`packages/common/interfaces/features/can-activate.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/can-activate.interface.ts#L14) **Part of:** [Common](subsystem-packages-common) Interface defining the `canActivate()` function that must be implemented by a guard. Return value indicates whether or not the current request is allowed to proceed. Return can be either synchronous (`boolean`) or asynchronous (`Promise` or `Observable`). `CanActivate` defines the contract for guards that determine whether an incoming request may continue to a route handler. Implementations inspect the current `ExecutionContext` and return `true` or `false`, either synchronously or through a `Promise` or `Observable`. ## Diagram ```mermaid graph LR Request[Incoming Request] --> Guard[CanActivate Guard] Guard --> Context[ExecutionContext] Context --> Guard Guard --> Decision{canActivate() result} Decision -->|true| Handler[Route Handler] Decision -->|false| Denied[Request Denied] ``` ## Usage ```ts import { CanActivate, ExecutionContext, Injectable, } from '@nestjs/common'; @Injectable() export class ApiKeyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const apiKey = request.headers['x-api-key']; return apiKey === process.env.API_KEY; } } // Apply the guard to a controller or route: // @UseGuards(ApiKeyGuard) ``` ## AI Coding Instructions - Implement `canActivate(context: ExecutionContext)` on every guard that uses this interface. - Return a `boolean`, `Promise`, or `Observable`; do not return response objects or throw for ordinary authorization failures. - Use `ExecutionContext` to access the correct transport context, such as `switchToHttp()`, `switchToWs()`, or `switchToRpc()`. - Return `false` to deny access; Nest handles the resulting forbidden response unless custom exception behavior is required. - Register guards with `@UseGuards()` or configure them as global guards through the application provider setup. ## Used by 22 references from 22 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (22) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `AuthGuard` — `integration/graphql-code-first/src/common/guards/auth.guard.ts`:9 - `CatsGuard` — `integration/graphql-schema-first/src/cats/cats.guard.ts`:4 - `Guard` — `integration/inspector/src/circular-hello/guards/request-scoped.guard.ts`:9 - `RolesGuard` — `integration/inspector/src/common/guards/roles.guard.ts`:4 - `Guard` — `integration/scopes/src/circular-hello/guards/request-scoped.guard.ts`:9 - `Guard` — `integration/scopes/src/circular-transient/guards/request-scoped.guard.ts`:9 - `DurableGuard` — `integration/scopes/src/durable/durable.guard.ts`:9 …and 14 more. # isString **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L45) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isString(val: any): val is string ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is string` ## Used by 22 references from 22 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (22) - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `flattenRoutePaths` — `packages/core/router/utils/flatten-route-paths.util.ts`:5 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 - `anonymousMiddleware` — `packages/core/middleware/utils.ts`:77 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `INSTANCE_METADATA_SYMBOL` — `packages/core/injector/instance-wrapper.ts`:22 - `Module` — `packages/core/injector/module.ts`:44 …and 14 more. # loadPackage **Kind:** Function **Source:** [`packages/common/utils/load-package.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/load-package.util.ts#L8) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function loadPackage(packageName: string, context: string, loaderFn: Function) ``` ## Parameters | Name | Type | |---|---| | `packageName` | `string` | | `context` | `string` | | `loaderFn` | `Function` | ## Used by 16 references from 16 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (16) - `route` — `packages/microservices/server/server.ts`:168 - `NestApplication` — `packages/core/nest-application.ts`:54 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `ClientGrpcProxy` — `packages/microservices/client/client-grpc.ts`:31 - `ClientKafka` — `packages/microservices/client/client-kafka.ts`:58 - `ClientMqtt` — `packages/microservices/client/client-mqtt.ts`:28 - `ClientNats` — `packages/microservices/client/client-nats.ts`:29 - `ClientRedis` — `packages/microservices/client/client-redis.ts`:28 …and 8 more. # UseInterceptors **Kind:** Function **Source:** [`packages/common/decorators/core/use-interceptors.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/use-interceptors.decorator.ts#L28) **Part of:** [Common](subsystem-packages-common) Decorator that binds interceptors to the scope of the controller or method, depending on its context. When `@UseInterceptors` is used at the controller level, the interceptor will be applied to every handler (method) in the controller. When `@UseInterceptors` is used at the individual handler level, the interceptor will apply only to that specific method. `@UseInterceptors()` binds one or more interceptors to a controller class or an individual route handler. Controller-scoped interceptors run for every handler in that controller, while method-scoped interceptors affect only the decorated endpoint. Interceptors can transform requests or responses, add cross-cutting behavior, and wrap handler execution. ## Signature ```ts function UseInterceptors(interceptors: (NestInterceptor | Function)[]): MethodDecorator & ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `interceptors` | `(NestInterceptor | Function)[]` | **Returns:** `MethodDecorator & ClassDecorator` ## Diagram ```mermaid graph LR A[Incoming Request] --> B{Interceptor Scope} B -->|Controller| C[All Controller Handlers] B -->|Method| D[Decorated Handler Only] C --> E[Interceptor Chain] D --> E E --> F[Route Handler] F --> G[Response] ``` ## Usage ```ts import { Controller, Get, UseInterceptors, CallHandler, ExecutionContext, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; class ResponseWrapperInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable { return next.handle().pipe( map((data) => ({ data, })), ); } } @Controller('users') @UseInterceptors(ResponseWrapperInterceptor) export class UsersController { @Get() findAll() { return [{ id: 1, name: 'Ada' }]; } @Get('health') health() { return { status: 'ok' }; } } ``` ## AI Coding Instructions - Apply `@UseInterceptors()` to a controller for behavior shared by all of its handlers; apply it to a method for endpoint-specific behavior. - Pass interceptor classes, interceptor instances, or multiple interceptors as supported by the framework’s decorator metadata. - Implement interceptors with the `NestInterceptor` contract and call `next.handle()` unless intentionally short-circuiting request execution. - Preserve interceptor ordering when composing multiple interceptors, since each interceptor wraps the next handler in the chain. - Use interceptors for cross-cutting concerns such as response mapping, caching, logging, serialization, and timeouts rather than placing that logic directly in controllers. ## Used by 17 references from 17 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (17) - `RecipesResolver` — `integration/graphql-code-first/src/recipes/recipes.resolver.ts`:13 - `HelloController` — `integration/inspector/src/circular-hello/hello.controller.ts`:14 - `RequestChainController` — `integration/inspector/src/request-chain/request-chain.controller.ts`:5 - `PassthroughInterceptor` — `integration/nest-application/sse/src/app.controller.ts`:28 - `HelloController` — `integration/scopes/src/circular-hello/hello.controller.ts`:14 - `HelloController` — `integration/scopes/src/circular-transient/hello.controller.ts`:14 - `TestController` — `integration/scopes/src/circular-transient/test.controller.ts`:12 - `HelloController` — `integration/scopes/src/hello/hello.controller.ts`:14 …and 9 more. # NestApplicationContextOptions **Kind:** Class **Source:** [`packages/common/interfaces/nest-application-context-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-application-context-options.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Properties | Property | Type | |---|---| | `logger` | `LoggerService | LogLevel[] | false` | | `abortOnError` | `boolean | undefined` | | `bufferLogs` | `boolean` | | `autoFlushLogs` | `boolean` | | `preview` | `boolean` | | `snapshot` | `boolean` | | `moduleIdGeneratorAlgorithm` | `'deep-hash' | 'reference'` | | `instrument` | `{ instanceDecorator: (instance: unknown) => unknown; }` | | `forceConsole` | `boolean` | ## Used by 9 references from 9 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (9) - `handler` — `packages/core/middleware/middleware-module.ts`:287 - `NestContainer` — `packages/core/injector/container.ts`:31 - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 - `TestingModule` — `packages/testing/testing-module.ts`:26 - `SocketModule` — `packages/websockets/socket-module.ts`:27 …and 1 more. # isEmpty **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L50) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isEmpty(array: any): boolean ``` ## Parameters | Name | Type | |---|---| | `array` | `any` | **Returns:** `boolean` ## Used by 20 references from 20 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (20) - `RouterExceptionFilters` — `packages/core/router/router-exception-filters.ts`:14 - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `CreateDecoratorOptions` — `packages/core/services/reflector.service.ts`:8 - `BaseExceptionFilterContext` — `packages/core/exceptions/base-exception-filter-context.ts`:11 - `ExceptionsHandler` — `packages/core/exceptions/exceptions-handler.ts`:9 - `ExternalExceptionFilterContext` — `packages/core/exceptions/external-exception-filter-context.ts`:14 - `ExternalExceptionsHandler` — `packages/core/exceptions/external-exceptions-handler.ts`:8 - `GuardsConsumer` — `packages/core/guards/guards-consumer.ts`:7 …and 12 more. # HttpServer **Kind:** Interface **Source:** [`packages/common/interfaces/http/http-server.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/http-server.interface.ts#L17) **Part of:** [Common](subsystem-packages-common) ## Used by 16 references from 16 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (16) - `RouterExceptionFilters` — `packages/core/router/router-exception-filters.ts`:14 - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `CustomHeader` — `packages/core/router/router-response-controller.ts`:18 - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `MiddlewareBuilder` — `packages/core/middleware/builder.ts`:17 - `handler` — `packages/core/middleware/middleware-module.ts`:287 - `anonymousMiddleware` — `packages/core/middleware/utils.ts`:77 …and 8 more. # UseGuards **Kind:** Function **Source:** [`packages/common/decorators/core/use-guards.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/use-guards.decorator.ts#L28) **Part of:** [Common](subsystem-packages-common) Decorator that binds guards to the scope of the controller or method, depending on its context. When `@UseGuards` is used at the controller level, the guard will be applied to every handler (method) in the controller. When `@UseGuards` is used at the individual handler level, the guard will apply only to that specific method. `@UseGuards()` binds one or more guards to a controller class or individual route handler. Guards run before the request reaches the handler and determine whether execution should continue, making them suitable for authentication, authorization, and request-level access control. ## Signature ```ts function UseGuards(guards: (CanActivate | Function)[]): MethodDecorator & ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `guards` | `(CanActivate | Function)[]` | **Returns:** `MethodDecorator & ClassDecorator` ## Diagram ```mermaid graph LR Request[Incoming Request] --> Guard[Guard canActivate()] Guard -->|true| Handler[Controller Handler] Guard -->|false / throws| Denied[Request Denied] Controller["@UseGuards() on Controller"] --> AllHandlers[All Controller Handlers] Method["@UseGuards() on Method"] --> Handler ``` ## Usage ```ts import { Controller, Get, UseGuards, CanActivate, ExecutionContext, } from '@nestjs/common'; class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return Boolean(request.headers.authorization); } } @Controller('users') @UseGuards(AuthGuard) // Applies to every handler in this controller export class UsersController { @Get() findAll() { return ['user-1', 'user-2']; } @Get('public') // This route still inherits the controller-level guard. findPublicProfile() { return { name: 'Public User' }; } } @Controller('reports') export class ReportsController { @Get() @UseGuards(AuthGuard) // Applies only to this handler findReports() { return ['report-1']; } } ``` ## AI Coding Instructions - Apply `@UseGuards()` at the controller level for access rules shared by all routes; apply it at the handler level for route-specific rules. - Pass guard classes, guard instances, or multiple guards as arguments, for example `@UseGuards(AuthGuard, RolesGuard)`. - Ensure custom guards implement the `CanActivate` interface and return a boolean, Promise, or Observable result. - Remember that controller-level guards are inherited by handler methods; do not assume a method-level decorator replaces controller guards. - Use guards for authorization decisions, and keep validation or request transformation concerns in pipes and interceptors. ## Used by 15 references from 15 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (15) - `RecipesResolver` — `integration/graphql-code-first/src/recipes/recipes.resolver.ts`:13 - `CatsController` — `integration/inspector/src/cats/cats.controller.ts`:8 - `HelloController` — `integration/inspector/src/circular-hello/hello.controller.ts`:14 - `HelloController` — `integration/scopes/src/circular-hello/hello.controller.ts`:14 - `HelloController` — `integration/scopes/src/circular-transient/hello.controller.ts`:14 - `TestController` — `integration/scopes/src/circular-transient/test.controller.ts`:12 - `HelloController` — `integration/scopes/src/hello/hello.controller.ts`:14 - `HelloController` — `integration/scopes/src/msvc/hello.controller.ts`:8 …and 7 more. # RequestMethod **Kind:** Enum **Source:** [`packages/common/enums/request-method.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/common/enums/request-method.enum.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Values - `GET` - `POST` - `PUT` - `DELETE` - `PATCH` - `ALL` - `OPTIONS` - `HEAD` - `SEARCH` - `PROPFIND` - `PROPPATCH` - `MKCOL` - `COPY` - `MOVE` - `LOCK` - `UNLOCK` ## Used by 17 references from 17 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (17) - `ExcludeRouteMetadata` — `packages/core/router/interfaces/exclude-route-metadata.interface.ts`:3 - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `CustomHeader` — `packages/core/router/router-response-controller.ts`:18 - `isRequestMethodAll` — `packages/core/router/utils/exclude-route.util.ts`:5 - `AppModule` — `integration/nest-application/global-prefix/src/app.module.ts`:7 …and 9 more. # ArgumentMetadata **Kind:** Interface **Source:** [`packages/common/interfaces/features/pipe-transform.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/pipe-transform.interface.ts#L13) **Part of:** [Common](subsystem-packages-common) Interface describing a pipe implementation's `transform()` method metadata argument. `ArgumentMetadata` describes the contextual information passed to a pipe's `transform()` method for a controller argument. It identifies where the value came from, optionally provides the runtime type associated with the argument, and includes parameter-specific data such as a route parameter name. ## Properties | Property | Type | |---|---| | `type` | `Paramtype` | | `metatype` | `Type | undefined` | | `data` | `string | undefined` | ## Diagram ```mermaid graph LR A[Incoming request value] --> B[Pipe transform(value, metadata)] B --> C[ArgumentMetadata] C --> D[type: Paramtype] C --> E[metatype: Type or undefined] C --> F[data: string or undefined] B --> G[Transformed controller argument] ``` ## Usage ```ts import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common'; @Injectable() export class ParseIdPipe implements PipeTransform { transform(value: string, metadata: ArgumentMetadata): number | string { if (metadata.type === 'param' && metadata.data === 'id') { const id = Number(value); if (Number.isNaN(id)) { throw new Error('The id parameter must be a number.'); } return id; } return value; } } ``` ## AI Coding Instructions - Implement pipes with the `PipeTransform` interface and accept `ArgumentMetadata` as the second `transform()` argument. - Use `metadata.type` to distinguish values from request bodies, query parameters, route parameters, or custom arguments. - Treat `metadata.metatype` as optional; it may be `undefined` when no runtime type information is available. - Treat `metadata.data` as optional and use it for parameter-specific identifiers, such as a route parameter name. - Avoid relying solely on `metatype` for validation when handling primitive values or interfaces, which may not retain useful runtime metadata. ## Used by 15 references from 15 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (15) - `UserByIdPipe` — `integration/hello-world/src/hello/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/hello-world/src/host/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/hello-world/src/host-array/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/inspector/src/circular-hello/users/user-by-id.pipe.ts`:4 - `ParseIntPipe` — `integration/inspector/src/common/pipes/parse-int.pipe.ts`:8 - `UserByIdPipe` — `integration/scopes/src/circular-hello/users/user-by-id.pipe.ts`:4 - `UserByIdPipe` — `integration/scopes/src/circular-transient/users/user-by-id.pipe.ts`:8 - `UserByIdPipe` — `integration/scopes/src/hello/users/user-by-id.pipe.ts`:9 …and 7 more. # InjectionToken **Kind:** Type **Source:** [`packages/common/interfaces/modules/injection-token.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/injection-token.interface.ts#L7) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts | string | symbol | Type | Abstract | Function ``` ## Used by 16 references from 16 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (16) - `moduleName` — `packages/core/middleware/container.ts`:68 - `handler` — `packages/core/middleware/middleware-module.ts`:287 - `handler` — `packages/core/middleware/resolver.ts`:18 - `getTransientInstances` — `packages/core/injector/helpers/transient-instances.ts`:9 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `InstanceLink` — `packages/core/injector/instance-links-host.ts`:10 - `INSTANCE_METADATA_SYMBOL` — `packages/core/injector/instance-wrapper.ts`:22 - `Module` — `packages/core/injector/module.ts`:44 …and 8 more. # Provider **Kind:** Type **Source:** [`packages/common/interfaces/modules/provider.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/provider.interface.ts#L10) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts | Type | ClassProvider | ValueProvider | FactoryProvider | ExistingProvider ``` ## Used by 16 references from 16 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (16) - `requestProvider` — `packages/core/router/request/request-providers.ts`:5 - `HelloModule` — `integration/inspector/src/circular-hello/hello.module.ts`:6 - `HelloModule` — `integration/scopes/src/circular-hello/hello.module.ts`:6 - `HelloModule` — `integration/scopes/src/circular-transient/hello.module.ts`:7 - `HelloModule` — `integration/scopes/src/hello/hello.module.ts`:6 - `HelloModule` — `integration/scopes/src/msvc/hello.module.ts`:7 - `HelloModule` — `integration/scopes/src/transient/hello.module.ts`:7 - `ClientsModule` — `packages/microservices/module/clients.module.ts`:17 …and 8 more. # ArgumentsHost **Kind:** Interface **Source:** [`packages/common/interfaces/features/arguments-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/arguments-host.interface.ts#L64) **Part of:** [Common](subsystem-packages-common) Provides methods for retrieving the arguments being passed to a handler. Allows choosing the appropriate execution context (e.g., Http, RPC, or WebSockets) to retrieve the arguments from. `ArgumentsHost` provides access to the arguments supplied when a framework handler is invoked. It lets guards, interceptors, filters, and other framework components inspect the current execution context and switch to the appropriate transport-specific host, such as HTTP, RPC, or WebSockets. ## Diagram ```mermaid graph LR A[Handler invocation] --> B[ArgumentsHost] B --> C[getArgs / getArgByIndex] B --> D[switchToHttp] B --> E[switchToRpc] B --> F[switchToWs] D --> G[HTTP request, response, next] E --> H[RPC data and context] F --> I[WebSocket client and data] ``` ## Usage ```ts import { ArgumentsHost, Catch, ExceptionFilter, HttpException, } from '@nestjs/common'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const http = host.switchToHttp(); const response = http.getResponse(); const request = http.getRequest(); response.status(exception.getStatus()).json({ statusCode: exception.getStatus(), path: request.url, message: exception.message, }); } } ``` ## AI Coding Instructions - Use `switchToHttp()`, `switchToRpc()`, or `switchToWs()` before reading transport-specific arguments. - Prefer the typed host adapters over accessing raw values through `getArgs()` or `getArgByIndex()`. - Keep shared guards, interceptors, and filters transport-aware; not every `ArgumentsHost` represents an HTTP request. - Use `getType()` when behavior must differ between HTTP, RPC, and WebSocket execution contexts. - Avoid assuming argument positions are consistent across transports; use the relevant context adapter methods instead. ## Used by 13 references from 13 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (13) - `UnauthorizedFilter` — `integration/graphql-code-first/src/common/filters/unauthorized.filter.ts`:4 - `HttpExceptionFilter` — `integration/inspector/src/common/filters/http-exception.filter.ts`:8 - `RequestFilter` — `integration/websockets/src/request.filter.ts`:4 - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 - `ExceptionsHandler` — `packages/core/exceptions/exceptions-handler.ts`:9 - `ExternalExceptionFilter` — `packages/core/exceptions/external-exception-filter.ts`:3 - `ExternalExceptionsHandler` — `packages/core/exceptions/external-exceptions-handler.ts`:8 - `BaseRpcExceptionFilter` — `packages/microservices/exceptions/base-rpc-exception-filter.ts`:15 …and 5 more. # HttpCode **Kind:** Function **Source:** [`packages/common/decorators/http/http-code.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/http-code.decorator.ts#L13) **Part of:** [Common](subsystem-packages-common) Request method Decorator. Defines the HTTP response status code. Overrides default status code for the decorated request method. `HttpCode()` is a method decorator that explicitly sets the HTTP status code returned by a request handler. It overrides the framework’s default response status for the decorated controller method, such as returning `204 No Content` after a successful update. ## Signature ```ts function HttpCode(statusCode: number): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `statusCode` | `number` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Controller Route Handler] B --> C[@HttpCode(status)] C --> D[Response Status Metadata] D --> E[HTTP Response with Configured Status Code] ``` ## Usage ```ts import { Controller, Post, HttpCode, HttpStatus } from '@nestjs/common'; @Controller('sessions') export class SessionsController { @Post('logout') @HttpCode(HttpStatus.NO_CONTENT) logout(): void { // End the current session. } } ``` ## AI Coding Instructions - Apply `@HttpCode()` directly to controller request-handler methods, alongside route decorators such as `@Get()`, `@Post()`, or `@Delete()`. - Use `HttpStatus` constants instead of hard-coded numeric status codes when possible for readability. - Choose a status code that matches the endpoint behavior; for example, use `204` when no response body is returned. - Remember that `@HttpCode()` overrides the default status associated with the HTTP request method. ## Used by 12 references from 12 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (12) - `AppController` — `integration/microservices/src/app.controller.ts`:20 - `GrpcController` — `integration/microservices/src/grpc/grpc.controller.ts`:21 - `AdvancedGrpcController` — `integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`:14 - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 - `KafkaConcurrentMessagesController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.messages.controller.ts`:6 - `MqttController` — `integration/microservices/src/mqtt/mqtt.controller.ts`:16 - `NatsController` — `integration/microservices/src/nats/nats.controller.ts`:19 …and 4 more. # StreamableFile **Kind:** Class **Source:** [`packages/common/file-stream/streamable-file.ts`](https://github.com/nestjs/nest/blob/master/packages/common/file-stream/streamable-file.ts#L13) **Part of:** [Common](subsystem-packages-common) `StreamableFile` wraps a `Readable` stream or in-memory buffer so it can be returned as a streamed HTTP response. It centralizes response metadata such as content type, disposition, and length, while allowing custom stream error handling and logging. ## Methods | Method | Signature | Returns | |---|---|---| | `getStream` | `getStream()` | `Readable` | | `getHeaders` | `getHeaders()` | `void` | | `setErrorHandler` | `setErrorHandler(handler: (err: Error, response: StreamableHandlerResponse) => void)` | `void` | | `setErrorLogger` | `setErrorLogger(handler: (err: Error) => void)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `handleError` | `( err: Error, response: StreamableHandlerResponse, ) => void` | | `logError` | `(err: Error) => void` | ## Where it refuses work - `StreamableFile` stops the work with an early return when `res.destroyed`. ## Diagram ```mermaid graph LR A[File Buffer or Readable Stream] --> B[StreamableFile] B --> C[getStream()] B --> D[getHeaders()] B --> E[setErrorHandler()] B --> F[setErrorLogger()] C --> G[HTTP Response Stream] D --> G E --> H[Custom Error Response] F --> I[Application Logger] ``` ## Usage ```ts import { Controller, Get, StreamableFile } from '@nestjs/common'; import { createReadStream } from 'node:fs'; import { join } from 'node:path'; @Controller('reports') export class ReportsController { @Get('download') download(): StreamableFile { const filePath = join(process.cwd(), 'files', 'monthly-report.pdf'); const stream = createReadStream(filePath); return new StreamableFile(stream, { type: 'application/pdf', disposition: 'attachment; filename="monthly-report.pdf"', }) .setErrorLogger((error) => { console.error('Unable to stream report:', error); }) .setErrorHandler((error, response) => { response.statusCode = 500; response.end('The report could not be downloaded.'); }); } } ``` ## AI Coding Instructions - Pass a `Readable` stream for large files to avoid loading the entire file into memory; use a buffer only for small generated content. - Set `type` and `disposition` options when returning downloadable files so clients receive the correct MIME type and filename. - Return the `StreamableFile` instance directly from supported controller routes rather than manually piping its stream unless custom response handling is required. - Configure `setErrorLogger()` and `setErrorHandler()` when stream failures need application-specific logging or HTTP error responses. - Ensure file streams are created from validated paths and that stream errors are handled, especially for files that may be missing or inaccessible. ## How it works `StreamableFile` is an exported class that packages either byte data or a readable/pipe-capable object with optional HTTP file-response metadata. It is re-exported from the common package. [packages/common/file-stream/streamable-file.ts:13](packages/common/file-stream/streamable-file.ts#L13) [packages/common/index.ts:9-12](packages/common/index.ts#L9-L12) - Its declared constructor overloads accept a `Uint8Array` or Node `Readable`, plus optional `StreamableFileOptions`. At runtime, it also accepts any object whose `pipe` property is a function. [packages/common/file-stream/streamable-file.ts:37-50](packages/common/file-stream/streamable-file.ts#L37-L50) [packages/common/utils/shared.utils.ts:43-44](packages/common/utils/shared.utils.ts#L43-L44) - For a `Uint8Array`—including a `Buffer`—it creates a new `Readable`, pushes the byte array, then pushes `null` to end that stream. If `options.length` is nullish, construction writes the byte-array length into the supplied options object. [packages/common/file-stream/streamable-file.ts:43-47](packages/common/file-stream/streamable-file.ts#L43-L47) - For an input with a functional `pipe`, it retains that input as the stream rather than wrapping it. [packages/common/file-stream/streamable-file.ts:48-50](packages/common/file-stream/streamable-file.ts#L48-L50) - Input that is neither a `Uint8Array` nor pipe-capable is not rejected by this constructor, and no stream is assigned; consequently, `getStream()` returns `undefined` in the tested case despite its declared `Readable` return type. Consumers that need a stream must therefore pass byte data or a pipe-capable object. [packages/common/file-stream/streamable-file.ts:43-55](packages/common/file-stream/streamable-file.ts#L43-L55) [packages/common/test/file-stream/streamable-file.spec.ts:22-27](packages/common/test/file-stream/streamable-file.spec.ts#L22-L27) - `getStream()` returns the stored stream reference. [packages/common/file-stream/streamable-file.ts:53-55](packages/common/file-stream/streamable-file.ts#L53-L55) `StreamableFileOptions` contains `type`, `disposition`, and `length`, corresponding to `Content-Type`, `Content-Disposition`, and `Content-Length` response headers. `disposition` may be a string or string array. [packages/common/file-stream/interfaces/streamable-options.interface.ts:8-21](packages/common/file-stream/interfaces/streamable-options.interface.ts#L8-L21) `getHeaders()` returns these three values, defaulting `type` to `application/octet-stream` and the other two to `undefined`. [packages/common/file-stream/streamable-file.ts:57-68](packages/common/file-stream/streamable-file.ts#L57-L68) When an Express response body is a `StreamableFile`, the adapter sets those headers only if the response does not already contain them, then pipes `getStream()` into the response. String-array header values are joined with commas before Express sets them. [packages/platform-express/adapters/express-adapter.ts:110-118](packages/platform-express/adapters/express-adapter.ts#L110-L118) [packages/platform-express/adapters/express-adapter.ts:501-522](packages/platform-express/adapters/express-adapter.ts#L501-L522) The Fastify adapter similarly assigns absent headers and sends the stored stream. [packages/platform-fastify/adapters/fastify-adapter.ts:449-482](packages/platform-fastify/adapters/fastify-adapter.ts#L449-L482) The class exposes replaceable stream-error callbacks: - The default `errorHandler` returns without action when `response.destroyed` is true. If headers were already sent, it calls `response.end()`. Otherwise, it sets `response.statusCode` to `HttpStatus.BAD_REQUEST` (`400`) and sends `err.message`. [packages/common/file-stream/streamable-file.ts:17-31](packages/common/file-stream/streamable-file.ts#L17-L31) [packages/common/enums/http-status.enum.ts:24-27](packages/common/enums/http-status.enum.ts#L24-L27) - `setErrorHandler(handler)` replaces that callback and returns the same `StreamableFile` instance for chaining. [packages/common/file-stream/streamable-file.ts:70-82](packages/common/file-stream/streamable-file.ts#L70-L82) - The default `errorLogger` calls `Logger('StreamableFile').error(err)`. `setErrorLogger(handler)` replaces it and also returns the instance. [packages/common/file-stream/streamable-file.ts:15](packages/common/file-stream/streamable-file.ts#L15) [packages/common/file-stream/streamable-file.ts:33-35](packages/common/file-stream/streamable-file.ts#L33-L35) [packages/common/file-stream/streamable-file.ts:84-91](packages/common/file-stream/streamable-file.ts#L84-L91) - In the Express adapter, a source-stream `error` invokes `errorHandler(err, response)`, while an error emitted by the result of `stream.pipe(response)` invokes `errorLogger(err)`. [packages/platform-express/adapters/express-adapter.ts:112-118](packages/platform-express/adapters/express-adapter.ts#L112-L118) ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `AppController` — `integration/send-files/src/app.controller.ts`:6 - `AppService` — `integration/send-files/src/app.service.ts`:9 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # ConfigurableModuleBuilder **Kind:** Class **Source:** [`packages/common/module-utils/configurable-module.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/configurable-module.builder.ts#L53) **Part of:** [Common](subsystem-packages-common) Factory that lets you create configurable modules and provides a way to reduce the majority of dynamic module boilerplate. `ConfigurableModuleBuilder` generates the dynamic-module infrastructure needed to configure a NestJS module without manually writing repetitive `forRoot`, `forRootAsync`, options-token, and provider boilerplate. It lets module authors customize static method names, factory method names, and extra module-definition options before producing a `ConfigurableModuleHost`. ## Methods | Method | Signature | Returns | |---|---|---| | `setExtras` | `setExtras(extras: ExtraModuleDefinitionOptions, transformDefinition: ( definition: DynamicModule, extras: ExtraModuleDefinitionOptions, ) => DynamicModule)` | `void` | | `setClassMethodName` | `setClassMethodName(key: StaticMethodKey)` | `void` | | `setFactoryMethodName` | `setFactoryMethodName(key: FactoryClassMethodKey)` | `void` | | `build` | `build()` | `ConfigurableModuleHost< ModuleOptions, StaticMethodKey, FactoryClassMethodKey, ExtraModuleDefinitionOptions >` | ## Properties | Property | Type | |---|---| | `staticMethodKey` | `StaticMethodKey` | | `factoryClassMethodKey` | `FactoryClassMethodKey` | | `extras` | `ExtraModuleDefinitionOptions` | | `transformModuleDefinition` | `( definition: DynamicModule, extraOptions: ExtraModuleDefinitionOptions, ) => DynamicModule` | | `logger` | `any` | ## Where it refuses work - `ConfigurableModuleBuilder` stops the work with an early return when `!extras`, in 2 places. - `ConfigurableModuleBuilder` stops the work with an early return when `options.inject && options.provideInjectionTokensFrom`. - `ConfigurableModuleBuilder` stops the work with an early return when `options.useFactory`. ## Diagram ```mermaid graph LR A[ConfigurableModuleBuilder] --> B[Configure method names] A --> C[Configure extras] B --> D[build()] C --> D D --> E[ConfigurableModuleHost] E --> F[ConfigurableModuleClass] E --> G[MODULE_OPTIONS_TOKEN] E --> H[OPTIONS_TYPE / ASYNC_OPTIONS_TYPE] F --> I[Application Module Imports] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ConfigurableModuleBuilder } from '@nestjs/common'; export interface EmailModuleOptions { apiKey: string; sender: string; } const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, } = new ConfigurableModuleBuilder() .setClassMethodName('forRoot') .setFactoryMethodName('createEmailOptions') .setExtras( { isGlobal: false }, (definition, extras) => ({ ...definition, global: extras.isGlobal, }), ) .build(); @Module({ providers: [ { provide: 'EMAIL_OPTIONS', useExisting: MODULE_OPTIONS_TOKEN, }, ], exports: ['EMAIL_OPTIONS'], }) export class EmailModule extends ConfigurableModuleClass {} // In another module: // EmailModule.forRoot({ // apiKey: process.env.EMAIL_API_KEY!, // sender: 'noreply@example.com', // }) ``` ## AI Coding Instructions - Create one `ConfigurableModuleBuilder` per configurable module and export the generated options token when other providers need access to configuration. - Call `setClassMethodName()` only when the default `register` method does not match the module’s public API convention, such as `forRoot`. - Use `setExtras()` for module-definition concerns such as `global`, not for runtime options that application providers consume. - Extend the generated `ConfigurableModuleClass` in the final `@Module()` class so generated synchronous and asynchronous registration methods remain available. - Keep custom factory method names aligned with async configuration factories when using `registerAsync`/`forRootAsync`-style integration. # BadRequestException **Kind:** Class **Source:** [`packages/common/exceptions/bad-request.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/bad-request.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Bad Request* type errors. `BadRequestException` represents an HTTP 400 error caused by invalid client input, malformed requests, or failed validation. It extends the framework's HTTP exception handling flow, allowing controllers and services to return consistent error responses that can be processed by global exception filters. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client Request] --> Controller[Controller or Service] Controller --> Validation{Input valid?} Validation -->|Yes| Handler[Continue request handling] Validation -->|No| Exception[BadRequestException] Exception --> Filter[HTTP Exception Filter] Filter --> Response[HTTP 400 Bad Request Response] ``` ## Usage ```ts import { BadRequestException } from '@nestjs/common'; export class UsersService { async createUser(email: string) { const existingUser = await this.findByEmail(email); if (existingUser) { throw new BadRequestException( 'A user with this email address already exists', ); } return this.saveUser({ email }); } private async findByEmail(email: string) { // Look up an existing user. } private async saveUser(user: { email: string }) { // Persist and return the new user. } } ``` ## AI Coding Instructions - Throw `BadRequestException` only for client-correctable request errors, such as invalid input, missing required data, or invalid request state. - Provide clear, actionable error messages; avoid exposing internal implementation details, database errors, or sensitive data. - Prefer validation pipes and DTO validation decorators for standard input validation; use this exception for custom business-rule validation. - Do not use this exception for authentication, authorization, missing resources, or server failures; use the corresponding HTTP exception type instead. - Ensure custom exception payloads remain compatible with the application's global exception filters and API error-response conventions. ## Used by 10 references from 10 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (10) - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `ErrorsController` — `integration/hello-world/src/errors/errors.controller.ts`:3 - `ParseIntPipe` — `integration/inspector/src/common/pipes/parse-int.pipe.ts`:8 - `ParseIntPipe` — `sample/01-cats-app/src/common/pipes/parse-int.pipe.ts`:8 - `ValidationPipe` — `sample/01-cats-app/src/common/pipes/validation.pipe.ts`:11 - `ParseIntPipe` — `sample/10-fastify/src/common/pipes/parse-int.pipe.ts`:4 - `ValidationPipe` — `sample/10-fastify/src/common/pipes/validation.pipe.ts`:11 - `ParseIntPipe` — `sample/36-hmr-esm/src/common/pipes/parse-int.pipe.ts`:8 …and 2 more. # SetMetadata **Kind:** Function **Source:** [`packages/common/decorators/core/set-metadata.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/set-metadata.decorator.ts#L22) **Part of:** [Common](subsystem-packages-common) Decorator that assigns metadata to the class/function using the specified `key`. Requires two parameters: - `key` - a value defining the key under which the metadata is stored - `value` - metadata to be associated with `key` This metadata can be reflected using the `Reflector` class. Example: `@SetMetadata('roles', ['admin'])` `SetMetadata` is a decorator factory that attaches custom metadata to a class or method under a specified key. NestJS components, such as guards and interceptors, can later read this metadata through `Reflector` to drive runtime behavior like authorization or feature configuration. ## Signature ```ts function SetMetadata(metadataKey: K, metadataValue: V): CustomDecorator ``` ## Parameters | Name | Type | |---|---| | `metadataKey` | `K` | | `metadataValue` | `V` | **Returns:** `CustomDecorator` ## Diagram ```mermaid graph LR A["@SetMetadata(key, value)"] --> B["Class or method"] B --> C["Reflect metadata storage"] C --> D["Reflector"] D --> E["Guard / interceptor / application logic"] ``` ## Usage ```ts import { Controller, Get, SetMetadata } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; export const ROLES_KEY = 'roles'; @Controller('users') export class UsersController { @Get() @SetMetadata(ROLES_KEY, ['admin']) findAll() { return []; } } // Example usage inside a guard: const roles = reflector.get(ROLES_KEY, context.getHandler()); ``` ## AI Coding Instructions - Use stable, descriptive metadata keys; export key constants when multiple files need to read the same metadata. - Apply `SetMetadata` to classes for controller-wide configuration or methods for route-specific configuration. - Read metadata through Nest's `Reflector`, typically using `getAllAndOverride` when both class- and method-level values should be supported. - Keep metadata values serializable and predictable, such as strings, arrays, or configuration objects. - Avoid using duplicate generic string keys across unrelated features, as metadata keys share the decorated target's metadata store. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `CreateDecoratorOptions` — `packages/core/services/reflector.service.ts`:8 - `FilterByInclude` — `packages/core/discovery/discovery-service.ts`:16 - `RouteConfig` — `packages/platform-fastify/decorators/route-config.decorator.ts`:9 - `RouteConstraints` — `packages/platform-fastify/decorators/route-constraints.decorator.ts`:10 - `RouteSchema` — `packages/platform-fastify/decorators/route-schema.decorator.ts`:14 - `Roles` — `sample/10-fastify/src/common/decorators/roles.decorator.ts`:3 - `IS_PUBLIC_KEY` — `sample/19-auth-jwt/src/auth/decorators/public.decorator.ts`:3 # addLeadingSlash **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L26) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function addLeadingSlash(path: string): string ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string` ## Used by 9 references from 9 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (9) - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `isRequestMethodAll` — `packages/core/router/utils/exclude-route.util.ts`:5 - `RouteInfoPathExtractor` — `packages/core/middleware/route-info-path-extractor.ts`:16 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 - `anonymousMiddleware` — `packages/core/middleware/utils.ts`:77 - `NestApplication` — `packages/core/nest-application.ts`:54 …and 1 more. # VersionValue **Kind:** Type **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L13) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts | string | typeof VERSION_NEUTRAL | Array ``` ## Used by 12 references from 12 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (12) - `RoutePathMetadata` — `packages/core/router/interfaces/route-path-metadata.interface.ts`:4 - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `RouteInfoPathExtractor` — `packages/core/middleware/route-info-path-extractor.ts`:16 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 - `AbstractHttpAdapter` — `packages/core/adapters/http-adapter.ts`:8 …and 4 more. # HttpStatus **Kind:** Enum **Source:** [`packages/common/enums/http-status.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/common/enums/http-status.enum.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Values - `CONTINUE` - `SWITCHING_PROTOCOLS` - `PROCESSING` - `EARLYHINTS` - `OK` - `CREATED` - `ACCEPTED` - `NON_AUTHORITATIVE_INFORMATION` - `NO_CONTENT` - `RESET_CONTENT` - `PARTIAL_CONTENT` - `MULTI_STATUS` - `ALREADY_REPORTED` - `CONTENT_DIFFERENT` - `AMBIGUOUS` - `MOVED_PERMANENTLY` - `FOUND` - `SEE_OTHER` - `NOT_MODIFIED` - `TEMPORARY_REDIRECT` - `PERMANENT_REDIRECT` - `BAD_REQUEST` - `UNAUTHORIZED` - `PAYMENT_REQUIRED` - `FORBIDDEN` - `NOT_FOUND` - `METHOD_NOT_ALLOWED` - `NOT_ACCEPTABLE` - `PROXY_AUTHENTICATION_REQUIRED` - `REQUEST_TIMEOUT` - `CONFLICT` - `GONE` - `LENGTH_REQUIRED` - `PRECONDITION_FAILED` - `PAYLOAD_TOO_LARGE` - `URI_TOO_LONG` - `UNSUPPORTED_MEDIA_TYPE` - `REQUESTED_RANGE_NOT_SATISFIABLE` - `EXPECTATION_FAILED` - `I_AM_A_TEAPOT` - `MISDIRECTED` - `UNPROCESSABLE_ENTITY` - `LOCKED` - `FAILED_DEPENDENCY` - `PRECONDITION_REQUIRED` - `TOO_MANY_REQUESTS` - `UNRECOVERABLE_ERROR` - `INTERNAL_SERVER_ERROR` - `NOT_IMPLEMENTED` - `BAD_GATEWAY` ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `CustomHeader` — `packages/core/router/router-response-controller.ts`:18 - `ErrorsInterceptor` — `sample/01-cats-app/src/common/interceptors/exception.interceptor.ts`:12 - `ExceptionInterceptor` — `sample/10-fastify/src/common/interceptors/exception.interceptor.ts`:12 - `AuthController` — `sample/19-auth-jwt/src/auth/auth.controller.ts`:13 - `ErrorsInterceptor` — `sample/36-hmr-esm/src/common/interceptors/exception.interceptor.ts`:12 - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # ExceptionFilter **Kind:** Interface **Source:** [`packages/common/interfaces/exceptions/exception-filter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/exceptions/exception-filter.interface.ts#L10) **Part of:** [Common](subsystem-packages-common) Interface describing implementation of an exception filter. `ExceptionFilter` defines the contract for handling exceptions thrown during request processing. Implementations receive the thrown exception and an `ArgumentsHost`, allowing them to create framework-specific error responses, log failures, or transform errors before they reach the client. ## Diagram ```mermaid graph LR A[Request Handler] -->|throws exception| B[ExceptionFilter.catch] B --> C[ArgumentsHost] C --> D[HTTP / RPC / WebSocket Context] B --> E[Formatted Error Response] E --> F[Client] ``` ## Usage ```ts import { ArgumentsHost, Catch, ExceptionFilter, HttpException, } from '@nestjs/common'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const response = host.switchToHttp().getResponse(); const request = host.switchToHttp().getRequest(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message, path: request.url, timestamp: new Date().toISOString(), }); } } // Register globally: // app.useGlobalFilters(new HttpExceptionFilter()); ``` ## AI Coding Instructions - Implement `catch(exception, host)` and use `host.switchToHttp()`, `switchToRpc()`, or `switchToWs()` for the active transport. - Type the exception generic, such as `ExceptionFilter`, when the filter handles a specific error class. - Add `@Catch(ErrorType)` to bind a filter to one or more exception types. - Avoid exposing stack traces or internal error details in production responses. - Register filters at the appropriate scope: method, controller, module provider, or globally with `useGlobalFilters()`. ## Used by 10 references from 10 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (10) - `HttpExceptionFilter` — `integration/inspector/src/common/filters/http-exception.filter.ts`:8 - `RequestFilter` — `integration/websockets/src/request.filter.ts`:4 - `ApplicationConfig` — `packages/core/application-config.ts`:13 - `BaseExceptionFilterContext` — `packages/core/exceptions/base-exception-filter-context.ts`:11 - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 - `NestApplication` — `packages/core/nest-application.ts`:54 - `DependenciesScanner` — `packages/core/scanner.ts`:75 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 …and 2 more. # INestApplication **Kind:** Interface **Source:** [`packages/common/interfaces/nest-application.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-application.interface.ts#L20) **Part of:** [Common](subsystem-packages-common) Interface defining the core NestApplication object. `INestApplication` defines the public API for a running Nest HTTP application. It extends the application context capabilities with HTTP server configuration, middleware registration, microservice integration, lifecycle management, and network listening methods. ## Diagram ```mermaid graph LR A[NestFactory.create] --> B[INestApplication] B --> C[Configure application] C --> C1[Middleware] C --> C2[CORS and versioning] C --> C3[Global prefix] C --> C4[WebSocket adapter] B --> D[Connect microservices] B --> E[Initialize and listen] E --> F[HTTP Server] F --> G[Clients] ``` ## Usage ```ts import { INestApplication } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap(): Promise { const app: INestApplication = await NestFactory.create(AppModule); app.setGlobalPrefix('api'); app.enableCors({ origin: ['https://example.com'], credentials: true, }); await app.listen(3000); console.log(`Application running at ${await app.getUrl()}`); } bootstrap(); ``` ## AI Coding Instructions - Obtain an `INestApplication` through `NestFactory.create()` and configure it before calling `listen()`. - Use `setGlobalPrefix()`, `enableCors()`, versioning, and middleware registration for application-wide HTTP behavior. - Use `connectMicroservice()` and `startAllMicroservices()` when building hybrid HTTP and microservice applications. - Prefer `getHttpServer()` only when an integration requires direct access to the underlying platform server. - Enable shutdown hooks when the application must gracefully handle process termination signals. ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `getHttpBaseOptions` — `integration/send-files/e2e/utils.ts`:5 - `NestApplication` — `packages/core/nest-application.ts`:54 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `NestExpressApplication` — `packages/platform-express/interfaces/nest-express-application.interface.ts`:20 - `NestFastifyApplication` — `packages/platform-fastify/interfaces/nest-fastify-application.interface.ts`:27 - `TestingModule` — `packages/testing/testing-module.ts`:26 # assignMetadata **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L30) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function assignMetadata(args: TArgs, paramtype: TParamtype, index: number, data: ParamData, pipes: (Type | PipeTransform)[]) ``` ## Parameters | Name | Type | |---|---| | `args` | `TArgs` | | `paramtype` | `TParamtype` | | `index` | `number` | | `data` | `ParamData` | | `pipes` | `(Type | PipeTransform)[]` | ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createRpcParamDecorator` — `packages/microservices/utils/param.utils.ts`:8 - `createWsParamDecorator` — `packages/websockets/utils/param.utils.ts`:8 # Optional **Kind:** Function **Source:** [`packages/common/decorators/core/optional.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/optional.decorator.ts#L20) **Part of:** [Common](subsystem-packages-common) Parameter decorator for an injected dependency marking the dependency as optional. For example: ```typescript constructor(@Optional() `Optional()` is a parameter decorator that marks a constructor dependency as optional in Nest's dependency injection system. If the requested provider is not available, Nest injects `undefined` instead of throwing a resolution error, allowing the consuming class to handle the absence of that dependency. ## Signature ```ts function Optional(): PropertyDecorator & ParameterDecorator ``` **Returns:** `PropertyDecorator & ParameterDecorator` ## Diagram ```mermaid graph LR A[Constructor parameter] --> B["@Optional()"] B --> C[Nest dependency injector] C -->|Provider available| D[Inject provider instance] C -->|Provider unavailable| E[Inject undefined] D --> F[Consumer handles dependency] E --> F ``` ## Usage ```typescript import { Inject, Injectable, Optional } from '@nestjs/common'; @Injectable() export class AuditService { constructor( @Optional() @Inject('AUDIT_LOGGER') private readonly logger?: { log(message: string): void }, ) {} recordEvent(event: string) { this.logger?.log(`Audit event: ${event}`); } } ``` ## AI Coding Instructions - Use `@Optional()` only on constructor parameters managed by Nest's dependency injection container. - Combine it with `@Inject()` when injecting optional custom tokens, interfaces, or string/symbol-based providers. - Type optional dependencies as optional (`dependency?: Type`) or explicitly handle `undefined` before using them. - Do not use `@Optional()` to hide required configuration or provider-registration mistakes; use it only when the dependency is genuinely optional. - Ensure consumers safely degrade when the provider is absent, for example with optional chaining or a fallback implementation. ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `DefaultsService` — `integration/injector/src/defaults/defaults.service.ts`:4 - `DefaultsService` — `integration/inspector/src/defaults/defaults.service.ts`:4 - `AnyFilesInterceptor` — `packages/platform-express/multer/interceptors/any-files.interceptor.ts`:24 - `FileFieldsInterceptor` — `packages/platform-express/multer/interceptors/file-fields.interceptor.ts`:27 - `FileInterceptor` — `packages/platform-express/multer/interceptors/file.interceptor.ts`:25 - `FilesInterceptor` — `packages/platform-express/multer/interceptors/files.interceptor.ts`:27 - `NoFilesInterceptor` — `packages/platform-express/multer/interceptors/no-files.interceptor.ts`:24 - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 # Header **Kind:** Function **Source:** [`packages/common/decorators/http/header.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/header.decorator.ts#L18) **Part of:** [Common](subsystem-packages-common) Request method Decorator. Sets a response header. For example: `@Header('Cache-Control', 'none')` `@Header('Cache-Control', () => 'none')` `Header` is a request method decorator that configures an HTTP response header for a route handler. Apply it to controller methods to set a static header value or compute the value dynamically when the request is handled. ## Signature ```ts function Header(name: string, value: string | (() => string)): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `value` | `string | (() => string)` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Controller Route Handler] B --> C[@Header Decorator Metadata] C --> D[Response Header Applied] D --> E[HTTP Response] ``` ## Usage ```ts import { Controller, Get, Header } from '@nestjs/common'; @Controller('reports') export class ReportsController { @Get('cached') @Header('Cache-Control', 'public, max-age=3600') getCachedReport() { return { status: 'ok' }; } @Get('dynamic') @Header('Cache-Control', () => 'no-store') getDynamicReport() { return { status: 'ok' }; } } ``` ## AI Coding Instructions - Apply `@Header()` to route handler methods, alongside decorators such as `@Get()`, `@Post()`, or other HTTP method decorators. - Use a string value for headers that are known at declaration time, such as `Content-Type` or `Cache-Control`. - Use a callback value when the header must be resolved dynamically during request handling. - Ensure header names and values comply with HTTP header conventions; avoid setting restricted or conflicting headers unintentionally. - Prefer framework response metadata decorators like `@Header()` over manually mutating the response object when the value does not require imperative response handling. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ErrorsController` — `integration/hello-world/src/errors/errors.controller.ts`:3 - `HelloController` — `integration/hello-world/src/hello/hello.controller.ts`:6 - `HostController` — `integration/hello-world/src/host/host.controller.ts`:6 - `HostArrayController` — `integration/hello-world/src/host-array/host-array.controller.ts`:6 # INestApplicationContext **Kind:** Interface **Source:** [`packages/common/interfaces/nest-application-context.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-application-context.interface.ts#L29) **Part of:** [Common](subsystem-packages-common) Interface defining NestApplicationContext. `INestApplicationContext` defines the contract for a Nest standalone application context without an HTTP server. It provides dependency-injection access, lifecycle management, logging configuration, request-scoped provider resolution, and shutdown hook support. It is commonly returned by `NestFactory.createApplicationContext()` for CLI tools, workers, scripts, and background services. ## Diagram ```mermaid graph LR A[AppModule] --> B[NestFactory.createApplicationContext] B --> C[INestApplicationContext] C --> D[get / resolve providers] C --> E[select module context] C --> F[init / close lifecycle] C --> G[useLogger / flushLogs] C --> H[enableShutdownHooks] ``` ## Usage ```ts import { INestApplicationContext } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ReportService } from './report.service'; async function bootstrap() { const app: INestApplicationContext = await NestFactory.createApplicationContext(AppModule); app.enableShutdownHooks(); const reportService = app.get(ReportService); await reportService.generateDailyReport(); await app.close(); } void bootstrap(); ``` ## AI Coding Instructions - Use `NestFactory.createApplicationContext()` when building non-HTTP processes such as CLI commands, queues, cron workers, or migration scripts. - Retrieve singleton providers with `app.get()`; use `app.resolve()` when resolving request-scoped or transient providers. - Always call `await app.close()` when the process completes to release lifecycle resources and trigger shutdown hooks. - Register `enableShutdownHooks()` for long-running processes that should gracefully handle termination signals. - Do not use HTTP application methods such as `listen()` with `INestApplicationContext`; use `INestApplication` when an HTTP server is required. ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `ModuleDebugEntry` — `packages/core/repl/repl-context.ts`:22 - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 - `BaseWsInstance` — `packages/websockets/adapters/ws-adapter.ts`:8 # Catch **Kind:** Function **Source:** [`packages/common/decorators/core/catch.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/catch.decorator.ts#L21) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a Nest exception filter. An exception filter handles exceptions thrown by or not handled by your application code. The decorated class must implement the `ExceptionFilter` interface. `Catch()` marks a class as a Nest exception filter, allowing it to intercept exceptions thrown during request processing. The decorated class must implement Nest's `ExceptionFilter` interface and can optionally target one or more specific exception types. ## Signature ```ts function Catch(exceptions: Array | Abstract>): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `exceptions` | `Array | Abstract>` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[Request Handler] -->|throws exception| B[Nest Exception Layer] B --> C{Matching @Catch Filter?} C -->|Yes| D[Custom ExceptionFilter.catch] D --> E[Create HTTP Response] C -->|No| F[Default Nest Exception Handler] ``` ## Usage ```ts import { ArgumentsHost, Catch, ExceptionFilter, HttpException, } from '@nestjs/common'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost): void { const response = host.switchToHttp().getResponse(); const request = host.switchToHttp().getRequest(); response.status(exception.getStatus()).json({ statusCode: exception.getStatus(), path: request.url, message: exception.message, }); } } // Register globally: // app.useGlobalFilters(new HttpExceptionFilter()); ``` ## AI Coding Instructions - Decorate exception filter classes with `@Catch()`; pass exception constructors such as `HttpException` to handle only matching errors. - Always implement the `ExceptionFilter` interface and provide a `catch(exception, host)` method. - Use `ArgumentsHost` to select the active transport context, such as `host.switchToHttp()` for HTTP requests. - Register filters globally with `app.useGlobalFilters()`, at controller scope with `@UseFilters()`, or provide them through Nest dependency injection. - Avoid swallowing exceptions without sending or delegating an appropriate response for the active transport. ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `UnauthorizedFilter` — `integration/graphql-code-first/src/common/filters/unauthorized.filter.ts`:4 - `HttpExceptionFilter` — `integration/inspector/src/common/filters/http-exception.filter.ts`:8 - `RequestFilter` — `integration/websockets/src/request.filter.ts`:4 - `HttpExceptionFilter` — `sample/01-cats-app/src/common/filters/http-exception.filter.ts`:8 - `ExceptionFilter` — `sample/03-microservices/src/common/filters/rpc-exception.filter.ts`:5 - `HttpExceptionFilter` — `sample/36-hmr-esm/src/common/filters/http-exception.filter.ts`:8 # FactoryProvider **Kind:** Interface **Source:** [`packages/common/interfaces/modules/provider.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/provider.interface.ts#L116) **Part of:** [Common](subsystem-packages-common) Interface defining a *Factory* type provider. For example: ```typescript const connectionFactory = { provide: 'CONNECTION', useFactory: (optionsProvider: OptionsProvider) => { const options = optionsProvider.get(); return new DatabaseConnection(options); }, inject: [OptionsProvider], }; ``` `FactoryProvider` defines a dependency injection provider that creates a value by invoking a factory function. The factory can receive injected dependencies, return either a synchronous value or a `Promise`, and can be configured with lifecycle scope and durability options. ## Properties | Property | Type | |---|---| | `provide` | `InjectionToken` | | `useFactory` | `(...args: any[]) => T | Promise` | | `inject` | `Array` | | `scope` | `Scope` | | `durable` | `boolean` | ## Diagram ```mermaid graph LR Token[Injection Token] --> Provider[FactoryProvider] Dependencies[Injected Dependencies] --> Factory[useFactory] Provider --> Factory Factory --> Instance[Created Value or Promise] Instance --> Container[DI Container] Provider --> Scope[scope] Provider --> Durable[durable] ``` ## Usage ```typescript import { Scope } from '@nestjs/common'; import type { FactoryProvider } from '@nestjs/common'; class ConfigService { getDatabaseUrl(): string { return process.env.DATABASE_URL ?? 'postgres://localhost/app'; } } class DatabaseConnection { constructor(public readonly url: string) {} } const databaseConnectionProvider: FactoryProvider = { provide: 'DATABASE_CONNECTION', inject: [ConfigService], scope: Scope.DEFAULT, durable: true, useFactory: (configService: ConfigService) => { return new DatabaseConnection(configService.getDatabaseUrl()); }, }; ``` ## AI Coding Instructions - Use `provide` as the token consumers inject; prefer symbols or constants for shared tokens to avoid string collisions. - List factory parameters in the same order as their corresponding entries in `inject`. - Return a value directly for synchronous initialization, or return a `Promise` when setup requires asynchronous work. - Use `OptionalFactoryDependency` in `inject` when a factory dependency is not required, and handle an absent value safely. - Set `scope` and `durable` intentionally, since they affect provider lifecycle behavior and instance reuse. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `LOGGER_PROVIDER` — `integration/scopes/src/resolve-scoped/logger.provider.ts`:3 - `isClassProvider` — `packages/core/injector/helpers/provider-classifier.ts`:9 - `INSTANCE_METADATA_SYMBOL` — `packages/core/injector/instance-wrapper.ts`:22 - `InternalCoreModule` — `packages/core/injector/internal-core-module/internal-core-module.ts`:16 - `Module` — `packages/core/injector/module.ts`:44 - `DependenciesScanner` — `packages/core/scanner.ts`:75 - `superJSONProvider` — `sample/34-using-esm-packages/src/superjson.provider.ts`:7 # ParseFilePipeBuilder **Kind:** Class **Source:** [`packages/common/pipes/file/parse-file-pipe.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/parse-file-pipe.builder.ts#L16) **Part of:** [Common](subsystem-packages-common) `ParseFilePipeBuilder` provides a fluent API for configuring and creating a `ParseFilePipe` for uploaded-file validation. It collects file validators—such as maximum size and allowed file type—and builds a pipe that can be applied to `@UploadedFile()` parameters in NestJS controllers. ## Methods | Method | Signature | Returns | |---|---|---| | `addMaxSizeValidator` | `addMaxSizeValidator(options: MaxFileSizeValidatorOptions)` | `void` | | `addFileTypeValidator` | `addFileTypeValidator(options: FileTypeValidatorOptions)` | `void` | | `addValidator` | `addValidator(validator: FileValidator)` | `void` | | `build` | `build(additionalOptions: Omit)` | `ParseFilePipe` | ## Diagram ```mermaid graph LR A[ParseFilePipeBuilder] --> B[addMaxSizeValidator] A --> C[addFileTypeValidator] A --> D[addValidator] B --> E[Validator collection] C --> E D --> E E --> F[build] F --> G[ParseFilePipe] G --> H[@UploadedFile() validation] ``` ## Usage ```ts import { Controller, HttpStatus, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { ParseFilePipeBuilder } from '@nestjs/common'; @Controller('uploads') export class UploadController { private readonly imageUploadPipe = new ParseFilePipeBuilder() .addFileTypeValidator({ fileType: /(jpg|jpeg|png)$/, }) .addMaxSizeValidator({ maxSize: 5 * 1024 * 1024, // 5 MB }) .build({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY, }); @Post('image') @UseInterceptors(FileInterceptor('file')) uploadImage(@UploadedFile(this.imageUploadPipe) file: Express.Multer.File) { return { filename: file.filename, mimetype: file.mimetype, size: file.size, }; } } ``` ## AI Coding Instructions - Use the fluent builder chain to add validators before calling `build()`; `build()` returns the `ParseFilePipe` used by controller parameters. - Prefer `addMaxSizeValidator()` and `addFileTypeValidator()` for standard upload constraints; use `addValidator()` for custom `FileValidator` implementations. - Configure size limits in bytes and ensure file-type rules match the formats accepted by the upload endpoint. - Pass pipe-level options, such as `errorHttpStatusCode` or `fileIsRequired`, to `build()` rather than embedding them in individual validators. - Reuse a built pipe when multiple endpoints share the same validation policy, but create separate builders for endpoint-specific rules. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AppController` — `sample/29-file-upload/src/app.controller.ts`:15 # selectExceptionFilterMetadata **Kind:** Function **Source:** [`packages/common/utils/select-exception-filter-metadata.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/select-exception-filter-metadata.util.ts#L3) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function selectExceptionFilterMetadata(filters: ExceptionFilterMetadata[], exception: T): ExceptionFilterMetadata | undefined ``` ## Parameters | Name | Type | |---|---| | `filters` | `ExceptionFilterMetadata[]` | | `exception` | `T` | **Returns:** `ExceptionFilterMetadata | undefined` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ExceptionsHandler` — `packages/core/exceptions/exceptions-handler.ts`:9 - `ExternalExceptionsHandler` — `packages/core/exceptions/external-exceptions-handler.ts`:8 - `RpcExceptionsHandler` — `packages/microservices/exceptions/rpc-exceptions-handler.ts`:13 - `WsExceptionsHandler` — `packages/websockets/exceptions/ws-exceptions-handler.ts`:12 # assignCustomParameterMetadata **Kind:** Function **Source:** [`packages/common/utils/assign-custom-metadata.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/assign-custom-metadata.util.ts#L9) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function assignCustomParameterMetadata(args: Record, paramtype: number | string, index: number, factory: CustomParamFactory, data: ParamData, pipes: (Type | PipeTransform)[]) ``` ## Parameters | Name | Type | |---|---| | `args` | `Record` | | `paramtype` | `number | string` | | `index` | `number` | | `factory` | `CustomParamFactory` | | `data` | `ParamData` | | `pipes` | `(Type | PipeTransform)[]` | # LoggerService **Kind:** Interface **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L23) **Part of:** [Common](subsystem-packages-common) ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `route` — `packages/microservices/server/server.ts`:168 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `InstanceLoader` — `packages/core/injector/instance-loader.ts`:11 - `INSTANCE_METADATA_SYMBOL` — `packages/core/injector/instance-wrapper.ts`:22 - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # RouteParamtypes **Kind:** Enum **Source:** [`packages/common/enums/route-paramtypes.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/common/enums/route-paramtypes.enum.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Values - `REQUEST` - `RESPONSE` - `NEXT` - `BODY` - `QUERY` - `PARAM` - `HEADERS` - `SESSION` - `FILE` - `FILES` - `HOST` - `IP` - `RAW_BODY` - `ACK` ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `IRouteParamsFactory` — `packages/core/router/interfaces/route-params-factory.interface.ts`:3 - `RouteParamsFactory` — `packages/core/router/route-params-factory.ts`:4 - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `ParamsTokenFactory` — `packages/core/pipes/params-token-factory.ts`:4 - `PipesConsumer` — `packages/core/pipes/pipes-consumer.ts`:5 - `RpcParamtype` — `packages/microservices/enums/rpc-paramtype.enum.ts`:3 - `WsParamtype` — `packages/websockets/enums/ws-paramtype.enum.ts`:3 # FileTypeValidator **Kind:** Class **Source:** [`packages/common/pipes/file/file-type.validator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/file-type.validator.ts#L78) **Part of:** [Common](subsystem-packages-common) Defines the built-in FileTypeValidator. It validates incoming files by examining their magic numbers using the file-type package, providing more reliable file type validation than just checking the mimetype string. `FileTypeValidator` is a built-in file validation class used with NestJS file upload pipes. It inspects the uploaded file buffer for magic numbers via the `file-type` package, making validation more reliable than trusting the client-provided MIME type alone. **Extends:** `FileValidator` ## Methods | Method | Signature | Returns | |---|---|---| | `buildErrorMessage` | `buildErrorMessage(file: IFile)` | `string` | | `isValid` | `isValid(file: IFile)` | `Promise` | ## Where it refuses work - `FileTypeValidator` stops the work with an early return when `this.validationOptions.fallbackToMimetype`, in 4 places. - `FileTypeValidator` stops the work with an early return when `errorMessage`. - `FileTypeValidator` stops the work with an early return when `file?.mimetype && !file.buffer && !this.validationOptions?.fallbackToMimetype && !this.va…`. - `FileTypeValidator` stops the work with an early return when `!this.validationOptions`. - `FileTypeValidator` stops the work with an early return when `this.validationOptions.skipMagicNumbersValidation`. - `FileTypeValidator` stops the work with an early return when `!isFileValid`. ## When something fails - `FileTypeValidator` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR A[Uploaded file] --> B[ParseFilePipe] B --> C[FileTypeValidator] C --> D[Inspect file buffer magic numbers] D --> E[file-type detects MIME type] E --> F{Matches configured fileType?} F -->|Yes| G[Accept file] F -->|No| H[Return validation error] ``` ## Usage ```ts import { Controller, HttpStatus, ParseFilePipe, Post, UploadedFile, UseInterceptors, FileTypeValidator, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post('image') @UseInterceptors(FileInterceptor('file')) uploadImage( @UploadedFile( new ParseFilePipe({ validators: [ new FileTypeValidator({ fileType: /image\/(jpeg|png)/, }), ], errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY, }), ) file: Express.Multer.File, ) { return { filename: file.originalname, detectedType: file.mimetype, }; } } ``` ## AI Coding Instructions - Use `FileTypeValidator` inside `ParseFilePipe` validator lists for uploaded files handled by Multer interceptors. - Configure `fileType` with either an exact MIME type string, such as `image/jpeg`, or a regular expression for multiple allowed types. - Do not rely only on `file.mimetype`; this validator checks the file buffer contents and is intended to prevent spoofed MIME types. - Ensure the upload adapter provides a `buffer` on the uploaded file, since magic-number detection requires access to file contents. - Combine this validator with `MaxFileSizeValidator` when endpoints need both type and size restrictions. # VersioningOptions **Kind:** Type **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L104) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts VersioningCommonOptions & ( | HeaderVersioningOptions | UriVersioningOptions | MediaTypeVersioningOptions | CustomVersioningOptions ) ``` ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `RoutePathMetadata` — `packages/core/router/interfaces/route-path-metadata.interface.ts`:4 - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `RouteInfoPathExtractor` — `packages/core/middleware/route-info-path-extractor.ts`:16 - `AbstractHttpAdapter` — `packages/core/adapters/http-adapter.ts`:8 - `ApplicationConfig` — `packages/core/application-config.ts`:13 - `NestApplication` — `packages/core/nest-application.ts`:54 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # INestMicroservice **Kind:** Interface **Source:** [`packages/common/interfaces/nest-microservice.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-microservice.interface.ts#L14) **Part of:** [Common](subsystem-packages-common) Interface describing Microservice Context. `INestMicroservice` describes the runtime context of a NestJS microservice application. It exposes lifecycle state through an RxJS observable, allowing integrations to react to status changes such as startup, readiness, or shutdown. ## Properties | Property | Type | |---|---| | `status` | `Observable` | ## Diagram ```mermaid graph LR A[Microservice Bootstrap] --> B[INestMicroservice] B --> C[status: Observable] C --> D[Lifecycle State Subscribers] D --> E[Monitoring / Shutdown / Integration Logic] ``` ## Usage ```ts import { INestMicroservice } from '@nestjs/common'; async function monitorMicroservice(app: INestMicroservice) { app.status.subscribe((status) => { console.log(`Microservice status: ${status}`); }); await app.listen(); } ``` ## AI Coding Instructions - Treat `status` as an RxJS `Observable`; subscribe to it rather than reading it as a synchronous string value. - Clean up long-lived subscriptions when adding custom lifecycle monitoring to avoid memory leaks. - Use the interface when accepting a microservice application context in reusable helpers or integration code. - Keep lifecycle-dependent logic resilient to multiple status emissions, including startup and shutdown transitions. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `NestApplication` — `packages/core/nest-application.ts`:54 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingModule` — `packages/testing/testing-module.ts`:26 # mixin **Kind:** Function **Source:** [`packages/common/decorators/core/injectable.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/injectable.decorator.ts#L53) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function mixin(mixinClass: Type) ``` ## Parameters | Name | Type | |---|---| | `mixinClass` | `Type` | ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `AnyFilesInterceptor` — `packages/platform-express/multer/interceptors/any-files.interceptor.ts`:24 - `FileFieldsInterceptor` — `packages/platform-express/multer/interceptors/file-fields.interceptor.ts`:27 - `FileInterceptor` — `packages/platform-express/multer/interceptors/file.interceptor.ts`:25 - `FilesInterceptor` — `packages/platform-express/multer/interceptors/files.interceptor.ts`:27 - `NoFilesInterceptor` — `packages/platform-express/multer/interceptors/no-files.interceptor.ts`:24 # NestApplicationOptions **Kind:** Interface **Source:** [`packages/common/interfaces/nest-application-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-application-options.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) `NestApplicationOptions` configures runtime behavior when creating a Nest application instance. It controls HTTP concerns such as CORS, request body parsing, HTTPS server options, raw body access, and connection shutdown behavior. ## Properties | Property | Type | |---|---| | `cors` | `boolean | CorsOptions | CorsOptionsDelegate` | | `bodyParser` | `boolean` | | `httpsOptions` | `HttpsOptions` | | `rawBody` | `boolean` | | `forceCloseConnections` | `boolean` | ## Diagram ```mermaid graph LR A[NestFactory.create] --> B[NestApplicationOptions] B --> C[CORS Configuration] B --> D[Body Parser] B --> E[HTTPS Options] B --> F[Raw Body Access] B --> G[Connection Shutdown] C --> H[Nest Application] D --> H E --> H F --> H G --> H ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import type { NestApplicationOptions } from '@nestjs/common'; import { AppModule } from './app.module'; async function bootstrap() { const options: NestApplicationOptions = { cors: { origin: ['https://example.com'], credentials: true, }, bodyParser: true, rawBody: true, forceCloseConnections: true, httpsOptions: { key: process.env.HTTPS_KEY, cert: process.env.HTTPS_CERT, }, }; const app = await NestFactory.create(AppModule, options); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Pass `NestApplicationOptions` as the second argument to `NestFactory.create()` when configuring an HTTP-based Nest application. - Use `cors: true` for default CORS behavior, or provide `CorsOptions`/a delegate when origins and credentials require explicit control. - Enable `rawBody` only when integrations need the unparsed payload, such as webhook signature verification. - Keep `bodyParser` enabled unless registering custom parsing middleware or handling request streams manually. - Supply valid Node.js HTTPS server options through `httpsOptions`, and consider `forceCloseConnections` for reliable shutdown in long-lived connection environments. ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `AbstractHttpAdapter` — `packages/core/adapters/http-adapter.ts`:8 - `NestApplication` — `packages/core/nest-application.ts`:54 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `TestingModule` — `packages/testing/testing-module.ts`:26 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # ParseIntPipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-int.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-int.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `UsersController` — `sample/05-sql-typeorm/src/users/users.controller.ts`:14 - `CatsResolver` — `sample/12-graphql-schema-first/src/cats/cats.resolver.ts`:11 - `PostsResolver` — `sample/31-graphql-federation-code-first/posts-application/src/posts/posts.resolver.ts`:14 - `CatsResolvers` — `integration/graphql-schema-first/src/cats/cats.resolvers.ts`:10 # Sse **Kind:** Function **Source:** [`packages/common/decorators/http/sse.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/sse.decorator.ts#L9) **Part of:** [Common](subsystem-packages-common) Declares this route as a Server-Sent-Events endpoint `Sse()` declares a controller route as a Server-Sent Events (SSE) endpoint. It configures the route to handle `GET` requests and marks it for streaming event data to connected clients, typically through an RxJS `Observable`. ## Signature ```ts function Sse(path: string, options: { [METHOD_METADATA]?: RequestMethod }): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | | `options` | `{ [METHOD_METADATA]?: RequestMethod }` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[Browser or SSE Client] -->|GET /events| Controller[Controller Method] Controller -->|@Sse()| Nest[NestJS SSE Handler] Nest -->|Observable stream| Client ``` ## Usage ```ts import { Controller, MessageEvent, Sse } from '@nestjs/common'; import { interval, map, Observable } from 'rxjs'; @Controller('notifications') export class NotificationsController { @Sse('stream') streamNotifications(): Observable { return interval(1000).pipe( map((count) => ({ data: { message: `Notification ${count}`, timestamp: new Date().toISOString(), }, })), ); } } ``` ```ts const events = new EventSource('/notifications/stream'); events.onmessage = (event) => { console.log(JSON.parse(event.data)); }; ``` ## AI Coding Instructions - Use `@Sse()` only on controller methods that return an RxJS `Observable` stream of SSE-compatible event objects. - Return event payloads using the `MessageEvent` shape, typically `{ data: ... }`, and optionally include `id`, `type`, or `retry`. - Keep SSE streams long-lived; ensure subscriptions are cleaned up when clients disconnect or when the application shuts down. - Use a normal `@Get()` endpoint for request-response APIs; SSE is intended for one-way server-to-client updates. - Ensure clients connect with `EventSource` or another client that supports the `text/event-stream` protocol. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `PassthroughInterceptor` — `integration/nest-application/sse/src/app.controller.ts`:28 - `AppController` — `sample/28-sse/src/app.controller.ts`:8 # validateEach **Kind:** Function **Source:** [`packages/common/utils/validate-each.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/validate-each.util.ts#L16) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function validateEach(context: { name: string }, arr: any[], predicate: Function, decorator: string, item: string): boolean ``` ## Parameters | Name | Type | |---|---| | `context` | `{ name: string }` | | `arr` | `any[]` | | `predicate` | `Function` | | `decorator` | `string` | | `item` | `string` | **Returns:** `boolean` # Version **Kind:** Function **Source:** [`packages/common/decorators/core/version.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/version.decorator.ts#L9) **Part of:** [Common](subsystem-packages-common) Sets the version of the endpoint to the passed version `Version()` sets version metadata on an individual endpoint, allowing the routing layer to match requests against a specific API version. Use it with application-level versioning configuration to support multiple versions of the same route without duplicating an entire controller. ## Signature ```ts function Version(version: VersionValue): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `version` | `VersionValue` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR A[Client Request
/v1/users] --> B[Versioning Strategy] B --> C[Controller Route] C --> D["@Version('1') metadata"] D --> E[Matching Endpoint Handler] ``` ## Usage ```ts import { Controller, Get, Version } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() @Version('1') findAllV1() { return { version: '1', users: [] }; } @Get() @Version('2') findAllV2() { return { version: '2', users: [] }; } } ``` ## AI Coding Instructions - Apply `@Version()` to route handler methods when only specific endpoints need a different API version. - Ensure versioning is enabled during application bootstrap, such as with `app.enableVersioning(...)`. - Use version values consistently across controllers, routes, and client-facing API documentation. - Avoid defining conflicting handlers with the same HTTP method, route path, and version value. - Prefer controller-level versioning when every endpoint in a controller belongs to the same API version. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `AppV2Controller` — `integration/inspector/src/app-v2.controller.ts`:3 - `MiddlewareController` — `integration/versioning/src/middleware.controller.ts`:3 - `OverridePartialController` — `integration/versioning/src/override-partial.controller.ts`:3 - `OverrideController` — `integration/versioning/src/override.controller.ts`:3 # ForwardReference **Kind:** Interface **Source:** [`packages/common/interfaces/modules/forward-reference.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/forward-reference.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) `ForwardReference` is a lightweight wrapper interface used to defer access to a value until it is needed. It is typically used to resolve circular dependencies between modules, providers, or other components that cannot be referenced directly during initial declaration. ## Properties | Property | Type | |---|---| | `forwardRef` | `T` | ## Diagram ```mermaid graph LR A[Module or Provider A] --> B[ForwardReference] B --> C[forwardRef: T] C --> D[Deferred Module or Provider B] D -. circular dependency .-> A ``` ## Usage ```ts import type { ForwardReference } from './forward-reference.interface'; interface UserModule { name: string; } const userModuleReference: ForwardReference = { forwardRef: { name: 'UserModule', }, }; // Resolve the deferred reference when needed. const userModule = userModuleReference.forwardRef; console.log(userModule.name); // "UserModule" ``` ## AI Coding Instructions - Use `ForwardReference` when a dependency must be declared before its final value can be resolved, especially for circular module relationships. - Keep the generic type `T` specific so consumers receive accurate type inference for `forwardRef`. - Access the wrapped dependency through the `forwardRef` field rather than treating the wrapper itself as the referenced value. - Do not add unrelated metadata to this interface; it should remain a minimal, typed reference wrapper. - Ensure code that consumes a forward reference resolves `.forwardRef` at the appropriate integration boundary. ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `ClientsModule` — `packages/microservices/module/clients.module.ts`:17 - `ModuleFactory` — `packages/core/injector/compiler.ts`:8 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `ByReferenceModuleOpaqueKeyFactory` — `packages/core/injector/opaque-key-factory/by-reference-module-opaque-key-factory.ts`:10 - `ModuleOpaqueKeyFactory` — `packages/core/injector/opaque-key-factory/interfaces/module-opaque-key-factory.interface.ts`:5 - `ModuleDefinition` — `packages/core/interfaces/module-definition.interface.ts`:4 - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # ContextType **Kind:** Type **Source:** [`packages/common/interfaces/features/arguments-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/arguments-host.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'http' | 'ws' | 'rpc' ``` ## Used by 9 references from 9 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (9) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `GuardsConsumer` — `packages/core/guards/guards-consumer.ts`:7 - `ParamProperties` — `packages/core/helpers/context-utils.ts`:15 - `ExecutionContextHost` — `packages/core/helpers/execution-context-host.ts`:10 - `ParamsFactory` — `packages/core/helpers/external-context-creator.ts`:28 - `ExternalErrorProxy` — `packages/core/helpers/external-proxy.ts`:5 - `InterceptorsConsumer` — `packages/core/interceptors/interceptors-consumer.ts`:13 - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 …and 1 more. # createParamDecorator **Kind:** Function **Source:** [`packages/common/decorators/http/create-route-param-metadata.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/create-route-param-metadata.decorator.ts#L19) **Part of:** [Common](subsystem-packages-common) Defines HTTP route param decorator `createParamDecorator` creates custom parameter decorators for HTTP route handlers. It stores parameter metadata and invokes a factory callback at request time, allowing handlers to receive values derived from the request, response, or execution context. ## Signature ```ts function createParamDecorator(factory: CustomParamFactory, enhancers: ParamDecoratorEnhancer[]): ( ...dataOrPipes: (Type | PipeTransform | FactoryData)[] ) => ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `factory` | `CustomParamFactory` | | `enhancers` | `ParamDecoratorEnhancer[]` | **Returns:** `( ...dataOrPipes: (Type | PipeTransform | FactoryData)[] ) => ParameterDecorator` ## Diagram ```mermaid graph LR A[HTTP Request] --> B[Route Handler] B --> C[Custom Parameter Decorator] C --> D[Factory Callback] D --> E[ExecutionContext] E --> F[Extracted Parameter Value] F --> G[Handler Method Argument] ``` ## Usage ```ts import { createParamDecorator, ExecutionContext } from '@nestjs/common'; export const CurrentUser = createParamDecorator( (property: string | undefined, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); const user = request.user; return property ? user?.[property] : user; }, ); // Usage in a controller @Get('profile') getProfile( @CurrentUser() user: User, @CurrentUser('id') userId: string, ) { return { user, userId }; } ``` ## AI Coding Instructions - Use the factory callback to extract values from `ExecutionContext`, typically through `ctx.switchToHttp().getRequest()`. - Treat the optional `data` argument as decorator configuration, such as a property name or lookup key. - Keep decorators focused on extracting request-scoped values; place business logic in guards, services, or controllers. - Ensure extracted values handle missing request properties safely, especially for optional authentication data. - Use the resulting decorator on controller method parameters and combine it with pipes when validation or transformation is needed. # EnhancerSubtype **Kind:** Type **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L33) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts (typeof ENHANCER_KEY_TO_SUBTYPE_MAP)[keyof typeof ENHANCER_KEY_TO_SUBTYPE_MAP] ``` ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `MESSAGES` — `packages/core/constants.ts`:3 - `NestContainer` — `packages/core/injector/container.ts`:31 - `INSTANCE_METADATA_SYMBOL` — `packages/core/injector/instance-wrapper.ts`:22 - `Module` — `packages/core/injector/module.ts`:44 - `EnhancerMetadataCacheEntry` — `packages/core/inspector/interfaces/enhancer-metadata-cache-entry.interface.ts`:5 - `AttachedEnhancerDefinition` — `packages/core/inspector/interfaces/extras.interface.ts`:6 - `ModuleNode` — `packages/core/inspector/interfaces/node.interface.ts`:4 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # NotFoundException **Kind:** Class **Source:** [`packages/common/exceptions/not-found.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/not-found.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Not Found* type errors. `NotFoundException` represents an HTTP 404 error when a requested resource cannot be found. It extends the application's HTTP exception system, providing a consistent way for controllers and services to signal missing entities to the framework's exception handling layer. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Controller or Service] -->|throws| B[NotFoundException] B --> C[HTTP Exception Handler] C --> D[HTTP 404 Not Found Response] D --> E[Client] ``` ## Usage ```ts import { NotFoundException } from '@nestjs/common'; async function findUserById(id: string) { const user = await usersRepository.findById(id); if (!user) { throw new NotFoundException(`User with ID "${id}" was not found`); } return user; } ``` ## AI Coding Instructions - Throw `NotFoundException` when a requested resource does not exist or cannot be resolved by its identifier. - Include a clear, safe error message that identifies the missing resource without exposing sensitive implementation details. - Use this exception instead of manually constructing `{ statusCode: 404 }` response objects; the framework exception filter formats the HTTP response. - Do not use `NotFoundException` for validation failures, authorization issues, or unexpected persistence errors; use the appropriate exception type instead. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `RecipesResolver` — `integration/graphql-code-first/src/recipes/recipes.resolver.ts`:13 - `RecipesResolver` — `sample/23-graphql-code-first/src/recipes/recipes.resolver.ts`:11 - `RecipesResolver` — `sample/33-graphql-mercurius/src/recipes/recipes.resolver.ts`:16 # UnauthorizedException **Kind:** Class **Source:** [`packages/common/exceptions/unauthorized.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/unauthorized.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Unauthorized* type errors. `UnauthorizedException` represents an HTTP 401 error, indicating that a request cannot be authenticated or lacks valid credentials. It extends the framework's HTTP exception model so authentication guards, controllers, and global exception filters can return a consistent unauthorized response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client Request] --> Guard[Authentication Guard] Guard -->|Missing or invalid credentials| Exception[UnauthorizedException] Exception --> Filter[HTTP Exception Filter] Filter --> Response[HTTP 401 Unauthorized Response] ``` ## Usage ```ts import { UnauthorizedException } from '@nestjs/common'; function validateAccessToken(token?: string) { if (!token || token !== process.env.API_ACCESS_TOKEN) { throw new UnauthorizedException('Invalid or missing access token'); } return { authenticated: true }; } ``` ## AI Coding Instructions - Throw `UnauthorizedException` when authentication fails, credentials are missing, or a token is invalid or expired. - Use `ForbiddenException` instead when the user is authenticated but does not have permission for the requested resource. - Provide a safe, client-facing error message; never include tokens, passwords, or internal authentication details. - Prefer throwing this exception from authentication guards or validation services so controllers remain focused on request handling. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `AuthGuard` — `integration/graphql-code-first/src/common/guards/auth.guard.ts`:9 - `AuthGuard` — `sample/19-auth-jwt/src/auth/auth.guard.ts`:13 - `AuthService` — `sample/19-auth-jwt/src/auth/auth.service.ts`:5 - `UnauthorizedFilter` — `integration/graphql-code-first/src/common/filters/unauthorized.filter.ts`:4 # MaxFileSizeValidator **Kind:** Class **Source:** [`packages/common/pipes/file/max-file-size.validator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/max-file-size.validator.ts#L47) **Part of:** [Common](subsystem-packages-common) Defines the built-in MaxSize File Validator `MaxFileSizeValidator` is a built-in file validator that checks whether an uploaded file is smaller than a configured maximum size. It is typically used with NestJS `ParseFilePipe` to reject oversized uploads before they reach application logic. **Extends:** `FileValidator` ## Methods | Method | Signature | Returns | |---|---|---| | `buildErrorMessage` | `buildErrorMessage(file: IFile)` | `string` | | `isValid` | `isValid(file: IFile)` | `boolean` | ## Where it refuses work - `MaxFileSizeValidator` stops the work with an early return when `errorMessage`. - `MaxFileSizeValidator` stops the work with an early return when `message`. - `MaxFileSizeValidator` stops the work with an early return when `file?.size`. - `MaxFileSizeValidator` stops the work with an early return when `!this.validationOptions || !file`. ## Diagram ```mermaid graph LR A[Incoming uploaded file] --> B[ParseFilePipe] B --> C[MaxFileSizeValidator] C --> D{file.size < maxSize?} D -->|Yes| E[Continue request handling] D -->|No| F[buildErrorMessage()] F --> G[Return validation error] ``` ## Usage ```ts import { Controller, MaxFileSizeValidator, ParseFilePipe, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) uploadFile( @UploadedFile( new ParseFilePipe({ validators: [ new MaxFileSizeValidator({ maxSize: 5 * 1024 * 1024, // 5 MB }), ], }), ) file: Express.Multer.File, ) { return { filename: file.originalname, size: file.size, }; } } ``` ## AI Coding Instructions - Instantiate `MaxFileSizeValidator` with a `maxSize` value in bytes; use clear constants for readable size limits. - Add the validator to `ParseFilePipe` alongside other validators such as `FileTypeValidator`. - Ensure the upload interceptor, such as `FileInterceptor`, runs before attempting to validate the uploaded file. - Do not rely on client-provided file metadata alone; configure upload limits and storage settings as additional protection. - Use `buildErrorMessage()` behavior consistently when extending or composing file-validation error handling. # ModuleMetadata **Kind:** Interface **Source:** [`packages/common/interfaces/modules/module-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/module-metadata.interface.ts#L14) **Part of:** [Common](subsystem-packages-common) Interface defining the property object that describes the module. `ModuleMetadata` defines the configuration object used to describe an application module. It declares the modules to import, controllers to register, providers to create or inject, and tokens or providers to expose to other modules. ## Properties | Property | Type | |---|---| | `imports` | `Array< Type | DynamicModule | Promise | ForwardReference >` | | `controllers` | `Type[]` | | `providers` | `Provider[]` | | `exports` | `Array< | DynamicModule | string | symbol | Provider | ForwardReference | Abstract | Function >` | ## Diagram ```mermaid graph LR M[ModuleMetadata] --> I[imports] M --> C[controllers] M --> P[providers] M --> E[exports] I --> IM[Static Modules] I --> DM[Dynamic Modules] I --> FR[Forward References] C --> CT[Controller Types] P --> PR[Providers and Injection Tokens] E --> EX[Exported Providers or Modules] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import type { ModuleMetadata } from '@nestjs/common'; import { UsersController } from './users.controller'; import { UsersService } from './users.service'; import { DatabaseModule } from '../database/database.module'; const usersModuleMetadata: ModuleMetadata = { imports: [DatabaseModule], controllers: [UsersController], providers: [UsersService], exports: [UsersService], }; @Module(usersModuleMetadata) export class UsersModule {} ``` ## AI Coding Instructions - Use `imports` for modules whose exported providers must be available within the current module. - Register injectable services, factories, values, and custom tokens in `providers`; register request handlers in `controllers`. - Add a provider to `exports` only when consuming modules need to inject it. - Use `forwardRef(() => SomeModule)` when resolving circular module dependencies rather than importing the module directly. - Preserve provider token consistency: exported tokens must correspond to providers declared locally or imported from another module. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ClientProvider` — `packages/microservices/module/interfaces/clients-module.interface.ts`:4 - `MulterModuleOptions` — `packages/platform-express/multer/interfaces/files-upload-module.interface.ts`:4 - `Test` — `packages/testing/test.ts`:8 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # InternalServerErrorException **Kind:** Class **Source:** [`packages/common/exceptions/internal-server-error.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/internal-server-error.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Internal Server Error* type errors. `InternalServerErrorException` represents an HTTP 500 error for unexpected server-side failures. It extends NestJS's HTTP exception system, producing a standardized error response that can be handled by Nest's built-in exception filters. Use it when a request cannot be completed because of an internal application or infrastructure error. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Controller or Service] --> B[Unexpected server-side failure] B --> C[InternalServerErrorException] C --> D[HttpException base class] D --> E[HTTP 500 Internal Server Error response] ``` ## Usage ```ts import { InternalServerErrorException } from '@nestjs/common'; async function createReport(): Promise<{ id: string }> { try { // Perform an operation that may fail unexpectedly. return await reportService.generate(); } catch (error) { throw new InternalServerErrorException( 'Unable to generate the report. Please try again later.', ); } } ``` ## AI Coding Instructions - Throw `InternalServerErrorException` only for unexpected server-side failures that should produce an HTTP `500` response. - Prefer more specific exceptions, such as `BadRequestException` or `NotFoundException`, when the failure is caused by invalid client input or missing resources. - Do not expose sensitive implementation details, stack traces, credentials, or raw database errors in the exception message. - Allow NestJS exception filters to serialize this exception into the standard HTTP error response format. - Preserve the original error in logs or observability tooling before throwing a sanitized exception response. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `DisconnectedClientController` — `integration/microservices/src/disconnected.controller.ts`:12 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 # isSymbol **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L51) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isSymbol(val: any): val is symbol ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is symbol` ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `UNKNOWN_DEPENDENCIES_MESSAGE` — `packages/core/errors/messages.ts`:63 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `Module` — `packages/core/injector/module.ts`:44 - `DeepHashedModuleOpaqueKeyFactory` — `packages/core/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.ts`:13 - `EventPattern` — `packages/microservices/decorators/event-pattern.decorator.ts`:21 - `GrpcMethodStreamingType` — `packages/microservices/decorators/message-pattern.decorator.ts`:22 # OnModuleInit **Kind:** Interface **Source:** [`packages/common/interfaces/hooks/on-init.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/hooks/on-init.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) Interface defining method called once the host module has been initialized. `OnModuleInit` is a lifecycle hook interface for providers, controllers, and modules that need to run initialization logic after their host module has been fully initialized. Implement the `onModuleInit()` method to perform setup work such as validating configuration, establishing connections, or preparing in-memory resources before the application begins handling requests. ## Diagram ```mermaid graph LR A[Application bootstraps] --> B[Host module initializes] B --> C[Provider/Controller implements OnModuleInit] C --> D[onModuleInit() executes] D --> E[Initialization resources ready] ``` ## Usage ```ts import { Injectable, OnModuleInit } from '@nestjs/common'; @Injectable() export class CacheService implements OnModuleInit { private connected = false; async onModuleInit(): Promise { await this.connect(); this.connected = true; } private async connect(): Promise { // Initialize a cache client or preload required data. } } ``` ## AI Coding Instructions - Implement `OnModuleInit` on providers, controllers, or modules that require setup after their containing module has initialized. - Define an `onModuleInit()` method; it may return `void` or `Promise` for asynchronous initialization. - Keep initialization logic focused and fail fast when required configuration or dependencies are unavailable. - Do not use this hook for request-specific work; use it only for one-time module lifecycle setup. - Ensure dependencies used during initialization are declared through NestJS dependency injection. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 - `HeroController` — `sample/04-grpc/src/hero/hero.controller.ts`:17 - `PrismaService` — `sample/22-graphql-prisma/src/prisma/prisma.service.ts`:9 - `AppModule` — `sample/34-using-esm-packages/src/app.module.ts`:7 - `DatabaseConnection` — `integration/repl/src/database/database.connection.ts`:3 - `callModuleInitHook` — `packages/core/hooks/on-module-init.hook.ts`:37 # VersioningType **Kind:** Enum **Source:** [`packages/common/enums/version-type.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/common/enums/version-type.enum.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Values - `URI` - `HEADER` - `MEDIA_TYPE` - `CUSTOM` ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `RouteInfoPathExtractor` — `packages/core/middleware/route-info-path-extractor.ts`:16 - `NestApplication` — `packages/core/nest-application.ts`:54 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # extendArrayMetadata **Kind:** Function **Source:** [`packages/common/utils/extend-metadata.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/extend-metadata.util.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function extendArrayMetadata(key: string, metadata: T, target: Function) ``` ## Parameters | Name | Type | |---|---| | `key` | `string` | | `metadata` | `T` | | `target` | `Function` | # FileValidator **Kind:** Class **Source:** [`packages/common/pipes/file/file-validator.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/file-validator.interface.ts#L9) **Part of:** [Common](subsystem-packages-common) Interface describing FileValidators, which can be added to a ParseFilePipe `FileValidator` defines the contract for validators used by `ParseFilePipe` to inspect uploaded files. Implementations provide validation logic through `isValid()` and return a user-facing failure message through `buildErrorMessage()` when validation fails. ## Methods | Method | Signature | Returns | |---|---|---| | `isValid` | `isValid(file: TFile | TFile[] | Record)` | `boolean | Promise` | | `buildErrorMessage` | `buildErrorMessage(file: any)` | `string` | ## Diagram ```mermaid graph LR A[Uploaded file] --> B[ParseFilePipe] B --> C[FileValidator.isValid] C -->|Valid| D[Controller handler] C -->|Invalid| E[FileValidator.buildErrorMessage] E --> F[Validation error response] ``` ## Usage ```ts import { FileValidator, ParseFilePipe, UploadedFile, UseInterceptors, FileInterceptor, Controller, Post, } from '@nestjs/common'; class AllowedMimeTypeValidator implements FileValidator { isValid(file?: Express.Multer.File): boolean { return file?.mimetype === 'image/png'; } buildErrorMessage(): string { return 'Only PNG image uploads are allowed.'; } } @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) upload( @UploadedFile( new ParseFilePipe({ validators: [new AllowedMimeTypeValidator()], }), ) file: Express.Multer.File, ) { return { filename: file.originalname, mimetype: file.mimetype, }; } } ``` ## AI Coding Instructions - Implement both `isValid()` and `buildErrorMessage()` for every custom `FileValidator`. - Keep `isValid()` focused on validation and return either a boolean or `Promise` for asynchronous checks. - Return clear, client-safe messages from `buildErrorMessage()`; avoid exposing internal storage or security details. - Register validator instances in `ParseFilePipe` through its `validators` option. - Account for missing files in validators when the upload field may be optional. # getInjectionProviders **Kind:** Function **Source:** [`packages/common/module-utils/utils/get-injection-providers.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/utils/get-injection-providers.util.ts#L32) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function getInjectionProviders(providers: Provider[], tokens: FactoryProvider['inject']): Provider[] ``` ## Parameters | Name | Type | |---|---| | `providers` | `Provider[]` | | `tokens` | `FactoryProvider['inject']` | **Returns:** `Provider[]` # isLogLevelEnabled **Kind:** Function **Source:** [`packages/common/services/utils/is-log-level-enabled.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/utils/is-log-level-enabled.util.ts#L17) **Part of:** [Common](subsystem-packages-common) Checks if target level is enabled. `isLogLevelEnabled` determines whether a target log level should be emitted based on the configured logger levels. It supports direct level matches and level-threshold behavior, allowing logging components to consistently filter messages before they are written. ## Signature ```ts function isLogLevelEnabled(targetLevel: LogLevel, logLevels: LogLevel[] | undefined): boolean ``` ## Parameters | Name | Type | |---|---| | `targetLevel` | `LogLevel` | | `logLevels` | `LogLevel[] | undefined` | **Returns:** `boolean` ## Diagram ```mermaid graph LR A[Target log level] --> C[isLogLevelEnabled] B[Configured log levels] --> C C --> D{Configuration exists?} D -- No --> E[Return false] D -- Yes --> F{Level explicitly enabled or allowed by threshold?} F -- Yes --> G[Return true] F -- No --> H[Return false] ``` ## Usage ```ts import { isLogLevelEnabled } from '@nestjs/common/services/utils/is-log-level-enabled.util'; const enabledLevels = ['debug']; if (isLogLevelEnabled('log', enabledLevels)) { console.log('Application started'); } if (isLogLevelEnabled('verbose', enabledLevels)) { console.log('Detailed diagnostic output'); } ``` ## AI Coding Instructions - Pass the requested log level as the first argument and the configured `LogLevel[]` collection as the second argument. - Treat an empty or undefined configured level list as logging disabled; do not assume a default level is enabled. - Reuse this utility before formatting or writing log messages to avoid unnecessary logging work. - Preserve the established log-level ordering when changing supported levels, since threshold evaluation depends on that order. # normalizePath **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L33) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function normalizePath(path: string): string ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `ROUTES` — `packages/core/router/router-module.ts`:9 - `flattenRoutePaths` — `packages/core/router/utils/flatten-route-paths.util.ts`:5 - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 # randomStringGenerator **Kind:** Function **Source:** [`packages/common/utils/random-string-generator.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/random-string-generator.util.ts#L3) **Part of:** [Common](subsystem-packages-common) ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `MulterModule` — `packages/platform-express/multer/multer.module.ts`:14 - `INSTANCE_METADATA_SYMBOL` — `packages/core/injector/instance-wrapper.ts`:22 - `Module` — `packages/core/injector/module.ts`:44 - `ByReferenceModuleOpaqueKeyFactory` — `packages/core/injector/opaque-key-factory/by-reference-module-opaque-key-factory.ts`:10 - `DeepHashedModuleOpaqueKeyFactory` — `packages/core/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.ts`:13 - `UuidFactoryMode` — `packages/core/inspector/uuid-factory.ts`:4 - `ClientProxy` — `packages/microservices/client/client-proxy.ts`:38 - `ClientRMQ` — `packages/microservices/client/client-rmq.ts`:57 # ValueProvider **Kind:** Interface **Source:** [`packages/common/interfaces/modules/provider.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/provider.interface.ts#L79) **Part of:** [Common](subsystem-packages-common) Interface defining a *Value* type provider. For example: ```typescript const connectionProvider = { provide: 'CONNECTION', useValue: connection, }; ``` `ValueProvider` defines a dependency injection provider that registers an existing value under an `InjectionToken`. Use it when a dependency is already created—such as a configuration object, database connection, or third-party client—and should be shared through the container without factory logic. ## Properties | Property | Type | |---|---| | `provide` | `InjectionToken` | | `useValue` | `T` | | `inject` | `never` | ## Diagram ```mermaid graph LR A[Existing value] --> B[ValueProvider] B -->|provide: InjectionToken| C[Dependency Injection Container] C -->|resolve token| D[Consumer] B -->|useValue: T| A ``` ## Usage ```typescript import type { ValueProvider } from '@nestjs/common'; const connection = createDatabaseConnection(); const connectionProvider: ValueProvider = { provide: 'CONNECTION', useValue: connection, }; // Consumers can inject the registered value using the same token. class UserRepository { constructor( @Inject('CONNECTION') private readonly connection: DatabaseConnection, ) {} } ``` ## AI Coding Instructions - Use `useValue` for pre-existing objects, constants, configuration, mocks, or initialized third-party clients. - Ensure the `provide` token exactly matches the token used by consuming classes or factories. - Do not add `inject` dependencies to a value provider; `useValue` is supplied directly and `inject` is `never`. - Prefer symbols or exported token constants over repeated string literals for shared application dependencies. - Use `ValueProvider` in tests to replace real dependencies with deterministic mock objects. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `isClassProvider` — `packages/core/injector/helpers/provider-classifier.ts`:9 - `InternalCoreModule` — `packages/core/injector/internal-core-module/internal-core-module.ts`:16 - `Module` — `packages/core/injector/module.ts`:44 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # ClassProvider **Kind:** Interface **Source:** [`packages/common/interfaces/modules/provider.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/provider.interface.ts#L36) **Part of:** [Common](subsystem-packages-common) Interface defining a *Class* type provider. For example: ```typescript const configServiceProvider = { provide: ConfigService, useClass: process.env.NODE_ENV === 'development' ? DevelopmentConfigService : ProductionConfigService, }; ``` `ClassProvider` defines a dependency injection provider that creates a token’s value by instantiating a class. It maps an `InjectionToken` to a concrete implementation type and can optionally configure the provider scope and durability behavior. ## Properties | Property | Type | |---|---| | `provide` | `InjectionToken` | | `useClass` | `Type` | | `scope` | `Scope` | | `inject` | `never` | | `durable` | `boolean` | ## Diagram ```mermaid graph LR A[InjectionToken
provide] --> B[ClassProvider] B --> C[Implementation Class
useClass] C --> D[DI Container] D --> E[Injected Consumer] B --> F[Scope
scope] B --> G[Durability
durable] ``` ## Usage ```typescript import { Scope } from '@nestjs/common'; import type { ClassProvider } from '@nestjs/common'; class DevelopmentConfigService { getDatabaseUrl() { return 'postgres://localhost/dev'; } } class ProductionConfigService { getDatabaseUrl() { return process.env.DATABASE_URL; } } const configServiceProvider: ClassProvider = { provide: 'CONFIG_SERVICE', useClass: process.env.NODE_ENV === 'development' ? DevelopmentConfigService : ProductionConfigService, scope: Scope.DEFAULT, durable: true, }; // Register in a module: // @Module({ // providers: [configServiceProvider], // exports: ['CONFIG_SERVICE'], // }) ``` ## AI Coding Instructions - Use `provide` to define the token consumers inject, and `useClass` to define the concrete class instantiated for that token. - Choose `useClass` when the dependency should be created by the container rather than supplied as an existing value. - Ensure the class assigned to `useClass` is constructible and that its own constructor dependencies are registered providers. - Configure `scope` only when lifecycle behavior differs from the default singleton scope. - Do not add an `inject` array to a `ClassProvider`; constructor dependencies are resolved from the `useClass` type automatically. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `isClassProvider` — `packages/core/injector/helpers/provider-classifier.ts`:9 - `Module` — `packages/core/injector/module.ts`:44 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # Redirect **Kind:** Function **Source:** [`packages/common/decorators/http/redirect.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/redirect.decorator.ts#L8) **Part of:** [Common](subsystem-packages-common) Redirects request to the specified URL. `Redirect()` is a route handler decorator that configures an HTTP redirect response for a controller endpoint. It stores redirect URL and optional status-code metadata that the framework reads when processing the request; a handler can also return redirect values dynamically. ## Signature ```ts function Redirect(url, statusCode: number): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `url` | `any` | | `statusCode` | `number` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[HTTP Client] --> Route[Controller Route Handler] Route --> Decorator["@Redirect(url, statusCode)"] Decorator --> Metadata[Redirect Metadata] Metadata --> Router[HTTP Response Processing] Router --> Response[Redirect Response
Location + 3xx Status] ``` ## Usage ```ts import { Controller, Get, Redirect } from '@nestjs/common'; @Controller('docs') export class DocsController { @Get() @Redirect('https://docs.example.com', 302) redirectToDocs() { // Responds with a 302 redirect to https://docs.example.com } @Get('latest') @Redirect() redirectToLatestVersion() { return { url: 'https://docs.example.com/v2', statusCode: 301, }; } } ``` ## AI Coding Instructions - Apply `@Redirect()` to controller route handlers, typically alongside HTTP method decorators such as `@Get()` or `@Post()`. - Provide a redirect URL and optional 3xx status code for static redirects; use a handler return value for request-dependent destinations. - Prefer `301` for permanent redirects and `302`/`307` for temporary redirects, based on the intended client and caching behavior. - Ensure redirect targets are validated when derived from request input to prevent open-redirect vulnerabilities. - Do not manually write the response after using this decorator; let the framework's redirect response processing consume the metadata. # Render **Kind:** Function **Source:** [`packages/common/decorators/http/render.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/render.decorator.ts#L14) **Part of:** [Common](subsystem-packages-common) Route handler method Decorator. Defines a template to be rendered by the controller. For example: `@Render('index')` `Render()` is a route handler decorator that assigns a view template to be rendered when the controller method completes. It integrates with the HTTP response pipeline, allowing handlers to return model data while the configured template is responsible for producing the final HTML response. ## Signature ```ts function Render(template: string): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `template` | `string` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR A[HTTP Request] --> B[Controller Route Handler] B --> C["@Render('template')"] B --> D[Handler Return Value / View Model] C --> E[Template Engine] D --> E E --> F[Rendered HTML Response] ``` ## Usage ```ts import { Controller, Get, Render } from '@nestjs/common'; @Controller() export class AppController { @Get() @Render('index') getHomePage() { return { title: 'Welcome', message: 'Hello from the controller', }; } } ``` ## AI Coding Instructions - Apply `@Render('template-name')` to controller route handler methods that should return rendered HTML rather than raw JSON. - Return an object from the handler to provide template variables; its properties become available to the configured view. - Ensure the template name matches a file supported by the application's configured view engine and views directory. - Do not manually call response rendering methods when using `@Render()`, unless intentionally bypassing the standard decorator-based flow. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `AppController` — `sample/15-mvc/src/app.controller.ts`:3 - `AppController` — `sample/17-mvc-fastify/src/app.controller.ts`:3 # WebSocketAdapter **Kind:** Interface **Source:** [`packages/common/interfaces/websockets/web-socket-adapter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/websockets/web-socket-adapter.interface.ts#L15) **Part of:** [Common](subsystem-packages-common) ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ApplicationConfig` — `packages/core/application-config.ts`:13 - `NestApplication` — `packages/core/nest-application.ts`:54 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `BaseWsInstance` — `packages/websockets/adapters/ws-adapter.ts`:8 # flatten **Kind:** Function **Source:** [`packages/common/decorators/core/dependencies.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/dependencies.decorator.ts#L3) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function flatten(arr: T): T extends Array ? R : never ``` ## Parameters | Name | Type | |---|---| | `arr` | `T` | **Returns:** `T extends Array ? R : never` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `FilterByInclude` — `packages/core/discovery/discovery-service.ts`:16 # ForbiddenException **Kind:** Class **Source:** [`packages/common/exceptions/forbidden.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/forbidden.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Forbidden* type errors. `ForbiddenException` represents an HTTP 403 error, indicating that a request was understood but the authenticated user does not have permission to perform the requested action. It extends the framework's HTTP exception handling system so controllers, guards, and services can signal authorization failures consistently. Use it when access is denied due to insufficient roles, ownership, or policy permissions. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Incoming request] --> B[Authorization check] B -->|Permission granted| C[Continue request handling] B -->|Permission denied| D[ForbiddenException] D --> E[HTTP 403 Forbidden response] ``` ## Usage ```ts import { ForbiddenException } from '@nestjs/common'; function updateProject(userId: string, project: { ownerId: string }) { if (project.ownerId !== userId) { throw new ForbiddenException( 'You do not have permission to update this project.', ); } return { success: true }; } ``` ## AI Coding Instructions - Throw `ForbiddenException` only for authorization failures; use `UnauthorizedException` when the user is not authenticated. - Perform role, ownership, or policy checks before executing protected mutations or exposing restricted data. - Provide a clear, safe error message, but do not reveal sensitive permission rules or internal resource details. - Prefer using guards or centralized authorization policies for reusable access-control logic rather than duplicating checks across controllers. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `ParamsFactory` — `packages/core/helpers/external-context-creator.ts`:28 # isPlainObject **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L7) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isPlainObject(fn: any): fn is object ``` ## Parameters | Name | Type | |---|---| | `fn` | `any` | **Returns:** `fn is object` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `KafkaRequest` — `packages/microservices/serializers/kafka-request.serializer.ts`:10 # ParseArrayPipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-array.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-array.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # RouteInfo **Kind:** Interface **Source:** [`packages/common/interfaces/middleware/middleware-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/middleware/middleware-configuration.interface.ts#L5) **Part of:** [Common](subsystem-packages-common) `RouteInfo` describes a single route targeted by middleware configuration. It combines the route path, HTTP request method, and API version so middleware can be applied to the correct endpoint variant. ## Properties | Property | Type | |---|---| | `path` | `string` | | `method` | `RequestMethod` | | `version` | `VersionValue` | ## Diagram ```mermaid graph LR Middleware[Middleware Configuration] --> RouteInfo RouteInfo --> Path[path: string] RouteInfo --> Method[method: RequestMethod] RouteInfo --> Version[version: VersionValue] RouteInfo --> TargetRoute[Versioned HTTP Route] ``` ## Usage ```ts import { RequestMethod } from '@nestjs/common'; import type { RouteInfo } from './middleware-configuration.interface'; const protectedRoute: RouteInfo = { path: 'users/:id', method: RequestMethod.GET, version: '1', }; // Example: register middleware for a specific versioned endpoint. consumer .apply(AuthMiddleware) .forRoutes(protectedRoute); ``` ## AI Coding Instructions - Provide all three fields when creating a `RouteInfo`: `path`, `method`, and `version`. - Use `RequestMethod` enum values instead of raw HTTP method strings such as `'GET'`. - Keep `path` consistent with the application's route definitions, including parameter segments like `:id`. - Set `version` to the same `VersionValue` used by the controller or route being targeted. - Use `RouteInfo` when middleware must apply to a specific method and API version rather than an entire controller. ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `MiddlewareBuilder` — `packages/core/middleware/builder.ts`:17 - `handler` — `packages/core/middleware/middleware-module.ts`:287 - `RouteInfoPathExtractor` — `packages/core/middleware/route-info-path-extractor.ts`:16 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 - `anonymousMiddleware` — `packages/core/middleware/utils.ts`:77 # ValidationPipe **Kind:** Pipe **Source:** [`packages/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/validation.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # Body **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L502) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the entire `body` object property, or optionally a named property of the `body` object, from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound body parameter. For example: ```typescript async create(@Body('role', new ValidationPipe()) role: string) ``` `Body()` binds a route handler parameter to the request `body` value. When given a property key, it extracts that property from `req.body`; pipes passed to the decorator run on the bound value. ## Signature ```ts function Body(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqBody[req.body] ReqBody --> BodyDecorator["@Body()"] BodyDecorator --> Property[Selected body property] Property --> Pipes[Pipes] Pipes --> Parameter[Route handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Post() async create( @Body('role', new ValidationPipe()) role: string, ) { return { role }; } } ``` ## AI Coding Instructions - Use `@Body()` when the handler needs the full request body. - Pass a property key, such as `@Body('role')`, when the handler needs a single body field. - Pass pipes after the property key so they receive the extracted value. - Keep body-property names aligned with the request DTO or client payload. # Body **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L502) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the entire `body` object property, or optionally a named property of the `body` object, from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound body parameter. For example: ```typescript async create(@Body('role', new ValidationPipe()) role: string) ``` `Body()` binds a route handler parameter to the request `body` value. When given a property key, it extracts that property from `req.body`; pipes passed to the decorator run on the bound value. ## Signature ```ts function Body(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqBody[req.body] ReqBody --> BodyDecorator["@Body()"] BodyDecorator --> Property[Selected body property] Property --> Pipes[Pipes] Pipes --> Parameter[Route handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Post() async create( @Body('role', new ValidationPipe()) role: string, ) { return { role }; } } ``` ## AI Coding Instructions - Use `@Body()` when the handler needs the full request body. - Pass a property key, such as `@Body('role')`, when the handler needs a single body field. - Pass pipes after the property key so they receive the extracted value. - Keep body-property names aligned with the request DTO or client payload. # Body **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L502) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the entire `body` object property, or optionally a named property of the `body` object, from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound body parameter. For example: ```typescript async create(@Body('role', new ValidationPipe()) role: string) ``` `Body()` binds a route handler parameter to the request `body` value. When given a property key, it extracts that property from `req.body`; pipes passed to the decorator run on the bound value. ## Signature ```ts function Body(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqBody[req.body] ReqBody --> BodyDecorator["@Body()"] BodyDecorator --> Property[Selected body property] Property --> Pipes[Pipes] Pipes --> Parameter[Route handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Post() async create( @Body('role', new ValidationPipe()) role: string, ) { return { role }; } } ``` ## AI Coding Instructions - Use `@Body()` when the handler needs the full request body. - Pass a property key, such as `@Body('role')`, when the handler needs a single body field. - Pass pipes after the property key so they receive the extracted value. - Keep body-property names aligned with the request DTO or client payload. # Body **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L502) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the entire `body` object property, or optionally a named property of the `body` object, from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound body parameter. For example: ```typescript async create(@Body('role', new ValidationPipe()) role: string) ``` `Body()` binds a route handler parameter to the request `body` value. When given a property key, it extracts that property from `req.body`; pipes passed to the decorator run on the bound value. ## Signature ```ts function Body(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqBody[req.body] ReqBody --> BodyDecorator["@Body()"] BodyDecorator --> Property[Selected body property] Property --> Pipes[Pipes] Pipes --> Parameter[Route handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Post() async create( @Body('role', new ValidationPipe()) role: string, ) { return { role }; } } ``` ## AI Coding Instructions - Use `@Body()` when the handler needs the full request body. - Pass a property key, such as `@Body('role')`, when the handler needs a single body field. - Pass pipes after the property key so they receive the extracted value. - Keep body-property names aligned with the request DTO or client payload. # Controller **Kind:** Function **Source:** [`packages/common/decorators/core/controller.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/controller.decorator.ts#L151) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses. An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example `GET /api/profile`, `POST /users/resume` A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers. `@Controller()` marks a class as a Nest controller. It establishes the class as the context for related HTTP route handlers or microservice message and event handlers. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Request[Inbound request or event] --> Controller["@Controller() class"] Controller --> Handler[Route or message handler] Handler --> Response[HTTP response or event result] ``` ## Usage ```ts import { Controller, Get, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll() { return ['Ada', 'Grace']; } @Post() create(@Body() user: { name: string }) { return user; } } ``` ## AI Coding Instructions - Apply `@Controller()` to classes that group related route, message, or event handlers. - Pass a route prefix such as `'users'` when handlers share a common URL path. - Add method decorators such as `@Get()` and `@Post()` for HTTP endpoints within the controller class. - Keep request handling in controllers and delegate business logic to injected services. - Match controller routes with the application’s configured global prefix and module registration. # Controller **Kind:** Function **Source:** [`packages/common/decorators/core/controller.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/controller.decorator.ts#L151) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses. An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example `GET /api/profile`, `POST /users/resume` A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers. `@Controller()` marks a class as a Nest controller. It establishes the class as the context for related HTTP route handlers or microservice message and event handlers. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Request[Inbound request or event] --> Controller["@Controller() class"] Controller --> Handler[Route or message handler] Handler --> Response[HTTP response or event result] ``` ## Usage ```ts import { Controller, Get, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll() { return ['Ada', 'Grace']; } @Post() create(@Body() user: { name: string }) { return user; } } ``` ## AI Coding Instructions - Apply `@Controller()` to classes that group related route, message, or event handlers. - Pass a route prefix such as `'users'` when handlers share a common URL path. - Add method decorators such as `@Get()` and `@Post()` for HTTP endpoints within the controller class. - Keep request handling in controllers and delegate business logic to injected services. - Match controller routes with the application’s configured global prefix and module registration. # Controller **Kind:** Function **Source:** [`packages/common/decorators/core/controller.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/controller.decorator.ts#L151) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses. An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example `GET /api/profile`, `POST /users/resume` A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers. `@Controller()` marks a class as a Nest controller. It establishes the class as the context for related HTTP route handlers or microservice message and event handlers. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Request[Inbound request or event] --> Controller["@Controller() class"] Controller --> Handler[Route or message handler] Handler --> Response[HTTP response or event result] ``` ## Usage ```ts import { Controller, Get, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll() { return ['Ada', 'Grace']; } @Post() create(@Body() user: { name: string }) { return user; } } ``` ## AI Coding Instructions - Apply `@Controller()` to classes that group related route, message, or event handlers. - Pass a route prefix such as `'users'` when handlers share a common URL path. - Add method decorators such as `@Get()` and `@Post()` for HTTP endpoints within the controller class. - Keep request handling in controllers and delegate business logic to injected services. - Match controller routes with the application’s configured global prefix and module registration. # Controller **Kind:** Function **Source:** [`packages/common/decorators/core/controller.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/controller.decorator.ts#L151) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses. An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example `GET /api/profile`, `POST /users/resume` A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers. `@Controller()` marks a class as a Nest controller. It establishes the class as the context for related HTTP route handlers or microservice message and event handlers. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Request[Inbound request or event] --> Controller["@Controller() class"] Controller --> Handler[Route or message handler] Handler --> Response[HTTP response or event result] ``` ## Usage ```ts import { Controller, Get, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll() { return ['Ada', 'Grace']; } @Post() create(@Body() user: { name: string }) { return user; } } ``` ## AI Coding Instructions - Apply `@Controller()` to classes that group related route, message, or event handlers. - Pass a route prefix such as `'users'` when handlers share a common URL path. - Add method decorators such as `@Get()` and `@Post()` for HTTP endpoints within the controller class. - Keep request handling in controllers and delegate business logic to injected services. - Match controller routes with the application’s configured global prefix and module registration. # CorsOptions **Kind:** Interface **Source:** [`packages/common/interfaces/external/cors-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/cors-options.interface.ts#L23) **Part of:** [Common](subsystem-packages-common) Interface describing CORS options that can be set. `CorsOptions` defines the Cross-Origin Resource Sharing (CORS) configuration accepted by the application’s HTTP layer. Use it to control which origins, methods, and headers browsers may use when making cross-origin requests, as well as how preflight `OPTIONS` requests are handled. ## Properties | Property | Type | |---|---| | `origin` | `StaticOrigin | CustomOrigin` | | `methods` | `string | string[]` | | `allowedHeaders` | `string | string[]` | | `exposedHeaders` | `string | string[]` | | `credentials` | `boolean` | | `maxAge` | `number` | | `preflightContinue` | `boolean` | | `optionsSuccessStatus` | `number` | ## Diagram ```mermaid graph LR App[Application Bootstrap] --> Options[CorsOptions] Options --> Origin[origin: StaticOrigin | CustomOrigin] Options --> Methods[methods: string | string[]] Options --> Headers[allowedHeaders / exposedHeaders] Options --> Credentials[credentials: boolean] Options --> Preflight[Preflight Settings] Preflight --> MaxAge[maxAge] Preflight --> Continue[preflightContinue] Preflight --> Status[optionsSuccessStatus] Options --> Middleware[CORS Middleware] Middleware --> Browser[Browser Cross-Origin Requests] ``` ## Usage ```ts import type { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface'; const corsOptions: CorsOptions = { origin: ['https://app.example.com', 'https://admin.example.com'], methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], allowedHeaders: ['Content-Type', 'Authorization'], exposedHeaders: ['X-Request-Id'], credentials: true, maxAge: 86400, optionsSuccessStatus: 204, }; // Example application integration app.enableCors(corsOptions); ``` ## AI Coding Instructions - Provide `origin` as a static origin value or a custom origin callback when origin validation must be dynamic. - Enable `credentials` only when required; credentialed requests should not use a wildcard (`*`) origin. - Include all custom request headers in `allowedHeaders`, especially headers such as `Authorization`. - Set `maxAge` to reduce repeated browser preflight requests for stable API policies. - Use `optionsSuccessStatus` for clients that require a specific successful response status for `OPTIONS` requests. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `GatewayMetadata` — `packages/websockets/interfaces/gateway-metadata.interface.ts`:8 # Delete **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L66) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP DELETE requests to the specified path. `Delete` is a route handler decorator that maps an HTTP `DELETE` request to a controller method. Use it to define endpoints responsible for removing resources or performing delete-oriented actions at a specified path. ## Definition ```ts createMappingDecorator(RequestMethod.DELETE) ``` ## Value ```ts createMappingDecorator(RequestMethod.DELETE) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|DELETE /users/:id| Router[HTTP Router] Router -->|matches route| Controller[Controller Method] Controller -->|@Delete(':id')| Handler[Delete Handler] Handler --> Response[HTTP Response] ``` ## Usage ```ts import { Controller, Delete, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Delete(':id') async remove(@Param('id') id: string) { await this.usersService.remove(id); return { message: `User ${id} deleted successfully`, }; } } ``` ## AI Coding Instructions - Apply `@Delete()` only to controller methods that handle HTTP `DELETE` requests. - Provide a route path such as `':id'` when the handler deletes a specific resource. - Use parameter decorators like `@Param()` to access path values required by the delete operation. - Delegate deletion logic to a service layer rather than placing persistence logic directly in the controller. - Return an appropriate response or configure the expected HTTP status code for successful deletion. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `DatabaseController` — `integration/inspector/src/database/database.controller.ts`:14 - `DogsController` — `integration/inspector/src/dogs/dogs.controller.ts`:14 - `UsersController` — `integration/inspector/src/users/users.controller.ts`:14 - `UsersController` — `integration/repl/src/users/users.controller.ts`:14 - `UsersController` — `sample/05-sql-typeorm/src/users/users.controller.ts`:14 - `CatsController` — `sample/06-mongoose/src/cats/cats.controller.ts`:7 - `UsersController` — `sample/07-sequelize/src/users/users.controller.ts`:6 # MiddlewareConsumer **Kind:** Interface **Source:** [`packages/common/interfaces/middleware/middleware-consumer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/middleware/middleware-consumer.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) Interface defining method for applying user defined middleware to routes. `MiddlewareConsumer` defines the API used to register application middleware during module configuration. Its `apply()` method accepts one or more middleware classes or functions and returns a configuration proxy that can target specific routes, controllers, HTTP methods, or exclusions. ## Diagram ```mermaid graph LR A[Module.configure] --> B[MiddlewareConsumer] B --> C[apply Middleware] C --> D[MiddlewareConfigProxy] D --> E[forRoutes / exclude] E --> F[Matched HTTP Routes] F --> G[Middleware Execution] G --> H[Route Handler] ``` ## Usage ```ts import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common'; import { LoggerMiddleware } from './logger.middleware'; import { CatsController } from './cats.controller'; @Module({ controllers: [CatsController], }) export class CatsModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .exclude({ path: 'cats/health', method: RequestMethod.GET }) .forRoutes(CatsController); } } ``` ## AI Coding Instructions - Use `MiddlewareConsumer` inside a module's `configure()` method, typically by implementing `NestModule`. - Pass middleware classes or compatible middleware functions to `consumer.apply()`. - Chain `forRoutes()` after `apply()` to ensure middleware is attached to intended controllers or route patterns. - Use `exclude()` before `forRoutes()` when a middleware should not run for selected endpoints. - Keep middleware registration module-specific when possible; use global middleware only when it truly applies across the application. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `CoreModule` — `integration/inspector/src/core/core.module.ts`:8 - `AppModule` — `integration/nest-application/global-prefix/src/app.module.ts`:7 - `AppModule` — `integration/versioning/src/app.module.ts`:13 - `MiddlewareBuilder` — `packages/core/middleware/builder.ts`:17 # Param **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L689) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `params` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@Param() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@Param('id') id: string) ``` `Param()` binds route parameters from `req.params` to a controller handler argument. Pass a parameter name to extract one value, or omit it to receive the full params object; pipes can transform or validate the bound value. ## Signature ```ts function Param(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqParams[req.params] ReqParams --> ParamDecorator["@Param()"] ParamDecorator --> HandlerParameter[Route handler parameter] Pipes[Pipes, if provided] --> HandlerParameter ``` ## Usage ```typescript import { Controller, Get, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id }; } @Get(':userId/posts/:postId') findPost(@Param() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one named route parameter. - Use `@Param()` without a name when the handler needs the complete `req.params` object. - Keep the decorator parameter name aligned with the route token, such as `@Get(':id')` and `@Param('id')`. - Attach pipes to `@Param()` when route parameter values require validation or transformation before reaching the handler. # Param **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L689) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `params` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@Param() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@Param('id') id: string) ``` `Param()` binds route parameters from `req.params` to a controller handler argument. Pass a parameter name to extract one value, or omit it to receive the full params object; pipes can transform or validate the bound value. ## Signature ```ts function Param(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqParams[req.params] ReqParams --> ParamDecorator["@Param()"] ParamDecorator --> HandlerParameter[Route handler parameter] Pipes[Pipes, if provided] --> HandlerParameter ``` ## Usage ```typescript import { Controller, Get, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id }; } @Get(':userId/posts/:postId') findPost(@Param() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one named route parameter. - Use `@Param()` without a name when the handler needs the complete `req.params` object. - Keep the decorator parameter name aligned with the route token, such as `@Get(':id')` and `@Param('id')`. - Attach pipes to `@Param()` when route parameter values require validation or transformation before reaching the handler. # Param **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L689) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `params` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@Param() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@Param('id') id: string) ``` `Param()` binds route parameters from `req.params` to a controller handler argument. Pass a parameter name to extract one value, or omit it to receive the full params object; pipes can transform or validate the bound value. ## Signature ```ts function Param(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqParams[req.params] ReqParams --> ParamDecorator["@Param()"] ParamDecorator --> HandlerParameter[Route handler parameter] Pipes[Pipes, if provided] --> HandlerParameter ``` ## Usage ```typescript import { Controller, Get, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id }; } @Get(':userId/posts/:postId') findPost(@Param() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one named route parameter. - Use `@Param()` without a name when the handler needs the complete `req.params` object. - Keep the decorator parameter name aligned with the route token, such as `@Get(':id')` and `@Param('id')`. - Attach pipes to `@Param()` when route parameter values require validation or transformation before reaching the handler. # Param **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L689) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `params` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@Param() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@Param('id') id: string) ``` `Param()` binds route parameters from `req.params` to a controller handler argument. Pass a parameter name to extract one value, or omit it to receive the full params object; pipes can transform or validate the bound value. ## Signature ```ts function Param(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[HTTP request] --> ReqParams[req.params] ReqParams --> ParamDecorator["@Param()"] ParamDecorator --> HandlerParameter[Route handler parameter] Pipes[Pipes, if provided] --> HandlerParameter ``` ## Usage ```typescript import { Controller, Get, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id }; } @Get(':userId/posts/:postId') findPost(@Param() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one named route parameter. - Use `@Param()` without a name when the handler needs the complete `req.params` object. - Keep the decorator parameter name aligned with the route token, such as `@Get(':id')` and `@Param('id')`. - Attach pipes to `@Param()` when route parameter values require validation or transformation before reaching the handler. # Query **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L408) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `query` property from the `req` object and populates the decorated parameter with the value of `query`. May also apply pipes to the bound query parameter. For example: ```typescript async find(@Query('user') user: string) ``` `@Query()` is a route-handler parameter decorator that reads the `query` property from the incoming request object. It binds either the full query object or a named query value to the decorated parameter, and can apply pipes during parameter binding. ## Signature ```ts function Query(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> QueryObject[req.query] QueryObject --> Decorator["@Query()"] Decorator --> HandlerParam[Route handler parameter] Pipes[Pipes] --> Decorator ``` ## Usage ```typescript import { Controller, Get, Query } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() find(@Query('user') user: string) { return { user }; } @Get('search') search(@Query() query: Record) { return query; } } ``` ## AI Coding Instructions - Use `@Query('key')` when a handler needs a single query parameter, and `@Query()` when it needs the full query object. - Keep query parameter names aligned with the request contract, such as `?user=value` for `@Query('user')`. - Apply pipes through the decorator when query values need validation or transformation. - Treat query values as request input and account for missing, repeated, or non-string values where applicable. # Query **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L408) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `query` property from the `req` object and populates the decorated parameter with the value of `query`. May also apply pipes to the bound query parameter. For example: ```typescript async find(@Query('user') user: string) ``` `@Query()` is a route-handler parameter decorator that reads the `query` property from the incoming request object. It binds either the full query object or a named query value to the decorated parameter, and can apply pipes during parameter binding. ## Signature ```ts function Query(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> QueryObject[req.query] QueryObject --> Decorator["@Query()"] Decorator --> HandlerParam[Route handler parameter] Pipes[Pipes] --> Decorator ``` ## Usage ```typescript import { Controller, Get, Query } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() find(@Query('user') user: string) { return { user }; } @Get('search') search(@Query() query: Record) { return query; } } ``` ## AI Coding Instructions - Use `@Query('key')` when a handler needs a single query parameter, and `@Query()` when it needs the full query object. - Keep query parameter names aligned with the request contract, such as `?user=value` for `@Query('user')`. - Apply pipes through the decorator when query values need validation or transformation. - Treat query values as request input and account for missing, repeated, or non-string values where applicable. # Query **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L408) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `query` property from the `req` object and populates the decorated parameter with the value of `query`. May also apply pipes to the bound query parameter. For example: ```typescript async find(@Query('user') user: string) ``` `@Query()` is a route-handler parameter decorator that reads the `query` property from the incoming request object. It binds either the full query object or a named query value to the decorated parameter, and can apply pipes during parameter binding. ## Signature ```ts function Query(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> QueryObject[req.query] QueryObject --> Decorator["@Query()"] Decorator --> HandlerParam[Route handler parameter] Pipes[Pipes] --> Decorator ``` ## Usage ```typescript import { Controller, Get, Query } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() find(@Query('user') user: string) { return { user }; } @Get('search') search(@Query() query: Record) { return query; } } ``` ## AI Coding Instructions - Use `@Query('key')` when a handler needs a single query parameter, and `@Query()` when it needs the full query object. - Keep query parameter names aligned with the request contract, such as `?user=value` for `@Query('user')`. - Apply pipes through the decorator when query values need validation or transformation. - Treat query values as request input and account for missing, repeated, or non-string values where applicable. # Query **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L408) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `query` property from the `req` object and populates the decorated parameter with the value of `query`. May also apply pipes to the bound query parameter. For example: ```typescript async find(@Query('user') user: string) ``` `@Query()` is a route-handler parameter decorator that reads the `query` property from the incoming request object. It binds either the full query object or a named query value to the decorated parameter, and can apply pipes during parameter binding. ## Signature ```ts function Query(property: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> QueryObject[req.query] QueryObject --> Decorator["@Query()"] Decorator --> HandlerParam[Route handler parameter] Pipes[Pipes] --> Decorator ``` ## Usage ```typescript import { Controller, Get, Query } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() find(@Query('user') user: string) { return { user }; } @Get('search') search(@Query() query: Record) { return query; } } ``` ## AI Coding Instructions - Use `@Query('key')` when a handler needs a single query parameter, and `@Query()` when it needs the full query object. - Keep query parameter names aligned with the request contract, such as `?user=value` for `@Query('user')`. - Apply pipes through the decorator when query values need validation or transformation. - Treat query values as request input and account for missing, repeated, or non-string values where applicable. # UploadedFile **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L241) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `file` object and populates the decorated parameter with the value of `file`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFile() file) { console.log(file); } ``` `@UploadedFile()` is a route handler parameter decorator that reads the uploaded file object from the request and assigns it to the decorated parameter. In Express applications, it works with Multer middleware or a Nest file interceptor that places a file on the request. ## Signature ```ts function UploadedFile(fileKey: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `fileKey` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[Client multipart request] --> Middleware[Multer or FileInterceptor] Middleware --> Request[Request with file object] Request --> Decorator[@UploadedFile()] Decorator --> Handler[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename, mimetype: file.mimetype, size: file.size, }; } } ``` ## AI Coding Instructions - Pair `@UploadedFile()` with Multer middleware or `FileInterceptor()` so the request contains a file object. - Match the field name passed to `FileInterceptor('file')` with the multipart form field sent by the client. - Handle missing files when the upload field is optional or middleware may reject the request. - Add validation pipes or file checks when routes need to restrict file type or size. # UploadedFile **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L241) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `file` object and populates the decorated parameter with the value of `file`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFile() file) { console.log(file); } ``` `@UploadedFile()` is a route handler parameter decorator that reads the uploaded file object from the request and assigns it to the decorated parameter. In Express applications, it works with Multer middleware or a Nest file interceptor that places a file on the request. ## Signature ```ts function UploadedFile(fileKey: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `fileKey` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[Client multipart request] --> Middleware[Multer or FileInterceptor] Middleware --> Request[Request with file object] Request --> Decorator[@UploadedFile()] Decorator --> Handler[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename, mimetype: file.mimetype, size: file.size, }; } } ``` ## AI Coding Instructions - Pair `@UploadedFile()` with Multer middleware or `FileInterceptor()` so the request contains a file object. - Match the field name passed to `FileInterceptor('file')` with the multipart form field sent by the client. - Handle missing files when the upload field is optional or middleware may reject the request. - Add validation pipes or file checks when routes need to restrict file type or size. # UploadedFile **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L241) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `file` object and populates the decorated parameter with the value of `file`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFile() file) { console.log(file); } ``` `@UploadedFile()` is a route handler parameter decorator that reads the uploaded file object from the request and assigns it to the decorated parameter. In Express applications, it works with Multer middleware or a Nest file interceptor that places a file on the request. ## Signature ```ts function UploadedFile(fileKey: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `fileKey` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[Client multipart request] --> Middleware[Multer or FileInterceptor] Middleware --> Request[Request with file object] Request --> Decorator[@UploadedFile()] Decorator --> Handler[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename, mimetype: file.mimetype, size: file.size, }; } } ``` ## AI Coding Instructions - Pair `@UploadedFile()` with Multer middleware or `FileInterceptor()` so the request contains a file object. - Match the field name passed to `FileInterceptor('file')` with the multipart form field sent by the client. - Handle missing files when the upload field is optional or middleware may reject the request. - Add validation pipes or file checks when routes need to restrict file type or size. # UploadedFile **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L241) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `file` object and populates the decorated parameter with the value of `file`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFile() file) { console.log(file); } ``` `@UploadedFile()` is a route handler parameter decorator that reads the uploaded file object from the request and assigns it to the decorated parameter. In Express applications, it works with Multer middleware or a Nest file interceptor that places a file on the request. ## Signature ```ts function UploadedFile(fileKey: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `fileKey` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[Client multipart request] --> Middleware[Multer or FileInterceptor] Middleware --> Request[Request with file object] Request --> Decorator[@UploadedFile()] Decorator --> Handler[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename, mimetype: file.mimetype, size: file.size, }; } } ``` ## AI Coding Instructions - Pair `@UploadedFile()` with Multer middleware or `FileInterceptor()` so the request contains a file object. - Match the field name passed to `FileInterceptor('file')` with the multipart form field sent by the client. - Handle missing files when the upload field is optional or middleware may reject the request. - Add validation pipes or file checks when routes need to restrict file type or size. # VERSION_NEUTRAL **Kind:** Constant **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) Indicates that this will work for any version passed in the request, or no version. `VERSION_NEUTRAL` is a versioning constant that marks a route or controller as compatible with every API version. It allows an endpoint to handle requests regardless of whether a version is specified in the request, providing a fallback for version-neutral functionality. ## Definition ```ts Symbol('VERSION_NEUTRAL') ``` ## Value ```ts Symbol('VERSION_NEUTRAL') ``` ## Diagram ```mermaid graph LR Request[Incoming Request] --> VersionCheck{Version specified?} VersionCheck -->|Yes| VersionedRoute[Version-specific Route] VersionCheck -->|No or Any Version| NeutralRoute[VERSION_NEUTRAL Route] NeutralRoute --> Handler[Route Handler] ``` ## Usage ```ts import { Controller, Get, VERSION_NEUTRAL } from '@nestjs/common'; @Controller({ path: 'health', version: VERSION_NEUTRAL, }) export class HealthController { @Get() check() { return { status: 'ok' }; } } ``` ## AI Coding Instructions - Use `VERSION_NEUTRAL` for endpoints that must remain accessible across all API versions, such as health checks or shared metadata routes. - Apply it through controller or route version metadata where Nest versioning is enabled. - Do not use it for endpoints whose response contract changes between API versions. - Ensure version-neutral routes do not conflict with version-specific routes using the same HTTP method and path. - Test requests both with and without version information to confirm the route is resolved as expected. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `VersionNeutralMiddlewareController` — `integration/versioning/src/neutral-middleware.controller.ts`:3 - `VersionNeutralController` — `integration/versioning/src/neutral.controller.ts`:3 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 - `MODULE_INIT_MESSAGE` — `packages/core/helpers/messages.ts`:7 - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # applyDecorators **Kind:** Function **Source:** [`packages/common/decorators/core/apply-decorators.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/apply-decorators.ts#L10) **Part of:** [Common](subsystem-packages-common) Function that returns a new decorator that applies all decorators provided by param Useful to build new decorators (or a decorator factory) encapsulating multiple decorators related with the same feature `applyDecorators` combines multiple class, method, or property decorators into a single reusable decorator. It applies each supplied decorator in order, making it useful for creating feature-specific decorator factories that encapsulate related metadata, guards, interceptors, or other decorator behavior. ## Signature ```ts function applyDecorators(decorators: Array) ``` ## Parameters | Name | Type | |---|---| | `decorators` | `Array` | ## Diagram ```mermaid graph LR A[Custom decorator factory] --> B[applyDecorators] B --> C[Decorator 1] B --> D[Decorator 2] B --> E[Decorator N] C --> F[Target class, method, or property] D --> F E --> F ``` ## Usage ```ts import { applyDecorators, SetMetadata, UseGuards, } from '@nestjs/common'; const RolesGuard = class {}; export function AdminOnly() { return applyDecorators( SetMetadata('roles', ['admin']), UseGuards(RolesGuard), ); } class UsersController { @AdminOnly() removeUser() { return 'User removed'; } } ``` ## AI Coding Instructions - Use `applyDecorators` when multiple decorators represent one cohesive feature or policy, such as authorization, caching, or API behavior. - Preserve decorator ordering, since decorators are applied in the order they are passed to `applyDecorators`. - Ensure every provided decorator is valid for the intended target type: class, method, or property. - Prefer creating named decorator factories, such as `AdminOnly()` or `PublicEndpoint()`, instead of repeating the same decorator combination across controllers. # Bind **Kind:** Function **Source:** [`packages/common/decorators/core/bind.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/bind.decorator.ts#L11) **Part of:** [Common](subsystem-packages-common) Decorator that binds *parameter decorators* to the method that follows. Useful when the language doesn't provide a 'Parameter Decorator' feature (i.e., vanilla JavaScript). `Bind` creates a method decorator that attaches the supplied decorators to the method it decorates. It is primarily used to apply parameter-oriented decorators in environments such as vanilla JavaScript, where parameter decorator syntax is not available. ## Signature ```ts function Bind(decorators: any[]): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `decorators` | `any[]` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR A[Bind decorator factories] --> B[@Bind(...decorators)] B --> C[Following method] C --> D[Apply supplied decorators] D --> E[Method metadata / runtime behavior] ``` ## Usage ```ts import { Bind, Controller, Get, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') @Bind(Param('id')) findOne(id: string) { return { id }; } } ``` ## AI Coding Instructions - Use `Bind` when parameter decorator syntax cannot be used directly, especially in JavaScript-based controllers. - Pass decorator factories, such as `Param('id')`, `Body()`, or custom parameter decorators, rather than raw values. - Place `@Bind(...)` on the method that should receive the decorator metadata. - Keep the bound decorators aligned with the method’s expected arguments and request-handling behavior. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `CatsController` — `sample/09-babel-example/src/cats/cats.controller.js`:12 # filterLogLevels **Kind:** Function **Source:** [`packages/common/services/utils/filter-log-levels.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/utils/filter-log-levels.util.ts#L7) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function filterLogLevels(parseableString): LogLevel[] ``` ## Parameters | Name | Type | |---|---| | `parseableString` | `any` | **Returns:** `LogLevel[]` # MessageEvent **Kind:** Interface **Source:** [`packages/common/interfaces/http/message-event.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/message-event.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) `MessageEvent` represents a server-sent event (SSE) message in the HTTP layer. It defines the payload and optional SSE metadata used to identify events, classify them, control client reconnection timing, and send comment-only messages. ## Properties | Property | Type | |---|---| | `data` | `string | object` | | `id` | `string` | | `type` | `string` | | `retry` | `number` | | `comment` | `string` | ## Diagram ```mermaid graph LR Server[HTTP/SSE Server] --> Event[MessageEvent] Event --> Data[data: string | object] Event --> Id[id: string] Event --> Type[type: string] Event --> Retry[retry: number] Event --> Comment[comment: string] Event --> Client[SSE Client] ``` ## Usage ```ts import { MessageEvent } from '@nestjs/common'; const event: MessageEvent = { id: 'order-1024', type: 'order.updated', data: { orderId: 1024, status: 'shipped', }, retry: 5000, comment: 'Order status notification', }; // Example SSE stream emission subscriber.next(event); ``` ## AI Coding Instructions - Use `data` for the event payload; it may be either a serialized string or a plain object. - Set `type` to a stable, consumer-friendly event name such as `user.created` or `order.updated`. - Provide a unique `id` when clients need to resume streams using the SSE `Last-Event-ID` mechanism. - Use `retry` in milliseconds to suggest how long SSE clients should wait before reconnecting. - Use `comment` for SSE heartbeat or informational messages that should not be treated as application event data. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `CustomHeader` — `packages/core/router/router-response-controller.ts`:18 - `AdditionalHeaders` — `packages/core/router/sse-stream.ts`:38 - `PassthroughInterceptor` — `integration/nest-application/sse/src/app.controller.ts`:28 - `AppController` — `sample/28-sse/src/app.controller.ts`:8 # NestMiddleware **Kind:** Interface **Source:** [`packages/common/interfaces/middleware/nest-middleware.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/middleware/nest-middleware.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `LoggerMiddleware` — `integration/inspector/src/common/middleware/logger.middleware.ts`:3 - `LoggerMiddleware` — `sample/01-cats-app/src/common/middleware/logger.middleware.ts`:3 - `LoggerMiddleware` — `sample/10-fastify/src/common/middleware/logger.middleware.ts`:3 - `LoggerMiddleware` — `sample/36-hmr-esm/src/common/middleware/logger.middleware.ts`:3 - `handler` — `packages/core/middleware/middleware-module.ts`:287 # RequestMapping **Kind:** Function **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L14) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function RequestMapping(metadata: RequestMappingMetadata): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `metadata` | `RequestMappingMetadata` | **Returns:** `MethodDecorator` # Response **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L112) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `Response` object from the underlying platform and populates the decorated parameter with the value of `Response`. Example: `logout(@Response() res)` `Response` is a route handler parameter decorator that injects the underlying platform response object into a controller method parameter. Use it when a handler needs direct access to response APIs, such as setting headers, cookies, status codes, or manually sending a response. ## Signature ```ts function Response(options: ResponseDecoratorOptions) ``` ## Parameters | Name | Type | |---|---| | `options` | `ResponseDecoratorOptions` | ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Route Handler] B --> C[@Response() Decorator] C --> D[Platform Response Object] D --> E[Decorated Handler Parameter] E --> F[Set headers, status, cookies, or send response] ``` ## Usage ```ts import { Controller, Get, Response } from '@nestjs/common'; @Controller('auth') export class AuthController { @Get('logout') logout(@Response() res: any) { res.clearCookie('session'); return res.status(200).send({ message: 'Logged out successfully' }); } } ``` ## AI Coding Instructions - Use `@Response()` only when the route handler requires direct access to the platform-specific response object. - When manually sending a response with methods such as `res.send()` or `res.json()`, ensure the handler does not also return a framework-managed response. - Keep response-specific logic limited to controllers; move business logic into services where possible. - Account for adapter differences when supporting multiple HTTP platforms, such as Express and Fastify. - Prefer standard return values for simple handlers to preserve framework-managed serialization and status handling. # stripEndSlash **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L40) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function stripEndSlash(path: string) ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RoutePathFactory` — `packages/core/router/route-path-factory.ts`:18 - `MiddlewareBuilder` — `packages/core/middleware/builder.ts`:17 - `RouteInfoPathExtractor` — `packages/core/middleware/route-info-path-extractor.ts`:16 # UsePipes **Kind:** Function **Source:** [`packages/common/decorators/core/use-pipes.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/use-pipes.decorator.ts#L29) **Part of:** [Common](subsystem-packages-common) Decorator that binds pipes to the scope of the controller or method, depending on its context. When `@UsePipes` is used at the controller level, the pipe will be applied to every handler (method) in the controller. When `@UsePipes` is used at the individual handler level, the pipe will apply only to that specific method. `@UsePipes()` binds one or more NestJS pipes to a controller class or individual route handler. Pipes transform or validate incoming request data before it reaches the handler, with controller-level pipes applying to all handlers and method-level pipes applying only to that route. ## Signature ```ts function UsePipes(pipes: (PipeTransform | Function)[]): ClassDecorator & MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(PipeTransform | Function)[]` | **Returns:** `ClassDecorator & MethodDecorator` ## Diagram ```mermaid graph LR Request[Incoming Request] --> Controller{Controller Scope?} Controller -->|@UsePipes on controller| GlobalPipe[Apply pipes to every handler] Controller -->|@UsePipes on method| MethodPipe[Apply pipes only to selected handler] GlobalPipe --> Handler[Route Handler] MethodPipe --> Handler Handler --> Response[Response] ``` ## Usage ```ts import { Body, Controller, Get, Param, ParseIntPipe, Post, UsePipes, ValidationPipe, } from '@nestjs/common'; class CreateUserDto { name: string; email: string; } @Controller('users') @UsePipes(new ValidationPipe({ transform: true })) export class UsersController { @Post() create(@Body() createUserDto: CreateUserDto) { return createUserDto; } @Get(':id') findOne( @Param('id', ParseIntPipe) id: number, ) { return { id }; } } ``` ## AI Coding Instructions - Apply `@UsePipes()` at the controller level when the same validation or transformation behavior should affect every route in that controller. - Apply it at the method level for route-specific pipe behavior; method-level configuration should not be assumed to affect sibling handlers. - Pass pipe classes, instances, or multiple pipe arguments as supported by NestJS, such as `@UsePipes(ValidationPipe)` or `@UsePipes(new ValidationPipe())`. - Prefer DTO-based validation with `ValidationPipe` for request bodies, and use parameter pipes such as `ParseIntPipe` for targeted route parameter conversion. - Ensure validation pipes are configured consistently with application-wide pipe settings to avoid unexpected differences between routes. # ConsoleLoggerOptions **Kind:** Interface **Source:** [`packages/common/services/console-logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/console-logger.service.ts#L18) **Part of:** [Common](subsystem-packages-common) `ConsoleLoggerOptions` configures how the console logger formats and emits application log messages. It controls enabled log levels, timestamp and context metadata, JSON/color output, object inspection limits, and whether output is forced through the native console. ## Properties | Property | Type | |---|---| | `logLevels` | `LogLevel[]` | | `timestamp` | `boolean` | | `prefix` | `string` | | `json` | `boolean` | | `colors` | `boolean` | | `context` | `string` | | `forceConsole` | `boolean` | | `compact` | `boolean | number` | | `maxArrayLength` | `number` | | `maxStringLength` | `number` | | `sorted` | `boolean | ((a: string, b: string) => number)` | | `depth` | `number` | | `showHidden` | `boolean` | | `breakLength` | `number` | ## Diagram ```mermaid graph LR A[ConsoleLoggerOptions] --> B[Filtering] A --> C[Formatting] A --> D[Output Behavior] A --> E[Inspection Limits] B --> B1[logLevels: LogLevel[]] C --> C1[timestamp] C --> C2[prefix] C --> C3[context] C --> C4[json] C --> C5[colors] C --> C6[compact] D --> D1[forceConsole] E --> E1[maxArrayLength] E --> E2[maxStringLength] ``` ## Usage ```ts import type { ConsoleLoggerOptions } from '@nestjs/common'; const loggerOptions: ConsoleLoggerOptions = { logLevels: ['log', 'error', 'warn', 'debug'], timestamp: true, prefix: 'api', context: 'Bootstrap', json: false, colors: true, forceConsole: false, compact: true, maxArrayLength: 20, maxStringLength: 200, }; // Pass the options to the application's console logger configuration. console.log(loggerOptions); ``` ## AI Coding Instructions - Use `logLevels` to limit emitted messages; include `error` and `warn` in production configurations unless intentionally suppressing them. - Enable `json` for structured logging pipelines; avoid combining it with human-focused formatting expectations such as colorized terminal output. - Set `context` and `prefix` consistently so log entries can be traced back to their module, service, or application. - Use `maxArrayLength`, `maxStringLength`, and `compact` to prevent large objects or payloads from producing excessive console output. - Set `forceConsole` only when native console output is required instead of the framework's configured logging transport. # Dependencies **Kind:** Function **Source:** [`packages/common/decorators/core/dependencies.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/dependencies.decorator.ts#L17) **Part of:** [Common](subsystem-packages-common) Decorator that sets required dependencies (required with a vanilla JavaScript objects) `Dependencies` is a class decorator that declares the dependencies required by a decorated component using a plain JavaScript object. It stores this dependency information as metadata so the surrounding framework can inspect, validate, or provide the required values during integration. ## Signature ```ts function Dependencies(dependencies: Array): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `dependencies` | `Array` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[Plain dependency object] --> B[@Dependencies] B --> C[Decorated class] C --> D[Dependency metadata] D --> E[Framework dependency resolution or validation] ``` ## Usage ```ts import { Dependencies } from '@your-package/common'; const logger = { info(message: string) { console.log(message); }, }; const configuration = { apiUrl: 'https://api.example.com', }; @Dependencies({ logger, configuration, }) class ApiClient { fetchUsers() { logger.info(`Fetching users from ${configuration.apiUrl}`); } } const client = new ApiClient(); client.fetchUsers(); ``` ## AI Coding Instructions - Pass dependencies as a plain JavaScript object, using clear property names for each required value. - Apply `@Dependencies(...)` to the class that needs the dependency metadata available to the framework. - Keep dependency definitions stable and avoid creating unrelated runtime state inside the decorator argument. - Ensure dependency keys match the names expected by the consuming resolver, validator, or integration layer. - When extending dependency handling, preserve the metadata contract used by other core decorators. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `CatsController` — `sample/09-babel-example/src/cats/cats.controller.js`:12 # ExistingProvider **Kind:** Interface **Source:** [`packages/common/interfaces/modules/provider.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/provider.interface.ts#L157) **Part of:** [Common](subsystem-packages-common) Interface defining an *Existing* (aliased) type provider. For example: ```typescript const loggerAliasProvider = { provide: 'AliasedLoggerService', useExisting: LoggerService }; ``` `ExistingProvider` defines an alias for an already-registered dependency injection provider. Instead of creating a new instance, it maps a new `provide` token to the same instance represented by `useExisting`. ## Properties | Property | Type | |---|---| | `provide` | `InjectionToken` | | `useExisting` | `any` | ## Diagram ```mermaid graph LR A[Injection Token: AliasedLoggerService] --> B[ExistingProvider] B -->|useExisting| C[Existing Provider: LoggerService] C --> D[Shared LoggerService Instance] ``` ## Usage ```typescript import { ExistingProvider } from '@nestjs/common'; class LoggerService { log(message: string) { console.log(message); } } const loggerAliasProvider: ExistingProvider = { provide: 'AliasedLoggerService', useExisting: LoggerService, }; @Module({ providers: [LoggerService, loggerAliasProvider], }) export class AppModule {} ``` ## AI Coding Instructions - Use `useExisting` when multiple injection tokens must resolve to the exact same provider instance. - Ensure the target referenced by `useExisting` is registered in the same module or available through imported/exported modules. - Use a distinct `provide` token for the alias, such as a string, symbol, class, or custom injection token. - Do not use `useExisting` when a separate instance is required; use `useClass`, `useFactory`, or `useValue` instead. - Prefer aliases for backwards-compatible token migrations or interface-based dependency injection. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `InternalCoreModule` — `packages/core/injector/internal-core-module/internal-core-module.ts`:16 - `Module` — `packages/core/injector/module.ts`:44 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # HttpsOptions **Kind:** Interface **Source:** [`packages/common/interfaces/external/https-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/https-options.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) Interface describing Https Options that can be set. `HttpsOptions` defines the TLS/HTTPS configuration used when creating secure HTTP servers or clients. It supports certificates, private keys, certificate authorities, cipher configuration, and mutual TLS validation settings. ## Properties | Property | Type | |---|---| | `pfx` | `any` | | `key` | `any` | | `passphrase` | `string` | | `cert` | `any` | | `ca` | `any` | | `crl` | `any` | | `ciphers` | `string` | | `honorCipherOrder` | `boolean` | | `requestCert` | `boolean` | | `rejectUnauthorized` | `boolean` | | `NPNProtocols` | `any` | | `SNICallback` | `(servername: string, cb: (err: Error, ctx: any) => any) => any` | | `secureOptions` | `number` | ## Diagram ```mermaid graph LR HttpsOptions[HttpsOptions] HttpsOptions --> Certificates[Certificate material] HttpsOptions --> TLS[TLS configuration] HttpsOptions --> ClientAuth[Client authentication] Certificates --> PFX[pfx] Certificates --> Key[key] Certificates --> Cert[cert] Certificates --> CA[ca] Certificates --> CRL[crl] Certificates --> Passphrase[passphrase] TLS --> Ciphers[ciphers] TLS --> CipherOrder[honorCipherOrder] ClientAuth --> RequestCert[requestCert] ClientAuth --> RejectUnauthorized[rejectUnauthorized] ``` ## Usage ```ts import { readFileSync } from 'node:fs'; import type { HttpsOptions } from '@nestjs/common'; const httpsOptions: HttpsOptions = { key: readFileSync('./certs/server-key.pem'), cert: readFileSync('./certs/server-cert.pem'), ca: readFileSync('./certs/ca-cert.pem'), ciphers: 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256', honorCipherOrder: true, // Enable mutual TLS when clients must provide a trusted certificate. requestCert: true, rejectUnauthorized: true, }; ``` ## AI Coding Instructions - Provide either `pfx` or a matching `key` and `cert` pair; do not configure conflicting certificate sources unless the underlying HTTPS integration supports it. - Load certificate files as `Buffer` values, typically with `readFileSync`, rather than hardcoding sensitive certificate content. - Use `passphrase` only when the private key or PFX bundle is encrypted. - Set `requestCert` and `rejectUnauthorized` together when implementing mutual TLS; disabling authorization can allow untrusted client certificates. - Configure `ca` with the trusted issuer certificates required to validate client certificates or upstream TLS peers. # InvalidDecoratorItemException **Kind:** Class **Source:** [`packages/common/utils/validate-each.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/validate-each.util.ts#L1) **Part of:** [Common](subsystem-packages-common) `InvalidDecoratorItemException` represents an invalid item encountered while validating decorator metadata or decorator-provided collections. It provides a `what()` method that returns a human-readable diagnostic message, allowing validation and tooling code to report the failure consistently. **Extends:** `Error` ## Methods | Method | Signature | Returns | |---|---|---| | `what` | `what()` | `string` | ## Diagram ```mermaid graph LR A[Decorator metadata validation] --> B[Invalid decorator item detected] B --> C[InvalidDecoratorItemException] C --> D[what(): string] D --> E[Readable diagnostic message] ``` ## Usage ```ts import { InvalidDecoratorItemException } from '@nestjs/common'; try { // Run code that processes or validates decorator metadata. initializeApplicationMetadata(); } catch (error) { if (error instanceof InvalidDecoratorItemException) { console.error(`Decorator configuration error: ${error.what()}`); } throw error; } ``` ## AI Coding Instructions - Use `InvalidDecoratorItemException` for invalid decorator items rather than throwing generic `Error` instances. - Call `what()` when presenting the error in logs, diagnostics, or developer-facing validation output. - Preserve the original exception when catching it; avoid replacing it with a less specific error type. - Keep decorator validation failures actionable by ensuring invalid items can be identified by the surrounding validation logic. # MergeWithValues **Kind:** Function **Source:** [`packages/common/utils/merge-with-values.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/merge-with-values.util.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function MergeWithValues(data: { [param: string]: any; }) ``` ## Parameters | Name | Type | |---|---| | `data` | `{ [param: string]: any; }` | # ParseBoolPipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-bool.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-bool.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # ParseDatePipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-date.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-date.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # ParseEnumPipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-enum.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-enum.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # ParseFilePipe **Kind:** Pipe **Source:** [`packages/common/pipes/file/parse-file.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/parse-file.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # ParseFloatPipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-float.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-float.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # ParseUUIDPipe **Kind:** Pipe **Source:** [`packages/common/pipes/parse-uuid.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-uuid.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # PayloadTooLargeException **Kind:** Class **Source:** [`packages/common/exceptions/payload-too-large.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/payload-too-large.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Payload Too Large* type errors. `PayloadTooLargeException` represents an HTTP 413 error when a client sends a request body that exceeds the server’s accepted size limit. It extends NestJS’s HTTP exception system, producing a standardized error response that can be handled by the framework’s exception filters. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client sends request payload] --> Limit{Payload within allowed size?} Limit -->|Yes| Handler[Process request] Limit -->|No| Exception[PayloadTooLargeException] Exception --> Response[HTTP 413 Payload Too Large response] ``` ## Usage ```ts import { PayloadTooLargeException } from '@nestjs/common'; function validatePayloadSize(payload: string) { const maxBytes = 1024 * 1024; // 1 MB if (Buffer.byteLength(payload, 'utf8') > maxBytes) { throw new PayloadTooLargeException( 'Request payload must not exceed 1 MB', ); } } ``` ## AI Coding Instructions - Throw `PayloadTooLargeException` when a request body, uploaded content, or serialized payload exceeds an enforced size limit. - Prefer a clear client-facing message that explains the limit or how the request can be reduced. - Do not use this exception for malformed payloads; use a validation-oriented exception such as `BadRequestException` instead. - Configure body-parser or upload middleware limits alongside application-level checks, since middleware may reject oversized requests before controllers run. - Preserve NestJS exception patterns by throwing the exception rather than manually constructing HTTP 413 responses. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `transformException` — `packages/platform-express/multer/multer/multer.utils.ts`:10 # PreconditionFailedException **Kind:** Class **Source:** [`packages/common/exceptions/precondition-failed.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/precondition-failed.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Precondition Failed* type errors. `PreconditionFailedException` represents an HTTP 412 *Precondition Failed* error. Use it when a request cannot be completed because one or more client-supplied preconditions—such as an ETag, version, or conditional header—do not match the current resource state. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client request with precondition] --> Handler[Application handler] Handler --> Check{Precondition valid?} Check -->|Yes| Update[Process request] Check -->|No| Exception[PreconditionFailedException] Exception --> Response[HTTP 412 Precondition Failed response] ``` ## Usage ```ts import { PreconditionFailedException } from '@nestjs/common'; async function updateDocument( id: string, expectedVersion: number, content: string, ) { const document = await documentsService.findById(id); if (document.version !== expectedVersion) { throw new PreconditionFailedException( 'The document has changed since it was last retrieved.', ); } return documentsService.update(id, content); } ``` ## AI Coding Instructions - Throw this exception only when a request's explicit precondition fails, such as an ETag, `If-Match` header, or optimistic-lock version check. - Prefer a clear, client-actionable message that explains the resource must be refreshed before retrying. - Do not use this exception for validation errors; use the appropriate bad-request or validation exception instead. - Allow the framework exception filter to serialize the exception into the standard HTTP 412 response shape. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DurableService` — `integration/scopes/src/durable/durable.service.ts`:10 # Req **Kind:** Constant **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L783) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `Request` object from the underlying platform and populates the decorated parameter with the value of `Request`. Alias for `Req` is a route handler parameter decorator that injects the underlying platform request object into a controller method parameter. It is typically used when access to raw request details—such as headers, cookies, URL parameters, or platform-specific properties—is needed. ## Definition ```ts Request ``` ## Value ```ts Request ``` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Platform Adapter] B --> C[Controller Route Handler] C --> D[@Req() Decorated Parameter] D --> E[Request Object] ``` ## Usage ```ts import { Controller, Get, Req } from '@nestjs/common'; import type { Request } from 'express'; @Controller('users') export class UsersController { @Get('profile') getProfile(@Req() request: Request) { return { userAgent: request.headers['user-agent'], path: request.path, }; } } ``` ## AI Coding Instructions - Use `@Req()` only when the full underlying request object is required; prefer focused decorators such as `@Body()`, `@Param()`, or `@Headers()` for specific values. - Type the parameter using the request type provided by the active HTTP platform, such as Express `Request` or Fastify `FastifyRequest`. - Avoid coupling business logic directly to the raw request object; extract required values in the controller and pass them to services. - Remember that request properties may vary between HTTP adapters, so avoid relying on adapter-specific fields unless the application is intentionally platform-specific. ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `AppController` — `integration/nest-application/app-locals/src/app.controller.ts`:4 - `AppController` — `integration/nest-application/global-prefix/src/app.controller.ts`:3 - `ExpressController` — `integration/nest-application/raw-body/src/express.controller.ts`:4 - `FastifyController` — `integration/nest-application/raw-body/src/fastify.controller.ts`:4 - `PassthroughInterceptor` — `integration/nest-application/sse/src/app.controller.ts`:28 - `AppController` — `integration/nest-application/use-body-parser/src/app.controller.ts`:4 # RequestTimeoutException **Kind:** Class **Source:** [`packages/common/exceptions/request-timeout.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/request-timeout.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Request Timeout* type errors. `RequestTimeoutException` represents an HTTP 408 Request Timeout error. Use it when a client request exceeds an allowed processing or response time, allowing NestJS exception filters to return a standardized timeout response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[HTTP Client] --> Controller[Controller / Service] Controller -->|Request exceeds time limit| Timeout[RequestTimeoutException] Timeout --> Filter[NestJS Exception Filter] Filter -->|HTTP 408 Request Timeout| Client ``` ## Usage ```ts import { Controller, Get, RequestTimeoutException } from '@nestjs/common'; @Controller('reports') export class ReportsController { @Get() async generateReport() { const completedInTime = false; if (!completedInTime) { throw new RequestTimeoutException( 'Report generation exceeded the allowed request time.', ); } return { status: 'complete' }; } } ``` ## AI Coding Instructions - Throw `RequestTimeoutException` when the request cannot complete within an expected server-side time limit. - Prefer this exception over generic `HttpException` when the appropriate HTTP response is `408 Request Timeout`. - Include a clear, client-safe error message; avoid exposing internal timing, infrastructure, or dependency details. - Let NestJS's built-in exception handling serialize the exception unless the application uses a custom global exception filter. - For long-running work, consider asynchronous job processing or background queues instead of repeatedly extending request timeouts. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DisconnectedClientController` — `integration/microservices/src/disconnected.controller.ts`:12 # ConfigurableModuleHost **Kind:** Interface **Source:** [`packages/common/module-utils/interfaces/configurable-module-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/interfaces/configurable-module-host.interface.ts#L10) **Part of:** [Common](subsystem-packages-common) Configurable module host. See properties for more details `ConfigurableModuleHost` describes the object produced by NestJS's configurable module builder. It groups the generated module class, dependency-injection token, and TypeScript helper types needed to register a module synchronously or asynchronously. Use it as the contract between a module definition and the application code that imports and configures that module. ## Properties | Property | Type | |---|---| | `ConfigurableModuleClass` | `ConfigurableModuleCls< ModuleOptions, MethodKey, FactoryClassMethodKey, ExtraModuleDefinitionOptions >` | | `MODULE_OPTIONS_TOKEN` | `string | symbol` | | `ASYNC_OPTIONS_TYPE` | `ConfigurableModuleAsyncOptions< ModuleOptions, FactoryClassMethodKey > & Partial` | | `OPTIONS_TYPE` | `ModuleOptions & Partial` | ## Diagram ```mermaid graph LR Builder[ConfigurableModuleBuilder] --> Host[ConfigurableModuleHost] Host --> ModuleClass[ConfigurableModuleClass] Host --> Token[MODULE_OPTIONS_TOKEN] Host --> SyncType[OPTIONS_TYPE] Host --> AsyncType[ASYNC_OPTIONS_TYPE] ModuleClass --> Register[register(options)] ModuleClass --> RegisterAsync[registerAsync(options)] Register --> Token RegisterAsync --> Token ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ConfigurableModuleBuilder, ConfigurableModuleHost, } from '@nestjs/common'; interface MailerModuleOptions { apiKey: string; defaultFrom: string; } const mailerModuleHost: ConfigurableModuleHost = new ConfigurableModuleBuilder() .setClassMethodName('forRoot') .build(); export const { ConfigurableModuleClass: MailerModule, MODULE_OPTIONS_TOKEN: MAILER_OPTIONS, } = mailerModuleHost; @Module({}) export class AppModule { static register() { return { module: AppModule, imports: [ MailerModule.forRoot({ apiKey: process.env.MAILER_API_KEY!, defaultFrom: 'no-reply@example.com', }), ], }; } } ``` ## AI Coding Instructions - Create `ConfigurableModuleHost` instances through `ConfigurableModuleBuilder.build()` rather than constructing the interface manually. - Use `ConfigurableModuleClass` to expose generated registration methods such as `register`, `forRoot`, or `registerAsync`. - Inject configuration values with the generated `MODULE_OPTIONS_TOKEN`; do not replace it with a hard-coded string unless required for compatibility. - Treat `OPTIONS_TYPE` and `ASYNC_OPTIONS_TYPE` as compile-time type helpers, not runtime values. - Keep the module options type focused on public configuration and use extra module definition options only for module metadata customization. # ExceptionFilterMetadata **Kind:** Interface **Source:** [`packages/common/interfaces/exceptions/exception-filter-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/exceptions/exception-filter-metadata.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) `ExceptionFilterMetadata` describes the runtime metadata Nest uses to associate an exception filter handler with the exception classes it can process. It stores the filter's `catch` function alongside the exception metatypes registered through decorators such as `@Catch()`. ## Properties | Property | Type | |---|---| | `func` | `ExceptionFilter['catch']` | | `exceptionMetatypes` | `Type[]` | ## Diagram ```mermaid graph LR A["@Catch(HttpException)"] --> B["ExceptionFilterMetadata"] C["Exception Filter instance"] --> D["func: filter.catch"] A --> E["exceptionMetatypes: Type<any>[]"] D --> B E --> B B --> F["Exceptions handler selects matching filter"] ``` ## Usage ```ts import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'; import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface'; @Catch(HttpException) class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const response = host.switchToHttp().getResponse(); response.status(exception.getStatus()).json({ message: exception.message, }); } } const filter = new HttpExceptionFilter(); const metadata: ExceptionFilterMetadata = { func: filter.catch.bind(filter), exceptionMetatypes: [HttpException], }; ``` ## AI Coding Instructions - Keep `func` compatible with `ExceptionFilter['catch']`; bind it to the filter instance when invoking it outside Nest's normal filter context. - Populate `exceptionMetatypes` with exception constructors, such as `HttpException` or custom error classes, not instantiated exceptions. - Treat this interface as internal runtime metadata used by Nest's exception-handler resolution flow. - Preserve the relationship between a filter's `catch` handler and its declared `@Catch()` exception types when extending exception-filter infrastructure. ## How it works `ExceptionFilterMetadata` is an exported TypeScript interface for the two values needed to select and invoke an exception filter: a `catch` function and an array of exception constructor types. It declares no executable logic, validation, errors, or side effects itself. [exception-filter-metadata.interface.ts:4-7](packages/common/interfaces/exceptions/exception-filter-metadata.interface.ts#L4-L7) - `func` has the type of `ExceptionFilter['catch']`. That method receives an exception and an `ArgumentsHost`, and may return any value. [exception-filter-metadata.interface.ts:5](packages/common/interfaces/exceptions/exception-filter-metadata.interface.ts#L5) [exception-filter.interface.ts:10-18](packages/common/interfaces/exceptions/exception-filter.interface.ts#L10-L18) - `exceptionMetatypes` is an array of constructible function types (`Type`); `Type` extends `Function` and has a `new (...args)` signature. [exception-filter-metadata.interface.ts:6](packages/common/interfaces/exceptions/exception-filter-metadata.interface.ts#L6) [type.interface.ts:1-3](packages/common/interfaces/type.interface.ts#L1-L3) Filter-context construction creates metadata objects by binding each filter instance’s `catch` method to that instance and reading its catch-type metadata through reflection. [base-exception-filter-context.ts:26-36](packages/core/exceptions/base-exception-filter-context.ts#L26-L36) The `@Catch()` decorator writes the supplied exception types under the metadata key that this reflection reads. [catch.decorator.ts:21-27](packages/common/decorators/core/catch.decorator.ts#L21-L27) A filter can be registered through `@UseFilters()` as a class or instance; that decorator accepts functions or objects whose `catch` member is a function, otherwise it can throw `InvalidDecoratorItemException`. [exception-filters.decorator.ts:29-30](packages/common/decorators/core/exception-filters.decorator.ts#L29-L30) [exception-filters.decorator.ts:40-60](packages/common/decorators/core/exception-filters.decorator.ts#L40-L60) [validate-each.util.ts:23-29](packages/common/utils/validate-each.util.ts#L23-L29) When selecting metadata for an exception, `selectExceptionFilterMetadata()` returns the first entry whose `exceptionMetatypes` array is empty or contains a constructor for which the exception is an `instanceof`; it returns `undefined` when no entry matches. [select-exception-filter-metadata.util.ts:3-13](packages/common/utils/select-exception-filter-metadata.util.ts#L3-L13) `ExceptionsHandler` stores an array of these objects, invokes the selected entry’s `func(exception, ctx)`, and reports whether a matching entry existed. If no custom filter matches, its `next()` method delegates to the base exception handler. [exceptions-handler.ts:9-17](packages/core/exceptions/exceptions-handler.ts#L9-L17) [exceptions-handler.ts:26-37](packages/core/exceptions/exceptions-handler.ts#L26-L37) Its `setCustomFilters()` method requires the supplied value to be an array and throws `InvalidExceptionFilterException` otherwise; it does not inspect the shape of each array entry in the shown code. [exceptions-handler.ts:19-24](packages/core/exceptions/exceptions-handler.ts#L19-L24) ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ExceptionsHandler` — `packages/core/exceptions/exceptions-handler.ts`:9 - `ExternalExceptionFilterContext` — `packages/core/exceptions/external-exception-filter-context.ts`:14 - `ExternalExceptionsHandler` — `packages/core/exceptions/external-exceptions-handler.ts`:8 - `WsExceptionsHandler` — `packages/websockets/exceptions/ws-exceptions-handler.ts`:12 # INVALID_MODULE_CONFIG_MESSAGE **Kind:** Function **Source:** [`packages/common/utils/validate-module-keys.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/validate-module-keys.util.ts#L3) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function INVALID_MODULE_CONFIG_MESSAGE(text: TemplateStringsArray, property: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `property` | `string` | # RawBody **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L573) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `rawBody` Buffer property from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound rawBody parameter. For example: ```typescript async create(@RawBody(new ValidationPipe()) rawBody: Buffer) ``` `RawBody` is a route-handler parameter decorator that reads the `rawBody` `Buffer` from the request object. It binds that value to the decorated parameter and applies any pipes passed to the decorator. ## Signature ```ts function RawBody(pipes: ( | Type> | PipeTransform )[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `( | Type> | PipeTransform )[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> RawBodyProperty[req.rawBody] RawBodyProperty --> RawBodyDecorator["@RawBody()"] RawBodyDecorator --> Pipes[Configured pipes] Pipes --> HandlerParameter[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, RawBody, ValidationPipe } from '@nestjs/common'; @Controller('webhooks') export class WebhooksController { @Post() async handleWebhook( @RawBody(new ValidationPipe()) rawBody: Buffer, ): Promise { // Verify or process the original request payload. console.log(rawBody.toString()); } } ``` ## AI Coding Instructions - Use `@RawBody()` only when the request adapter has populated `req.rawBody` with the original payload buffer. - Keep the decorated parameter typed as `Buffer` so handlers process the unparsed request body. - Pass pipes to `@RawBody(...)` when the bound raw body requires validation or transformation. - Do not replace `@RawBody()` with parsed body access when signature verification depends on the original request bytes. # RawBody **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L573) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `rawBody` Buffer property from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound rawBody parameter. For example: ```typescript async create(@RawBody(new ValidationPipe()) rawBody: Buffer) ``` `RawBody` is a route-handler parameter decorator that reads the `rawBody` `Buffer` from the request object. It binds that value to the decorated parameter and applies any pipes passed to the decorator. ## Signature ```ts function RawBody(pipes: ( | Type> | PipeTransform )[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `( | Type> | PipeTransform )[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> RawBodyProperty[req.rawBody] RawBodyProperty --> RawBodyDecorator["@RawBody()"] RawBodyDecorator --> Pipes[Configured pipes] Pipes --> HandlerParameter[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, RawBody, ValidationPipe } from '@nestjs/common'; @Controller('webhooks') export class WebhooksController { @Post() async handleWebhook( @RawBody(new ValidationPipe()) rawBody: Buffer, ): Promise { // Verify or process the original request payload. console.log(rawBody.toString()); } } ``` ## AI Coding Instructions - Use `@RawBody()` only when the request adapter has populated `req.rawBody` with the original payload buffer. - Keep the decorated parameter typed as `Buffer` so handlers process the unparsed request body. - Pass pipes to `@RawBody(...)` when the bound raw body requires validation or transformation. - Do not replace `@RawBody()` with parsed body access when signature verification depends on the original request bytes. # RawBody **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L573) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `rawBody` Buffer property from the `req` object and populates the decorated parameter with that value. Also applies pipes to the bound rawBody parameter. For example: ```typescript async create(@RawBody(new ValidationPipe()) rawBody: Buffer) ``` `RawBody` is a route-handler parameter decorator that reads the `rawBody` `Buffer` from the request object. It binds that value to the decorated parameter and applies any pipes passed to the decorator. ## Signature ```ts function RawBody(pipes: ( | Type> | PipeTransform )[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `( | Type> | PipeTransform )[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request] --> RawBodyProperty[req.rawBody] RawBodyProperty --> RawBodyDecorator["@RawBody()"] RawBodyDecorator --> Pipes[Configured pipes] Pipes --> HandlerParameter[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, RawBody, ValidationPipe } from '@nestjs/common'; @Controller('webhooks') export class WebhooksController { @Post() async handleWebhook( @RawBody(new ValidationPipe()) rawBody: Buffer, ): Promise { // Verify or process the original request payload. console.log(rawBody.toString()); } } ``` ## AI Coding Instructions - Use `@RawBody()` only when the request adapter has populated `req.rawBody` with the original payload buffer. - Keep the decorated parameter typed as `Buffer` so handlers process the unparsed request body. - Pass pipes to `@RawBody(...)` when the bound raw body requires validation or transformation. - Do not replace `@RawBody()` with parsed body access when signature verification depends on the original request bytes. # ValidatorOptions **Kind:** Interface **Source:** [`packages/common/interfaces/external/validator-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/validator-options.interface.ts#L9) **Part of:** [Common](subsystem-packages-common) Options passed to validator during validation. `ValidatorOptions` configures how validation is performed for incoming objects. It controls property handling, validation groups, debug and default messages, and whether unknown properties are allowed or rejected. ## Properties | Property | Type | |---|---| | `enableDebugMessages` | `boolean` | | `skipUndefinedProperties` | `boolean` | | `skipNullProperties` | `boolean` | | `skipMissingProperties` | `boolean` | | `whitelist` | `boolean` | | `forbidNonWhitelisted` | `boolean` | | `groups` | `string[]` | | `always` | `boolean` | | `strictGroups` | `boolean` | | `dismissDefaultMessages` | `boolean` | | `validationError` | `{ target?: boolean; value?: boolean; }` | | `forbidUnknownValues` | `boolean` | | `stopAtFirstError` | `boolean` | ## Diagram ```mermaid graph LR A[Validation request] --> B[ValidatorOptions] B --> C[Property handling] B --> D[Validation groups] B --> E[Validation messages] B --> F[Whitelist behavior] C --> C1[skipUndefinedProperties] C --> C2[skipNullProperties] C --> C3[skipMissingProperties] D --> D1[groups] D --> D2[always] D --> D3[strictGroups] E --> E1[enableDebugMessages] E --> E2[dismissDefaultMessages] F --> F1[whitelist] F --> F2[forbidNonWhitelisted] ``` ## Usage ```ts import type { ValidatorOptions } from './interfaces/external/validator-options.interface'; const validatorOptions: ValidatorOptions = { whitelist: true, forbidNonWhitelisted: true, skipMissingProperties: false, skipUndefinedProperties: true, skipNullProperties: false, groups: ['create'], always: false, strictGroups: true, enableDebugMessages: process.env.NODE_ENV !== 'production', dismissDefaultMessages: false, }; // Pass the options to the validation layer or validator integration. const errors = await validate(createUserDto, validatorOptions); ``` ## AI Coding Instructions - Enable `whitelist` when validating DTOs or request payloads to prevent unrecognized input properties from being retained. - Use `forbidNonWhitelisted` together with `whitelist` when unknown properties should produce validation errors instead of being silently removed. - Choose only the skip option that matches the API contract: `skipUndefinedProperties`, `skipNullProperties`, and `skipMissingProperties` have different behaviors. - Use `groups` with `strictGroups` when validation decorators are explicitly scoped to operations such as `create` or `update`. - Keep `enableDebugMessages` disabled in production environments to avoid exposing implementation details in validation responses. # ClassTransformOptions **Kind:** Interface **Source:** [`packages/common/interfaces/external/class-transform-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/class-transform-options.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) Options to be passed during transformation. `ClassTransformOptions` defines configuration passed to class transformation operations, such as converting plain objects into class instances or serializing instances into plain data. It controls property exposure rules, groups, versioning, decorator behavior, circular-reference handling, and implicit type conversion. ## Properties | Property | Type | |---|---| | `strategy` | `'excludeAll' | 'exposeAll'` | | `groups` | `string[]` | | `version` | `number` | | `excludePrefixes` | `string[]` | | `ignoreDecorators` | `boolean` | | `targetMaps` | `any[]` | | `enableCircularCheck` | `boolean` | | `enableImplicitConversion` | `boolean` | | `excludeExtraneousValues` | `boolean` | | `exposeDefaultValues` | `boolean` | | `exposeUnsetFields` | `boolean` | ## Diagram ```mermaid graph LR A[Transformation Operation] --> B[ClassTransformOptions] B --> C[strategy
excludeAll | exposeAll] B --> D[groups and version] B --> E[excludePrefixes] B --> F[Decorator Controls] B --> G[Type Conversion] B --> H[Circular Reference Check] B --> I[Target Maps] F --> F1[ignoreDecorators] F --> F2[excludeExtraneousValues] F --> F3[exposeDefaultValues] G --> G1[enableImplicitConversion] ``` ## Usage ```ts import { plainToInstance } from 'class-transformer'; import type { ClassTransformOptions } from '@nestjs/common'; class CreateUserDto { name: string; age: number; } const options: ClassTransformOptions = { strategy: 'excludeAll', enableImplicitConversion: true, excludeExtraneousValues: true, groups: ['create'], version: 1, }; const payload = { name: 'Ada Lovelace', age: '36', internalToken: 'do-not-expose', }; const user = plainToInstance(CreateUserDto, payload, options); // With implicit conversion enabled, age can be converted to a number. console.log(user.age); ``` ## AI Coding Instructions - Pass `ClassTransformOptions` to transformation utilities consistently when converting request payloads, DTOs, or response objects. - Use `excludeExtraneousValues` with explicit exposure decorators to prevent undeclared input properties from being included. - Enable `enableImplicitConversion` only when automatic primitive conversion is intended; validate transformed values separately. - Use `groups` and `version` to support context-specific or versioned serialization without duplicating DTO classes. - Enable `enableCircularCheck` for object graphs that may contain circular references, noting that it can add processing overhead. # FileTypeValidatorOptions **Kind:** Type **Source:** [`packages/common/pipes/file/file-type.validator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/file-type.validator.ts#L13) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts { fileType: string | RegExp; errorMessage?: string | ((ctx: FileTypeValidatorContext) => string); skipMagicNumbersValidation?: boolean; fallbackToMimetype?: boolean; overrideMimeType?: boolean; } ``` # GetOrResolveOptions **Kind:** Interface **Source:** [`packages/common/interfaces/nest-application-context.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-application-context.interface.ts#L10) **Part of:** [Common](subsystem-packages-common) `GetOrResolveOptions` configures how a Nest application context looks up or resolves providers. Use `strict` to control whether resolution is limited to the current module context, and `each` to request all matching provider instances instead of a single result. ## Properties | Property | Type | |---|---| | `strict` | `boolean` | | `each` | `boolean` | ## Diagram ```mermaid graph LR A[Application Context] --> B[GetOrResolveOptions] B --> C[strict: boolean] B --> D[each: boolean] C --> E[Limit lookup to current module context] D --> F[Return one or all matching providers] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { GetOrResolveOptions } from '@nestjs/common'; const options: GetOrResolveOptions = { strict: false, each: true, }; const app = await NestFactory.createApplicationContext(AppModule); // Search across module boundaries and return every matching provider. const handlers = app.get(MyHandlerToken, options); handlers.forEach((handler) => handler.handle()); ``` ## AI Coding Instructions - Set `strict: true` when a provider must be resolved only from the current module context. - Use `strict: false` for cross-module provider lookup when providers are exported through imported modules. - Set `each: true` only when multiple providers may share the requested token; handle the returned collection accordingly. - Keep provider tokens and expected return types aligned, especially when using custom injection tokens. - Prefer explicit options when lookup behavior is important to avoid unintended module-boundary resolution. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `AbstractInstanceResolver` — `packages/core/injector/abstract-instance-resolver.ts`:12 - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 # isNumber **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L46) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isNumber(val: any): val is number ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is number` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `EventPattern` — `packages/microservices/decorators/event-pattern.decorator.ts`:21 - `GrpcMethodStreamingType` — `packages/microservices/decorators/message-pattern.decorator.ts`:22 - `transformPatternToRoute` — `packages/microservices/utils/transform-pattern.utils.ts`:21 # OnModuleDestroy **Kind:** Interface **Source:** [`packages/common/interfaces/hooks/on-destroy.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/hooks/on-destroy.interface.ts#L10) **Part of:** [Common](subsystem-packages-common) Interface defining method called just before Nest destroys the host module (`app.close()` method has been evaluated). Use to perform cleanup on resources (e.g., Database connections). `OnModuleDestroy` is a Nest lifecycle interface for providers, controllers, and modules that need to release resources before their host module is destroyed. Nest invokes `onModuleDestroy()` after `app.close()` begins shutdown, making it suitable for closing database connections, stopping background workers, or clearing external clients. ## Diagram ```mermaid graph LR A[Application calls app.close()] --> B[Nest starts module shutdown] B --> C[Provider implements OnModuleDestroy] C --> D[onModuleDestroy() is invoked] D --> E[Release resources
close connections / stop workers] E --> F[Host module is destroyed] ``` ## Usage ```ts import { Injectable, OnModuleDestroy } from '@nestjs/common'; @Injectable() export class DatabaseService implements OnModuleDestroy { private readonly connection = createDatabaseConnection(); async onModuleDestroy(): Promise { await this.connection.close(); } } function createDatabaseConnection() { return { async close() { console.log('Database connection closed'); }, }; } ``` ## AI Coding Instructions - Implement `OnModuleDestroy` on injectable providers that own resources requiring explicit cleanup. - Define an `onModuleDestroy()` method; it may be synchronous or return a `Promise`. - Close only resources owned by the current provider, such as database clients, message consumers, or timers. - Make cleanup safe to run once and avoid throwing unnecessary errors during application shutdown. - Ensure shutdown is initiated through `app.close()` so Nest can invoke lifecycle hooks. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `KafkaController` — `integration/microservices/src/kafka/kafka.controller.ts`:15 - `KafkaConcurrentController` — `integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`:24 - `DatabaseConnection` — `integration/repl/src/database/database.connection.ts`:3 - `callModuleDestroyHook` — `packages/core/hooks/on-module-destroy.hook.ts`:41 # UploadedFiles **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L303) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `files` object and populates the decorated parameter with the value of `files`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFiles() files) { console.log(files); } ``` `@UploadedFiles()` is a route handler parameter decorator for Express-based applications. It reads the `files` object attached by Multer middleware and assigns that value to the decorated handler parameter. ## Signature ```ts function UploadedFiles(pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Multer middleware] --> B[Request files object] B --> C[@UploadedFiles()] C --> D[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFiles, UseInterceptors } from '@nestjs/common'; import { FilesInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FilesInterceptor('files')) uploadFiles(@UploadedFiles() files: Express.Multer.File[]) { console.log(files); return files; } } ``` ## AI Coding Instructions - Apply `@UploadedFiles()` only to route handler parameters. - Register Multer middleware or a Nest file interceptor before reading the decorated parameter. - Expect the parameter value to match the `files` object created by the configured Multer middleware. - Use `@UploadedFile()` instead when the route accepts a single file rather than a files object. # UploadedFiles **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L303) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `files` object and populates the decorated parameter with the value of `files`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFiles() files) { console.log(files); } ``` `@UploadedFiles()` is a route handler parameter decorator for Express-based applications. It reads the `files` object attached by Multer middleware and assigns that value to the decorated handler parameter. ## Signature ```ts function UploadedFiles(pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Multer middleware] --> B[Request files object] B --> C[@UploadedFiles()] C --> D[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFiles, UseInterceptors } from '@nestjs/common'; import { FilesInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FilesInterceptor('files')) uploadFiles(@UploadedFiles() files: Express.Multer.File[]) { console.log(files); return files; } } ``` ## AI Coding Instructions - Apply `@UploadedFiles()` only to route handler parameters. - Register Multer middleware or a Nest file interceptor before reading the decorated parameter. - Expect the parameter value to match the `files` object created by the configured Multer middleware. - Use `@UploadedFile()` instead when the route accepts a single file rather than a files object. # UploadedFiles **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L303) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `files` object and populates the decorated parameter with the value of `files`. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications. For example: ```typescript uploadFile(@UploadedFiles() files) { console.log(files); } ``` `@UploadedFiles()` is a route handler parameter decorator for Express-based applications. It reads the `files` object attached by Multer middleware and assigns that value to the decorated handler parameter. ## Signature ```ts function UploadedFiles(pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Multer middleware] --> B[Request files object] B --> C[@UploadedFiles()] C --> D[Route handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFiles, UseInterceptors } from '@nestjs/common'; import { FilesInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FilesInterceptor('files')) uploadFiles(@UploadedFiles() files: Express.Multer.File[]) { console.log(files); return files; } } ``` ## AI Coding Instructions - Apply `@UploadedFiles()` only to route handler parameters. - Register Multer middleware or a Nest file interceptor before reading the decorated parameter. - Expect the parameter value to match the `files` object created by the configured Multer middleware. - Use `@UploadedFile()` instead when the route accepts a single file rather than a files object. # validateModuleKeys **Kind:** Function **Source:** [`packages/common/utils/validate-module-keys.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/validate-module-keys.util.ts#L15) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function validateModuleKeys(keys: string[]) ``` ## Parameters | Name | Type | |---|---| | `keys` | `string[]` | # BadGatewayException **Kind:** Class **Source:** [`packages/common/exceptions/bad-gateway.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/bad-gateway.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Bad Gateway* type errors. `BadGatewayException` represents an HTTP 502 Bad Gateway error, typically used when an upstream service, proxy, or gateway returns an invalid response. It extends the framework's HTTP exception handling so the error is converted into a consistent HTTP response for clients. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Controller or Service] -->|throws| B[BadGatewayException] B --> C[HTTP Exception Handler] C --> D[HTTP 502 Bad Gateway Response] D --> E[Client] ``` ## Usage ```ts import { BadGatewayException, Injectable } from '@nestjs/common'; @Injectable() export class PaymentService { async chargeCustomer() { const response = await fetch('https://payments.example.com/charge'); if (!response.ok) { throw new BadGatewayException( 'The payment provider returned an invalid response.', ); } return response.json(); } } ``` ## AI Coding Instructions - Throw `BadGatewayException` when a failure originates from an upstream dependency, such as an external API, reverse proxy, or service gateway. - Do not use this exception for client validation failures; use appropriate 4xx exceptions for invalid requests or authorization issues. - Provide a client-safe error message and avoid exposing upstream response bodies, credentials, or internal infrastructure details. - Allow the framework's global exception filter to serialize the exception into a standard HTTP 502 response. # ConflictException **Kind:** Class **Source:** [`packages/common/exceptions/conflict.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/conflict.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Conflict* type errors. `ConflictException` represents an HTTP 409 Conflict error. Use it when a request cannot be completed because it conflicts with the current state of a resource, such as attempting to create a record that already exists. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Application logic] -->|Detects conflicting state| B[ConflictException] B --> C[HTTP exception handler] C -->|HTTP 409 Conflict response| D[Client] ``` ## Usage ```ts import { ConflictException } from '@nestjs/common'; async function createUser(email: string) { const existingUser = await usersRepository.findByEmail(email); if (existingUser) { throw new ConflictException( `A user with email "${email}" already exists.`, ); } return usersRepository.create({ email }); } ``` ## AI Coding Instructions - Throw `ConflictException` only for resource-state conflicts, such as duplicate unique fields or incompatible concurrent updates. - Prefer a clear, client-safe error message that explains which conflict occurred without exposing sensitive data. - Do not use this exception for validation failures; use a bad-request or validation-specific exception instead. - Let the framework’s global exception handling convert the exception into the standard HTTP 409 response. # EXCEPTION_FILTERS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L25) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__exceptionFilters__' ``` ## Value ```ts '__exceptionFilters__' ``` ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `RouterExceptionFilters` — `packages/core/router/router-exception-filters.ts`:14 - `ExternalExceptionFilterContext` — `packages/core/exceptions/external-exception-filter-context.ts`:14 - `DependenciesScanner` — `packages/core/scanner.ts`:75 - `ExceptionFiltersContext` — `packages/microservices/context/exception-filters-context.ts`:16 - `ExceptionFiltersContext` — `packages/websockets/context/exception-filters-context.ts`:10 # GatewayTimeoutException **Kind:** Class **Source:** [`packages/common/exceptions/gateway-timeout.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/gateway-timeout.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Gateway Timeout* type errors. `GatewayTimeoutException` represents an HTTP 504 Gateway Timeout error. Use it when an upstream service, proxy, or gateway does not respond within the expected time, allowing the application’s exception handling layer to return a consistent HTTP error response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Application Handler] --> B[Calls Upstream Service] B -->|Request times out| C[GatewayTimeoutException] C --> D[Global Exception Filter] D --> E[HTTP 504 Gateway Timeout Response] ``` ## Usage ```ts import { GatewayTimeoutException } from '@nestjs/common'; async function fetchInventory(productId: string) { try { return await inventoryClient.get(`/products/${productId}`, { timeout: 5_000, }); } catch (error) { if (error.code === 'ECONNABORTED') { throw new GatewayTimeoutException( 'The inventory service did not respond in time.', ); } throw error; } } ``` ## AI Coding Instructions - Throw `GatewayTimeoutException` when an upstream dependency exceeds its configured response deadline. - Use this exception for HTTP 504 scenarios; do not use it for client request timeouts or malformed requests. - Include a safe, actionable message without exposing upstream credentials, internal URLs, or sensitive error details. - Ensure HTTP clients and service integrations define explicit timeout values so timeout failures can be handled consistently. - Allow the framework’s global exception filter to serialize the exception into the standard HTTP error response. # GoneException **Kind:** Class **Source:** [`packages/common/exceptions/gone.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/gone.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Gone* type errors. `GoneException` represents an HTTP **410 Gone** error, indicating that a requested resource previously existed but is no longer available. Use it in application services or controllers when a resource has been permanently removed and clients should not retry the same request expecting it to reappear. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client Request] --> Controller[Controller or Service] Controller --> Check{Resource permanently removed?} Check -- Yes --> Gone[GoneException] Gone --> Response[HTTP 410 Gone Response] Check -- No --> Normal[Continue normal handling] ``` ## Usage ```ts import { GoneException } from '@nestjs/common'; async function getArchivedDocument(id: string) { const document = await documentRepository.findById(id); if (!document || document.isPermanentlyDeleted) { throw new GoneException(`Document "${id}" is no longer available`); } return document; } ``` ## AI Coding Instructions - Throw `GoneException` only when a resource is known to be permanently unavailable; use `NotFoundException` when its existence is unknown. - Include a clear message or response body that helps clients understand why the resource cannot be retrieved. - Use this exception in controller or service flows where the framework can translate it into an HTTP 410 response. - Do not use HTTP 410 for temporary unavailability; prefer appropriate retryable error handling for transient failures. # HttpVersionNotSupportedException **Kind:** Class **Source:** [`packages/common/exceptions/http-version-not-supported.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http-version-not-supported.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Http Version Not Supported* type errors. `HttpVersionNotSupportedException` represents an HTTP 505 error, indicating that the server does not support the HTTP protocol version used by the client request. It extends Nest's HTTP exception system so the framework can serialize the error into a standard HTTP response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client Request] --> VersionCheck[HTTP Version Validation] VersionCheck -->|Supported| Handler[Request Handler] VersionCheck -->|Unsupported| Exception[HttpVersionNotSupportedException] Exception --> Response[HTTP 505 Response] ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { HttpVersionNotSupportedException } from '@nestjs/common'; @Controller('protocol') export class ProtocolController { @Get() getProtocolInfo(): string { const clientHttpVersion = 'HTTP/0.9'; if (clientHttpVersion !== 'HTTP/1.1' && clientHttpVersion !== 'HTTP/2') { throw new HttpVersionNotSupportedException( `HTTP version "${clientHttpVersion}" is not supported.`, ); } return 'Supported HTTP version.'; } } ``` ## AI Coding Instructions - Throw `HttpVersionNotSupportedException` when request processing detects an unsupported HTTP protocol version. - Provide a clear message or response body that identifies the unsupported version without exposing sensitive server configuration. - Prefer framework-level protocol validation when available; use this exception for application-specific compatibility checks. - Do not use this exception for malformed requests or unsupported media types; use the corresponding HTTP exception type instead. # ImATeapotException **Kind:** Class **Source:** [`packages/common/exceptions/im-a-teapot.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/im-a-teapot.exception.ts#L14) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *ImATeapotException* type errors. Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. `ImATeapotException` represents the HTTP `418 I'm a Teapot` response defined for requests that cannot be fulfilled because a teapot was asked to brew coffee. It extends the framework’s HTTP exception system so controllers, guards, or services can return a consistent status code and response body for this intentionally humorous but standardized error case. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B{Request asks teapot
to brew coffee?} B -- Yes --> C[Throw ImATeapotException] C --> D[HTTP Exception Handler] D --> E[418 I'm a Teapot Response] B -- No --> F[Continue normal processing] ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { ImATeapotException } from '@nestjs/common'; @Controller('coffee') export class CoffeeController { @Get('brew') brewCoffee() { const appliance = 'teapot'; if (appliance === 'teapot') { throw new ImATeapotException( 'A teapot cannot brew coffee. The response body may be short and stout.', ); } return { status: 'brewing' }; } } ``` ## AI Coding Instructions - Throw `ImATeapotException` only when the intended HTTP response is `418 I'm a Teapot`. - Provide a concise response message or body when useful; callers may rely on the exception’s standard HTTP status code. - Prefer framework exception handling over manually constructing a `Response` with status `418`. - Use this exception in controllers or service-layer validation paths where the request is semantically inappropriate, not for general client errors. # Injectable **Kind:** Function **Source:** [`packages/common/decorators/core/injectable.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/injectable.decorator.ts#L43) **Part of:** [Common](subsystem-packages-common) Decorator that marks a class as a [provider](https://docs.nestjs.com/providers). Providers can be injected into other classes via constructor parameter injection using Nest's built-in [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection) system. When injecting a provider, it must be visible within the module scope (loosely speaking, the containing module) of the class it is being injected into. This can be done by: - defining the provider in the same module scope - exporting the provider from one module scope and importing that module into the module scope of the class being injected into - exporting the provider from a module that is marked as global using the `@Global()` decorator Providers can also be defined in a more explicit and imperative form using various [custom provider](https://docs.nestjs.com/fundamentals/custom-providers) techniques that expose more capabilities of the DI system. `@Injectable()` marks a class as a Nest provider, allowing Nest's dependency injection container to create and inject it into other classes. Providers must be registered in a module and visible in the consuming class's module scope through local registration, module imports/exports, or a global module. ## Signature ```ts function Injectable(options: InjectableOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `options` | `InjectableOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Service["@Injectable()
UsersService"] --> Module["UsersModule providers"] Module --> Container["Nest DI Container"] Container --> Consumer["UsersController
constructor(usersService)"] ``` ## Usage ```ts import { Controller, Get, Injectable, Module } from '@nestjs/common'; @Injectable() export class UsersService { findAll() { return ['Ada', 'Grace']; } } @Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {} @Get() findAll() { return this.usersService.findAll(); } } @Module({ controllers: [UsersController], providers: [UsersService], }) export class UsersModule {} ``` ## AI Coding Instructions - Apply `@Injectable()` to classes intended to be instantiated and managed by Nest's DI container. - Register injectable classes in a module's `providers` array before injecting them elsewhere. - Export providers from their defining module and import that module where the provider is consumed across module boundaries. - Use constructor injection for dependencies; avoid manually instantiating injectable providers with `new`. - Prefer custom provider definitions when a dependency requires a token, factory, value, alias, or custom scope. # MethodNotAllowedException **Kind:** Class **Source:** [`packages/common/exceptions/method-not-allowed.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/method-not-allowed.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Method Not Allowed* type errors. `MethodNotAllowedException` represents an HTTP 405 error when a request uses a method that is not supported by a route or resource. It integrates with the common exception handling system so unsupported methods can be converted into a consistent HTTP error response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[HTTP Client] --> Request[Request with unsupported method] Request --> Route[Route/Controller] Route --> Exception[MethodNotAllowedException] Exception --> Handler[Global Exception Handler] Handler --> Response[HTTP 405 Method Not Allowed] ``` ## Usage ```ts import { MethodNotAllowedException } from '@nestjs/common'; function updateUser(requestMethod: string) { if (requestMethod !== 'PATCH') { throw new MethodNotAllowedException( `Method ${requestMethod} is not allowed for this resource.`, ); } return { updated: true }; } ``` ## AI Coding Instructions - Throw `MethodNotAllowedException` when a route exists but does not support the incoming HTTP method. - Prefer framework routing configuration for normal method enforcement; use this exception for explicit runtime validation or custom dispatching. - Include a clear error message when the allowed method or resource context helps API consumers diagnose the issue. - Do not use this exception for missing routes; use a not-found exception when no matching resource or endpoint exists. # MiddlewareConfigProxy **Kind:** Interface **Source:** [`packages/common/interfaces/middleware/middleware-config-proxy.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/middleware/middleware-config-proxy.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `MiddlewareBuilder` — `packages/core/middleware/builder.ts`:17 # MiddlewareConfiguration **Kind:** Interface **Source:** [`packages/common/interfaces/middleware/middleware-configuration.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/middleware/middleware-configuration.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) `MiddlewareConfiguration` defines how a middleware component is bound to one or more application routes. It pairs a middleware class or instance with route targets expressed as controllers, path strings, or `RouteInfo` objects. ## Properties | Property | Type | |---|---| | `middleware` | `T` | | `forRoutes` | `(Type | string | RouteInfo)[]` | ## Diagram ```mermaid graph LR MC[MiddlewareConfiguration] M[middleware: T] FR[forRoutes: Route Targets] C[Controller Type] P[Path String] RI[RouteInfo] MC --> M MC --> FR FR --> C FR --> P FR --> RI ``` ## Usage ```ts import { MiddlewareConfiguration, RouteInfo } from '@nestjs/common'; class LoggerMiddleware { use(req: Request, res: Response, next: () => void) { console.log(`${req.method} ${req.url}`); next(); } } const configuration: MiddlewareConfiguration = { middleware: LoggerMiddleware, forRoutes: [ 'users', { path: 'admin', method: RequestMethod.ALL } as RouteInfo, ], }; ``` ## AI Coding Instructions - Set `middleware` to the middleware class, function, or compatible middleware value expected by the consuming configuration API. - Use `forRoutes` to target controllers, route path strings, or `RouteInfo` objects with explicit HTTP method matching. - Prefer `RouteInfo` when middleware should apply only to a specific HTTP method rather than every method for a path. - Ensure route strings and controller references match the routes registered by the application module. - Keep middleware configuration close to module setup so route bindings remain discoverable and maintainable. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `MiddlewareBuilder` — `packages/core/middleware/builder.ts`:17 - `moduleName` — `packages/core/middleware/container.ts`:68 - `handler` — `packages/core/middleware/middleware-module.ts`:287 # MisdirectedException **Kind:** Class **Source:** [`packages/common/exceptions/misdirected.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/misdirected.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Misdirected* type errors. `MisdirectedException` represents an HTTP `421 Misdirected Request` error, indicating that a request was sent to a server or connection that cannot serve the requested resource. Use it when request routing, host validation, or connection-level handling determines that the request should be handled by a different server or endpoint. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B{Request targets correct server?} B -- Yes --> C[Continue request handling] B -- No --> D[Throw MisdirectedException] D --> E[HTTP 421 Misdirected Request Response] ``` ## Usage ```ts import { Controller, Get, Headers } from '@nestjs/common'; import { MisdirectedException } from '@nestjs/common'; @Controller('api') export class ApiController { @Get() getData(@Headers('host') host?: string) { if (host !== 'api.example.com') { throw new MisdirectedException( 'This request was sent to the wrong host.', ); } return { message: 'Request handled successfully.' }; } } ``` ## AI Coding Instructions - Throw `MisdirectedException` only for HTTP `421` scenarios, such as invalid host routing or requests received by the wrong server connection. - Prefer a clear, client-safe error message that explains why the request cannot be handled by the current target. - Do not use this exception for missing routes, authorization failures, or generic proxy errors; use the corresponding HTTP exception instead. - Ensure reverse-proxy, gateway, and host-header validation logic consistently identifies the expected target before throwing this exception. # NotAcceptableException **Kind:** Class **Source:** [`packages/common/exceptions/not-acceptable.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/not-acceptable.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Not Acceptable* type errors. `NotAcceptableException` represents an HTTP 406 *Not Acceptable* error. Use it when the server cannot provide a response that satisfies the client’s requested representation, such as an unsupported `Accept` header or response format. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client request
Accept header] --> Handler[Controller or service] Handler --> Validation{Requested format supported?} Validation -->|Yes| Response[Return compatible response] Validation -->|No| Exception[NotAcceptableException] Exception --> HttpResponse[HTTP 406 Not Acceptable] ``` ## Usage ```ts import { Controller, Get, Headers, NotAcceptableException } from '@nestjs/common'; @Controller('reports') export class ReportsController { @Get() getReport(@Headers('accept') accept?: string) { if (accept && !accept.includes('application/json')) { throw new NotAcceptableException( 'This endpoint only supports application/json responses.', ); } return { id: 'report-123', format: 'json', }; } } ``` ## AI Coding Instructions - Throw `NotAcceptableException` when content negotiation fails and no acceptable response representation can be returned. - Prefer a clear, client-safe error message that identifies the unsupported requested format or media type. - Use this exception for HTTP 406 scenarios; use `UnsupportedMediaTypeException` for unsupported request body `Content-Type` values. - Allow NestJS exception filters to serialize the exception unless the application requires a custom error-response format. # NotImplementedException **Kind:** Class **Source:** [`packages/common/exceptions/not-implemented.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/not-implemented.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Not Implemented* type errors. `NotImplementedException` represents an HTTP 501 *Not Implemented* error. Use it when an endpoint, feature, or operation is recognized by the application but is not currently supported or available. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Client Request] --> B[Controller or Service] B --> C{Feature Implemented?} C -- No --> D[Throw NotImplementedException] D --> E[HTTP 501 Response] C -- Yes --> F[Continue Processing] ``` ## Usage ```ts import { NotImplementedException } from '@nestjs/common'; export class ReportsService { exportReport(format: string) { if (format === 'xml') { throw new NotImplementedException( 'XML report exports are not implemented yet.', ); } return this.generateSupportedReport(format); } private generateSupportedReport(format: string) { return { format, status: 'generated' }; } } ``` ## AI Coding Instructions - Throw `NotImplementedException` only for recognized functionality that is intentionally unavailable, resulting in an HTTP 501 response. - Prefer a clear, user-facing message that identifies the unsupported feature or operation. - Do not use this exception for missing resources; use `NotFoundException` when an entity does not exist. - Do not use it for invalid client input; use validation or `BadRequestException` for unsupported request values. - Let framework exception handling serialize the exception into the standard HTTP error response rather than manually constructing a response. # RpcExceptionFilter **Kind:** Interface **Source:** [`packages/common/interfaces/exceptions/rpc-exception-filter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/exceptions/rpc-exception-filter.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) Interface describing implementation of an RPC exception filter. `RpcExceptionFilter` defines the contract for handling exceptions thrown during RPC and microservice message processing. Implementations receive the thrown exception and execution context, then return an RxJS `Observable` representing the error response sent through the configured transport. ## Diagram ```mermaid graph LR A[RPC Request] --> B[Message Handler] B -->|Throws exception| C[RpcExceptionFilter] C --> D[catch exception, host] D --> E[Observable Error Response] E --> F[RPC Client / Transport] ``` ## Usage ```ts import { ArgumentsHost, Catch, RpcExceptionFilter } from '@nestjs/common'; import { RpcException } from '@nestjs/microservices'; import { Observable, throwError } from 'rxjs'; @Catch(RpcException) export class RpcErrorFilter implements RpcExceptionFilter { catch(exception: RpcException, host: ArgumentsHost): Observable { const rpcContext = host.switchToRpc(); const request = rpcContext.getData(); console.error('RPC request failed:', request, exception.getError()); return throwError(() => exception.getError()); } } ``` ## AI Coding Instructions - Implement `catch(exception, host)` and always return an RxJS `Observable`; use `throwError` when propagating an RPC error. - Use `host.switchToRpc()` to access RPC-specific data, context, or transport arguments instead of HTTP request/response APIs. - Prefer throwing or handling `RpcException` instances in microservice handlers so transport-compatible error payloads are preserved. - Register custom filters through `@UseFilters()` or as global microservice exception filters, depending on the required scope. - Avoid returning plain objects or promises directly from `catch`; the interface expects an observable response. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `BaseRpcExceptionFilter` — `packages/microservices/exceptions/base-rpc-exception-filter.ts`:15 - `ExceptionFilter` — `sample/03-microservices/src/common/filters/rpc-exception.filter.ts`:5 # ServiceUnavailableException **Kind:** Class **Source:** [`packages/common/exceptions/service-unavailable.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/service-unavailable.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Service Unavailable* type errors. `ServiceUnavailableException` represents an HTTP 503 Service Unavailable error. Use it when a request cannot be fulfilled because a dependency, downstream service, or the application itself is temporarily unavailable. It integrates with the framework's exception handling pipeline to produce a consistent HTTP error response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Request Handler] --> B{Required service available?} B -->|Yes| C[Return successful response] B -->|No| D[Throw ServiceUnavailableException] D --> E[Exception Filter] E --> F[HTTP 503 Service Unavailable Response] ``` ## Usage ```ts import { ServiceUnavailableException } from '@nestjs/common'; async function fetchInventory(productId: string) { const inventoryService = await getInventoryService(); if (!inventoryService.isAvailable()) { throw new ServiceUnavailableException( 'Inventory service is temporarily unavailable', ); } return inventoryService.getStock(productId); } ``` ## AI Coding Instructions - Throw `ServiceUnavailableException` only for temporary availability failures that should return HTTP status `503`. - Include a clear, client-safe message describing the unavailable dependency or service state. - Prefer this exception over generic internal-server errors when retries may succeed after the service recovers. - Ensure upstream health checks, circuit breakers, or dependency clients surface availability failures consistently. # UnprocessableEntityException **Kind:** Class **Source:** [`packages/common/exceptions/unprocessable-entity.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/unprocessable-entity.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Unprocessable Entity* type errors. `UnprocessableEntityException` represents an HTTP 422 error, used when a request is syntactically valid but cannot be processed because its content fails validation or violates business rules. It extends the framework’s HTTP exception infrastructure so controllers and services can return consistent client-facing error responses. **Extends:** `HttpException` ## Diagram ```mermaid graph LR Client[Client Request] --> Controller[Controller / Service] Controller --> Validation{Valid request content?} Validation -->|No| Exception[UnprocessableEntityException] Exception --> Response[HTTP 422 Response] Validation -->|Yes| Handler[Continue processing] ``` ## Usage ```ts import { UnprocessableEntityException } from '@nestjs/common'; function updateProfile(input: { email: string }) { if (!input.email.includes('@')) { throw new UnprocessableEntityException( 'A valid email address is required.', ); } return { updated: true }; } ``` ## AI Coding Instructions - Throw `UnprocessableEntityException` when request data is structurally valid but fails semantic validation or business-rule checks. - Prefer clear, actionable error messages that help API consumers correct the invalid input. - Use HTTP 422 instead of `BadRequestException` when the request format is valid but a field value or state prevents processing. - Allow the application’s global exception filter to serialize the exception into the standard HTTP error response format. # UnsupportedMediaTypeException **Kind:** Class **Source:** [`packages/common/exceptions/unsupported-media-type.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/unsupported-media-type.exception.ts#L11) **Part of:** [Common](subsystem-packages-common) Defines an HTTP exception for *Unsupported Media Type* type errors. `UnsupportedMediaTypeException` represents an HTTP 415 error, indicating that the server cannot process a request because its `Content-Type` is unsupported. It is typically thrown by controllers, guards, or middleware during request validation so NestJS can return a standardized HTTP error response. **Extends:** `HttpException` ## Diagram ```mermaid graph LR A[Client request] --> B[Content-Type validation] B -->|Supported media type| C[Controller handler] B -->|Unsupported media type| D[UnsupportedMediaTypeException] D --> E[HTTP 415 response] ``` ## Usage ```ts import { Controller, Post, Headers, UnsupportedMediaTypeException, } from '@nestjs/common'; @Controller('uploads') export class UploadController { @Post() upload(@Headers('content-type') contentType?: string) { if (!contentType?.startsWith('image/png')) { throw new UnsupportedMediaTypeException( 'Only image/png uploads are supported.', ); } return { message: 'Upload accepted' }; } } ``` ## AI Coding Instructions - Throw this exception when validation fails specifically because the request media type or `Content-Type` header is unsupported. - Prefer HTTP 415 over `BadRequestException` when the request body format is valid but its declared media type is not accepted. - Validate media types with `startsWith()` when parameters such as `charset` or multipart boundaries may be present. - Provide a clear error message describing the accepted media types for API consumers. - Use NestJS exception filters or the default exception handling pipeline rather than manually constructing HTTP 415 responses. # ConfigurableModuleAsyncOptions **Kind:** Interface **Source:** [`packages/common/module-utils/interfaces/configurable-module-async-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/interfaces/configurable-module-async-options.interface.ts#L29) **Part of:** [Common](subsystem-packages-common) Interface that represents the module async options object Factory method name varies depending on the "FactoryClassMethodKey" type argument. `ConfigurableModuleAsyncOptions` defines how a configurable module resolves its options asynchronously during module registration. It supports options provided by an existing factory, a newly instantiated factory class, or an inline factory function, with optional dependency injection for factory arguments. ## Properties | Property | Type | |---|---| | `useExisting` | `Type< ConfigurableModuleOptionsFactory >` | | `useClass` | `Type< ConfigurableModuleOptionsFactory >` | | `useFactory` | `(...args: any[]) => Promise | ModuleOptions` | | `inject` | `FactoryProvider['inject']` | | `provideInjectionTokensFrom` | `Provider[]` | ## Diagram ```mermaid graph LR A[ConfigurableModuleAsyncOptions] --> B{Options source} B --> C[useExisting] B --> D[useClass] B --> E[useFactory] C --> F[ConfigurableModuleOptionsFactory] D --> F E --> G[ModuleOptions] H[inject] --> E I[provideInjectionTokensFrom] --> H F --> G ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ConfigurableModuleAsyncOptions } from '@nestjs/common'; interface DatabaseModuleOptions { host: string; port: number; } @Injectable() class DatabaseConfigService { getDatabaseOptions(): DatabaseModuleOptions { return { host: 'localhost', port: 5432, }; } } const asyncOptions: ConfigurableModuleAsyncOptions = { inject: [DatabaseConfigService], useFactory: (configService: DatabaseConfigService) => { return configService.getDatabaseOptions(); }, }; // Example module registration: // DatabaseModule.registerAsync(asyncOptions); ``` ## AI Coding Instructions - Use exactly one options strategy: `useFactory`, `useClass`, or `useExisting`; avoid combining factory sources unless the consuming module explicitly supports it. - Add all dependencies required by `useFactory` to `inject`, preserving the same parameter order as the factory function. - Use `useExisting` when a compatible options factory is already registered as a provider; use `useClass` when the module should create the factory provider. - Ensure factory methods return `ModuleOptions` or `Promise` and match the method key expected by `FactoryClassMethodKey`. - Use `provideInjectionTokensFrom` when injection tokens must be collected from additional providers before resolving factory dependencies. # DefaultValuePipe **Kind:** Pipe **Source:** [`packages/common/pipes/default-value.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/default-value.pipe.ts#L1) **Part of:** [Common](subsystem-packages-common) # HostParam **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L764) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `hosts` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@HostParam() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@HostParam('id') id: string) ``` `HostParam()` binds a route handler parameter to values extracted from the request host and stored on `req.hosts`. Pass a host parameter name to read one value, or omit the name to receive the full host parameter object; pipes can transform or validate the bound value. ## Signature ```ts function HostParam(property: string | (Type | PipeTransform)): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request host] --> Matcher[Host route matcher] Matcher --> Hosts[req.hosts] Hosts --> Decorator["@HostParam()"] Decorator --> Handler[Route handler parameter] Decorator --> Pipes[Pipes] Pipes --> Handler ``` ## Usage ```typescript import { Controller, Get, HostParam } from '@nestjs/common'; @Controller({ host: ':account.example.com' }) export class AccountController { @Get() findAccount(@HostParam('account') account: string) { return { account }; } @Get('host-params') findHostParams(@HostParam() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@HostParam('name')` when the controller host pattern defines a named parameter such as `:account`. - Use `@HostParam()` when the handler needs every value from `req.hosts`. - Keep host parameter names aligned with the names declared in the controller host pattern. - Add pipes as additional decorator arguments when the bound host value needs validation or transformation. # HostParam **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L764) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `hosts` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@HostParam() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@HostParam('id') id: string) ``` `HostParam()` binds a route handler parameter to values extracted from the request host and stored on `req.hosts`. Pass a host parameter name to read one value, or omit the name to receive the full host parameter object; pipes can transform or validate the bound value. ## Signature ```ts function HostParam(property: string | (Type | PipeTransform)): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request host] --> Matcher[Host route matcher] Matcher --> Hosts[req.hosts] Hosts --> Decorator["@HostParam()"] Decorator --> Handler[Route handler parameter] Decorator --> Pipes[Pipes] Pipes --> Handler ``` ## Usage ```typescript import { Controller, Get, HostParam } from '@nestjs/common'; @Controller({ host: ':account.example.com' }) export class AccountController { @Get() findAccount(@HostParam('account') account: string) { return { account }; } @Get('host-params') findHostParams(@HostParam() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@HostParam('name')` when the controller host pattern defines a named parameter such as `:account`. - Use `@HostParam()` when the handler needs every value from `req.hosts`. - Keep host parameter names aligned with the names declared in the controller host pattern. - Add pipes as additional decorator arguments when the bound host value needs validation or transformation. # HostParam **Kind:** Function **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L764) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `hosts` property from the `req` object and populates the decorated parameter with the value of `params`. May also apply pipes to the bound parameter. For example, extracting all params: ```typescript findOne(@HostParam() params: string[]) ``` For example, extracting a single param: ```typescript findOne(@HostParam('id') id: string) ``` `HostParam()` binds a route handler parameter to values extracted from the request host and stored on `req.hosts`. Pass a host parameter name to read one value, or omit the name to receive the full host parameter object; pipes can transform or validate the bound value. ## Signature ```ts function HostParam(property: string | (Type | PipeTransform)): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Request[Incoming request host] --> Matcher[Host route matcher] Matcher --> Hosts[req.hosts] Hosts --> Decorator["@HostParam()"] Decorator --> Handler[Route handler parameter] Decorator --> Pipes[Pipes] Pipes --> Handler ``` ## Usage ```typescript import { Controller, Get, HostParam } from '@nestjs/common'; @Controller({ host: ':account.example.com' }) export class AccountController { @Get() findAccount(@HostParam('account') account: string) { return { account }; } @Get('host-params') findHostParams(@HostParam() params: Record) { return params; } } ``` ## AI Coding Instructions - Use `@HostParam('name')` when the controller host pattern defines a named parameter such as `:account`. - Use `@HostParam()` when the handler needs every value from `req.hosts`. - Keep host parameter names aligned with the names declared in the controller host pattern. - Add pipes as additional decorator arguments when the bound host value needs validation or transformation. # MaxFileSizeValidatorOptions **Kind:** Type **Source:** [`packages/common/pipes/file/max-file-size.validator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/max-file-size.validator.ts#L9) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts { maxSize: number; message?: string | ((maxSize: number) => string); errorMessage?: string | ((ctx: MaxFileSizeValidatorContext) => string); } ``` # ShutdownHooksOptions **Kind:** Interface **Source:** [`packages/common/interfaces/shutdown-hooks-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/shutdown-hooks-options.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) Options for configuring shutdown hooks behavior. `ShutdownHooksOptions` configures how application shutdown hooks behave. It currently controls whether the shutdown process should explicitly terminate the Node.js process after registered cleanup handlers have completed. ## Properties | Property | Type | |---|---| | `useProcessExit` | `boolean` | ## Diagram ```mermaid graph LR A[Application shutdown signal] --> B[Shutdown hooks handler] B --> C[Run registered cleanup hooks] C --> D{useProcessExit?} D -->|true| E[Call process.exit] D -->|false| F[Allow event loop to exit naturally] ``` ## Usage ```ts import type { ShutdownHooksOptions } from '@package/common'; const shutdownOptions: ShutdownHooksOptions = { useProcessExit: true, }; // Pass options when configuring the application's shutdown handling. configureShutdownHooks(shutdownOptions); ``` ## AI Coding Instructions - Set `useProcessExit` to `true` only when the application must terminate immediately after cleanup hooks finish. - Prefer `false` when open resources should be allowed to close naturally through the Node.js event loop. - Ensure shutdown hooks complete asynchronous cleanup before process termination is triggered. - Keep this interface focused on shutdown behavior; add new lifecycle configuration options as explicit, typed fields. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 # ValidationError **Kind:** Interface **Source:** [`packages/common/interfaces/external/validation-error.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/validation-error.interface.ts#L9) **Part of:** [Common](subsystem-packages-common) Validation error description. `ValidationError` describes a failed validation result for a single property on an object. It captures the validated target, invalid value, violated constraints, optional validation contexts, and nested errors for child objects or arrays. ## Properties | Property | Type | |---|---| | `target` | `Record` | | `property` | `string` | | `value` | `any` | | `constraints` | `{ [type: string]: string; }` | | `children` | `ValidationError[]` | | `contexts` | `{ [type: string]: any; }` | ## Diagram ```mermaid graph LR A[ValidationError] --> B[target: Record] A --> C[property: string] A --> D[value: any] A --> E[constraints: constraint messages] A --> F[contexts: constraint metadata] A --> G[children: ValidationError[]] G --> H[Nested property errors] E --> I[Validation failure messages] ``` ## Usage ```ts import type { ValidationError } from '@your-package/common'; const error: ValidationError = { target: { email: 'invalid-email', }, property: 'email', value: 'invalid-email', constraints: { isEmail: 'email must be a valid email address', }, contexts: { isEmail: { code: 'INVALID_EMAIL', }, }, children: [], }; function formatValidationError(validationError: ValidationError): string[] { const messages = Object.values(validationError.constraints ?? {}); return [ ...messages, ...validationError.children.flatMap(formatValidationError), ]; } console.log(formatValidationError(error)); // ['email must be a valid email address'] ``` ## AI Coding Instructions - Preserve nested validation failures in `children`; do not discard them when formatting errors for nested DTOs or array elements. - Treat `constraints` and `contexts` as potentially absent or empty when consuming validation results. - Use `property` together with parent error paths to build complete field paths such as `address.street`. - Avoid exposing `target` or raw `value` directly in API responses when they may contain sensitive data. - Keep constraint keys aligned with the validation library or custom validator names that produced the error. # WsArgumentsHost **Kind:** Interface **Source:** [`packages/common/interfaces/features/arguments-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/arguments-host.interface.ts#L25) **Part of:** [Common](subsystem-packages-common) Methods to obtain WebSocket data and client objects. `WsArgumentsHost` provides typed access to the arguments associated with a WebSocket handler invocation. It exposes the incoming message payload, connected client instance, and event pattern after an `ArgumentsHost` or `ExecutionContext` has been switched to the WebSocket context. ## Diagram ```mermaid graph LR A[WebSocket Event] --> B[ExecutionContext] B --> C[switchToWs()] C --> D[WsArgumentsHost] D --> E[getClient()] D --> F[getData()] D --> G[getPattern()] ``` ## Usage ```ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, WsArgumentsHost, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { Socket } from 'socket.io'; @Injectable() export class WsLoggingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable { const wsContext: WsArgumentsHost = context.switchToWs(); const client = wsContext.getClient(); const data = wsContext.getData<{ message: string }>(); const pattern = wsContext.getPattern(); console.log({ clientId: client.id, pattern, message: data.message, }); return next.handle(); } } ``` ## AI Coding Instructions - Obtain this interface through `context.switchToWs()` when working in guards, interceptors, filters, or pipes that support multiple transport types. - Use generic type parameters with `getData()` and `getClient()` to avoid untyped message payloads and client objects. - Do not assume the client is always a Socket.IO `Socket`; its type depends on the configured WebSocket adapter. - Use `getPattern()` when logging, authorizing, or routing behavior based on the WebSocket event name. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ExecutionContextHost` — `packages/core/helpers/execution-context-host.ts`:10 # Abstract **Kind:** Interface **Source:** [`packages/common/interfaces/abstract.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/abstract.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) `Abstract` is a generic interface that describes a constructor-like type with a `prototype` property of type `T`. It is useful when APIs need to accept or reference a class definition while preserving the instance type represented by that class. ## Properties | Property | Type | |---|---| | `prototype` | `T` | ## Diagram ```mermaid graph LR A[Abstract] --> B[prototype: T] C[Class Definition] --> A B --> D[Instance Shape T] ``` ## Usage ```ts interface Abstract { prototype: T; } class UserService { findUser(id: string): string { return `User ${id}`; } } function getPrototype(type: Abstract): T { return type.prototype; } const userServicePrototype = getPrototype(UserService); userServicePrototype.findUser("123"); ``` ## AI Coding Instructions - Use `Abstract` when a function or API needs to receive a class-like value and access its instance prototype. - Keep the generic `T` aligned with the instance type represented by the class or constructor. - Do not assume `Abstract` guarantees that the value is constructable; it only defines the `prototype` property. - Prefer constructor interfaces with `new (...args) => T` when callers must instantiate the provided type. - Ensure classes passed to APIs using `Abstract` expose a prototype compatible with the expected generic type. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `InvalidClassScopeException` — `packages/core/errors/exceptions/invalid-class-scope.exception.ts`:6 - `AbstractInstanceResolver` — `packages/core/injector/abstract-instance-resolver.ts`:12 - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 # ConfigurableModuleBuilderOptions **Kind:** Interface **Source:** [`packages/common/module-utils/configurable-module.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/configurable-module.builder.ts#L23) **Part of:** [Common](subsystem-packages-common) `ConfigurableModuleBuilderOptions` configures how a configurable module is generated by Nest's module utilities. It defines the injection token used for module options, the module name used in generated APIs, and whether each registration should create a transient module instance. ## Properties | Property | Type | |---|---| | `optionsInjectionToken` | `string | symbol` | | `moduleName` | `string` | | `alwaysTransient` | `boolean` | ## Diagram ```mermaid graph LR A[ConfigurableModuleBuilderOptions] --> B[optionsInjectionToken] A --> C[moduleName] A --> D[alwaysTransient] B --> E[Inject module configuration] C --> F[Generate named registration methods] D --> G[Control module instance reuse] ``` ## Usage ```ts import { ConfigurableModuleBuilder } from '@nestjs/common'; export interface DatabaseModuleOptions { uri: string; poolSize?: number; } const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new ConfigurableModuleBuilder({ moduleName: 'Database', optionsInjectionToken: Symbol('DATABASE_MODULE_OPTIONS'), alwaysTransient: false, }).build(); export { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN }; ``` ## AI Coding Instructions - Use `optionsInjectionToken` when consumers need to inject module configuration into providers; prefer a `Symbol` to avoid token collisions. - Set `moduleName` to a stable, descriptive name because it affects generated configurable-module APIs and diagnostics. - Enable `alwaysTransient` only when every `register()` or `registerAsync()` call must create a distinct dynamic module instance. - Keep the options interface aligned with the generic passed to `ConfigurableModuleBuilder`. - Export the generated module class and options token so feature providers can register and inject configuration consistently. # ConfigurableModuleCls **Kind:** Type **Source:** [`packages/common/module-utils/interfaces/configurable-module-cls.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/interfaces/configurable-module-cls.interface.ts#L16) **Part of:** [Common](subsystem-packages-common) Class that represents a blueprint/prototype for a configurable Nest module. This class provides static methods for constructing dynamic modules. Their names can be controlled through the "MethodKey" type argument. `ConfigurableModuleCls` describes the class produced by Nest’s configurable module utilities. It defines the static registration methods that create `DynamicModule` definitions, including custom method names such as `forRoot` and `forRootAsync`. ## Definition ```ts { new (): any; } & Record< `${MethodKey}`, ( options: ModuleOptions & Partial, ) => DynamicModule > & Record< `${MethodKey}Async`, ( options: ConfigurableModuleAsyncOptions< ModuleOptions, FactoryClassMethodKey > & Partial, ) => DynamicModule > ``` ## Diagram ```mermaid graph LR Builder[ConfigurableModuleBuilder] --> GeneratedClass[ConfigurableModuleCls] GeneratedClass --> SyncMethod[forRoot / register] GeneratedClass --> AsyncMethod[forRootAsync / registerAsync] SyncMethod --> DynamicModule[DynamicModule] AsyncMethod --> DynamicModule DynamicModule --> NestApp[Nest application imports] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ConfigurableModuleBuilder, ConfigurableModuleCls, } from '@nestjs/common'; interface CacheModuleOptions { ttl: number; prefix?: string; } const { ConfigurableModuleClass } = new ConfigurableModuleBuilder() .setClassMethodName('forRoot') .build(); export class CacheModule extends ConfigurableModuleClass {} const CacheConfigurableModule: ConfigurableModuleCls< CacheModuleOptions, 'forRoot' > = CacheModule; @Module({ imports: [ CacheConfigurableModule.forRoot({ ttl: 60, prefix: 'app:', }), ], }) export class AppModule {} ``` ## AI Coding Instructions - Use `ConfigurableModuleCls` when a helper, factory, or abstraction needs to accept a generated configurable module class. - Keep the `MethodKey` generic aligned with the method configured through `setClassMethodName()`, such as `'forRoot'`. - Prefer extending the generated `ConfigurableModuleClass` when defining the public Nest module class. - Use the generated synchronous or asynchronous registration method in a module’s `imports` array, since each call returns a `DynamicModule`. - Do not instantiate configurable module classes directly; use their static registration methods instead. # ErrorHttpStatusCode **Kind:** Type **Source:** [`packages/common/utils/http-error-by-code.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/http-error-by-code.util.ts#L27) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts | HttpStatus.BAD_GATEWAY | HttpStatus.BAD_REQUEST | HttpStatus.CONFLICT | HttpStatus.FORBIDDEN | HttpStatus.GATEWAY_TIMEOUT | HttpStatus.GONE | HttpStatus.HTTP_VERSION_NOT_SUPPORTED | HttpStatus.I_AM_A_TEAPOT | HttpStatus.INTERNAL_SERVER_ERROR | HttpStatus.METHOD_NOT_ALLOWED | HttpStatus.MISDIRECTED | HttpStatus.NOT_ACCEPTABLE | HttpStatus.NOT_FOUND | HttpStatus.NOT_IMPLEMENTED | HttpStatus.PAYLOAD_TOO_LARGE | HttpStatus.PRECONDITION_FAILED | HttpStatus.REQUEST_TIMEOUT | HttpStatus.SERVICE_UNAVAILABLE | HttpStatus.UNAUTHORIZED | HttpStatus.UNPROCESSABLE_ENTITY | HttpStatus.UNSUPPORTED_MEDIA_TYPE ``` # Global **Kind:** Function **Source:** [`packages/common/decorators/modules/global.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/modules/global.decorator.ts#L14) **Part of:** [Common](subsystem-packages-common) Decorator that makes a module global-scoped. Once imported into any module, a global-scoped module will be visible in all modules. Thereafter, modules that wish to inject a service exported from a global module do not need to import the provider module. `Global()` marks a Nest module as globally scoped. Once the module is imported anywhere in the application, its exported providers become available for injection across other modules without requiring repeated module imports. ## Signature ```ts function Global(): ClassDecorator ``` **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[AppModule imports ConfigModule] --> B[@Global ConfigModule] B --> C[Exports ConfigService] C --> D[FeatureModule] C --> E[UsersModule] C --> F[OrdersModule] ``` ## Usage ```ts import { Global, Module } from '@nestjs/common'; @Global() @Module({ providers: [ConfigService], exports: [ConfigService], }) export class ConfigModule {} @Module({ imports: [ConfigModule], }) export class AppModule {} @Module({ providers: [UsersService], }) export class UsersModule { constructor(private readonly configService: ConfigService) {} } ``` ## AI Coding Instructions - Apply `@Global()` only to modules whose exported providers should be available application-wide. - Import a global module at least once, typically from `AppModule`, so Nest can register it. - Explicitly add shared providers to the module's `exports` array; global scope does not automatically export every provider. - Avoid making feature-specific modules global, as this hides dependencies and can make module boundaries harder to understand. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `GlobalService` — `integration/lazy-modules/src/global.module.ts`:3 - `InternalCoreModule` — `packages/core/injector/internal-core-module/internal-core-module.ts`:16 # HttpArgumentsHost **Kind:** Interface **Source:** [`packages/common/interfaces/features/arguments-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/arguments-host.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) Methods to obtain request and response objects. `HttpArgumentsHost` provides HTTP-specific access to the request, response, and next-function objects for the current execution context. It is typically obtained through `ExecutionContext.switchToHttp()` in guards, interceptors, filters, and custom decorators. Use it when framework-agnostic context handling needs to interact with the underlying HTTP adapter. ## Diagram ```mermaid graph LR A[ExecutionContext] --> B[switchToHttp()] B --> C[HttpArgumentsHost] C --> D[getRequest()] C --> E[getResponse()] C --> F[getNext()] D --> G[HTTP Request] E --> H[HTTP Response] F --> I[Next Middleware Function] ``` ## Usage ```ts import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class ApiKeyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const http = context.switchToHttp(); const request = http.getRequest<{ headers: Record }>(); const response = http.getResponse<{ status: (code: number) => unknown }>(); const apiKey = request.headers['x-api-key']; if (!apiKey) { response.status(401); return false; } return true; } } ``` ## AI Coding Instructions - Obtain `HttpArgumentsHost` from `ExecutionContext.switchToHttp()` rather than assuming every execution context is HTTP-based. - Use the generic type parameters on `getRequest()`, `getResponse()`, and `getNext()` when adapter-specific request or response types are needed. - Avoid using this interface in transport-agnostic logic unless the code explicitly supports only HTTP contexts. - Prefer reading request data through `getRequest()` and let NestJS handlers manage normal response serialization where possible. - Remember that `getNext()` is primarily relevant to Express-style middleware flows and may not be meaningful for every HTTP adapter. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ExecutionContextHost` — `packages/core/helpers/execution-context-host.ts`:10 # HttpErrorByCode **Kind:** Constant **Source:** [`packages/common/utils/http-error-by-code.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/http-error-by-code.util.ts#L50) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts Record> ``` ## Value ```ts { [HttpStatus.BAD_GATEWAY]: BadGatewayException, [HttpStatus.BAD_REQUEST]: BadRequestException, [HttpStatus.CONFLICT]: ConflictException, [HttpStatus.FORBIDDEN]: ForbiddenException, [HttpStatus.GATEWAY_TIMEOUT]: GatewayTimeoutException, [HttpStatus.GONE]: GoneException, [HttpStatus.HTTP_VERSION_NOT_SUPPORTED]: HttpVersionNotSupportedException, [HttpStatus.I_AM_A_TEAPOT]: ImATeapotE… ``` # OnApplicationShutdown **Kind:** Interface **Source:** [`packages/common/interfaces/hooks/on-application-shutdown.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/hooks/on-application-shutdown.interface.ts#L9) **Part of:** [Common](subsystem-packages-common) Interface defining method to respond to system signals (when application gets shutdown by, e.g., SIGTERM) `OnApplicationShutdown` is a lifecycle hook interface for providers that need to perform cleanup when the application is shutting down. Implement `onApplicationShutdown()` to respond to operating-system signals such as `SIGTERM` and release resources such as database connections, queues, or background workers. ## Diagram ```mermaid graph LR Signal[OS signal: SIGTERM / SIGINT] --> App[Nest application] App --> Lifecycle[Shutdown lifecycle hooks] Lifecycle --> Hook[OnApplicationShutdown] Hook --> Cleanup[Release resources and cleanup] ``` ## Usage ```ts import { Injectable, OnApplicationShutdown } from '@nestjs/common'; @Injectable() export class DatabaseService implements OnApplicationShutdown { async onApplicationShutdown(signal?: string) { console.log(`Application shutting down via ${signal ?? 'unknown signal'}`); // Close database connections, stop workers, flush telemetry, etc. await this.closeDatabaseConnection(); } private async closeDatabaseConnection() { // Cleanup implementation } } // Enable shutdown hooks during application bootstrap: // const app = await NestFactory.create(AppModule); // app.enableShutdownHooks(); ``` ## AI Coding Instructions - Implement `onApplicationShutdown(signal?: string)` in injectable providers that own resources requiring graceful cleanup. - Enable shutdown hooks with `app.enableShutdownHooks()`; the hook is not invoked for OS signals unless shutdown hooks are enabled. - Treat the optional `signal` parameter as informational, since shutdown can also be initiated programmatically. - Make cleanup operations idempotent and safe to run during partial application initialization. - Await asynchronous cleanup work so connections, queues, and telemetry are properly flushed before process exit. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `ServerGateway` — `integration/websockets/src/server.gateway.ts`:6 - `ClientsModule` — `packages/microservices/module/clients.module.ts`:17 - `callAppShutdownHook` — `packages/core/hooks/on-app-shutdown.hook.ts`:45 # ParseArrayPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-array.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-array.pipe.ts#L19) **Part of:** [Common](subsystem-packages-common) `ParseArrayPipeOptions` configures how an array input is parsed and validated by `ParseArrayPipe`. It defines the expected item type, the delimiter used for string inputs, whether empty or missing values are allowed, and how parsing errors are converted into exceptions. ## Properties | Property | Type | |---|---| | `items` | `Type` | | `separator` | `string` | | `optional` | `boolean` | | `exceptionFactory` | `(error: any) => any` | ## Diagram ```mermaid graph LR Input[Request input] --> Pipe[ParseArrayPipe] Pipe --> Separator[separator: split string input] Separator --> Items[items: validate each item type] Pipe --> Optional[optional: allow missing value] Items --> Result[Parsed array] Pipe --> Errors[Validation error] Errors --> Factory[exceptionFactory] Factory --> Exception[Custom exception] ``` ## Usage ```ts import { ParseArrayPipe, ParseArrayPipeOptions } from '@nestjs/common'; const options: ParseArrayPipeOptions = { items: Number, separator: ',', optional: false, exceptionFactory: (error) => { throw new Error(`Invalid ID list: ${error}`); }, }; const parseIds = new ParseArrayPipe(options); // "1,2,3" becomes [1, 2, 3] const ids = await parseIds.transform('1,2,3', { type: 'query', data: 'ids', metatype: String, }); ``` ## AI Coding Instructions - Provide `items` when each array element should be validated or transformed as a specific runtime type. - Use `separator` for comma-separated query parameters or other delimited string inputs; ensure it matches the API contract. - Set `optional: true` only when omitted or empty input should pass through without raising a validation error. - Use `exceptionFactory` to align parsing failures with the application's standard HTTP exception format. - Keep custom exception factories deterministic and avoid exposing raw validation details to clients. # ParseDatePipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-date.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-date.pipe.ts#L13) **Part of:** [Common](subsystem-packages-common) `ParseDatePipeOptions` configures how a date-parsing pipe handles incoming values and validation failures. It controls whether values may be omitted, supplies a fallback date, and defines how parsing errors are converted into HTTP exceptions. ## Properties | Property | Type | |---|---| | `optional` | `boolean` | | `default` | `() => Date` | | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(error: string) => any` | ## Diagram ```mermaid graph LR Input[Incoming date value] --> Pipe[ParseDatePipe] Pipe --> Optional{optional?} Optional -- Missing and allowed --> Default[default(): Date] Optional -- Value provided --> Parse[Parse and validate date] Parse -- Valid --> Date[Date result] Parse -- Invalid --> Factory[exceptionFactory(error)] Factory --> Error[HTTP exception] Status[errorHttpStatusCode] --> Factory ``` ## Usage ```ts import { ParseDatePipeOptions } from '@nestjs/common'; const datePipeOptions: ParseDatePipeOptions = { optional: true, default: () => new Date(), errorHttpStatusCode: 400, exceptionFactory: (error: string) => ({ statusCode: 400, message: `Invalid date: ${error}`, }), }; // Example: pass these options when configuring the date parsing pipe. ``` ## AI Coding Instructions - Set `optional: true` only when an absent input should be accepted; provide a `default` callback for the resulting value. - Keep `default` as a function so a fresh `Date` instance is created for every pipe invocation. - Use `errorHttpStatusCode` consistently with the API's validation-error conventions. - Ensure `exceptionFactory` returns an exception shape recognized by the surrounding HTTP framework. - Include actionable parsing details in the `error` message without exposing sensitive request data. # ParseUUIDPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-uuid.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-uuid.pipe.ts#L17) **Part of:** [Common](subsystem-packages-common) `ParseUUIDPipeOptions` configures the behavior of NestJS's `ParseUUIDPipe`, which validates incoming values as UUIDs. It lets callers restrict accepted UUID versions, customize validation errors, provide a custom exception factory, and allow optional values to bypass validation. ## Properties | Property | Type | |---|---| | `version` | `'3' | '4' | '5' | '7'` | | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(errors: string) => any` | | `optional` | `boolean` | ## Diagram ```mermaid graph LR A[Incoming route value] --> B[ParseUUIDPipe] B --> C{Value is optional
and empty?} C -->|Yes| D[Return value unchanged] C -->|No| E{Valid UUID?} E -->|Yes| F[Return validated UUID] E -->|No| G[Create validation exception] H[ParseUUIDPipeOptions] --> B H --> I[version: 3 | 4 | 5 | 7] H --> J[optional: boolean] H --> K[errorHttpStatusCode] H --> L[exceptionFactory] K --> G L --> G ``` ## Usage ```ts import { BadRequestException, ParseUUIDPipe, } from '@nestjs/common'; const uuidPipe = new ParseUUIDPipe({ version: '4', optional: false, exceptionFactory: (errors) => new BadRequestException({ message: 'Invalid user identifier', errors, }), }); // Example controller usage @Get(':id') findOne( @Param('id', uuidPipe) id: string, ) { return this.usersService.findOne(id); } ``` ## AI Coding Instructions - Use `version` to enforce the UUID format expected by the API, such as `'4'` for randomly generated identifiers. - Set `optional: true` only for parameters that may legitimately be absent; valid non-empty values must still be UUIDs. - Prefer `exceptionFactory` when the application requires a shared or custom error response format. - Use `errorHttpStatusCode` for standard HTTP error customization when a custom exception body is unnecessary. - Apply `ParseUUIDPipe` at controller boundaries (`@Param`, `@Query`, or `@Body`) before passing identifiers to services or repositories. ## How it works ## Type `ParseUUIDPipeOptions` is the optional configuration interface accepted by `ParseUUIDPipe`’s constructor. The pipe stores these options and reads `version`, `exceptionFactory`, `errorHttpStatusCode`, and `optional` during construction or transformation. [`packages/common/pipes/parse-uuid.pipe.ts:17-38`](packages/common/pipes/parse-uuid.pipe.ts#L17-L38) [`packages/common/pipes/parse-uuid.pipe.ts:59-71`](packages/common/pipes/parse-uuid.pipe.ts#L59-L71) ## Members - `version?: '3' | '4' | '5' | '7'` selects the UUID version pattern checked by the pipe. If omitted, the pipe checks against its general UUID pattern instead. [`packages/common/pipes/parse-uuid.pipe.ts:19-21`](packages/common/pipes/parse-uuid.pipe.ts#L19-L21) [`packages/common/pipes/parse-uuid.pipe.ts:67`](packages/common/pipes/parse-uuid.pipe.ts#L67) [`packages/common/pipes/parse-uuid.pipe.ts:77`](packages/common/pipes/parse-uuid.pipe.ts#L77) [`packages/common/pipes/parse-uuid.pipe.ts:87-92`](packages/common/pipes/parse-uuid.pipe.ts#L87-L92) - `errorHttpStatusCode?: ErrorHttpStatusCode` selects the status-specific exception class used when no `exceptionFactory` is supplied; it defaults to `HttpStatus.BAD_REQUEST` (`400`). [`packages/common/pipes/parse-uuid.pipe.ts:23-25`](packages/common/pipes/parse-uuid.pipe.ts#L23-L25) [`packages/common/pipes/parse-uuid.pipe.ts:61-70`](packages/common/pipes/parse-uuid.pipe.ts#L61-L70) [`packages/common/enums/http-status.enum.ts:26`](packages/common/enums/http-status.enum.ts#L26) The `ErrorHttpStatusCode` type is limited to the status codes mapped in `HttpErrorByCode`, including bad request, unauthorized, forbidden, not found, conflict, several gateway/server errors, and others listed in its union. [`packages/common/utils/http-error-by-code.util.ts:27-48`](packages/common/utils/http-error-by-code.util.ts#L27-L48) [`packages/common/utils/http-error-by-code.util.ts:50-72`](packages/common/utils/http-error-by-code.util.ts#L50-L72) - `exceptionFactory?: (errors: string) => any` replaces the default exception creation function. On invalid input, the pipe calls this function with either `"The value passed as UUID is not a string"` or a version-aware `"Validation failed (uuid ... is expected)"` message, then throws its return value. [`packages/common/pipes/parse-uuid.pipe.ts:27-32`](packages/common/pipes/parse-uuid.pipe.ts#L27-L32) [`packages/common/pipes/parse-uuid.pipe.ts:68-70`](packages/common/pipes/parse-uuid.pipe.ts#L68-L70) [`packages/common/pipes/parse-uuid.pipe.ts:77-82`](packages/common/pipes/parse-uuid.pipe.ts#L77-L82) [`packages/common/pipes/parse-uuid.pipe.ts:87-90`](packages/common/pipes/parse-uuid.pipe.ts#L87-L90) - `optional?: boolean` changes handling only for `null` and `undefined`: when it is truthy, `transform()` returns either value unchanged without UUID checking. [`packages/common/pipes/parse-uuid.pipe.ts:33-37`](packages/common/pipes/parse-uuid.pipe.ts#L33-L37) [`packages/common/pipes/parse-uuid.pipe.ts:73-76`](packages/common/pipes/parse-uuid.pipe.ts#L73-L76) [`packages/common/utils/shared.utils.ts:48-49`](packages/common/utils/shared.utils.ts#L48-L49) ## Validation behavior controlled by the options The accepted UUID patterns require hyphenated hexadecimal text with `8-4-4-4-12` groups. Version-specific patterns require `3`, `4`, `5`, or `7` at the beginning of the third group; versions 4, 5, and 7 also require `8`, `9`, `A`, or `B` at the beginning of the fourth group. Matching is case-insensitive. [`packages/common/pipes/parse-uuid.pipe.ts:49-55`](packages/common/pipes/parse-uuid.pipe.ts#L49-L55) Except for the `optional` null/undefined path, a value must be a string before pattern matching. Non-string values cause the configured exception factory’s result to be thrown. [`packages/common/pipes/parse-uuid.pipe.ts:73-84`](packages/common/pipes/parse-uuid.pipe.ts#L73-L84) [`packages/common/pipes/parse-uuid.pipe.ts:87-92`](packages/common/pipes/parse-uuid.pipe.ts#L87-L92) [`packages/common/utils/shared.utils.ts:45`](packages/common/utils/shared.utils.ts#L45) # RpcArgumentsHost **Kind:** Interface **Source:** [`packages/common/interfaces/features/arguments-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/arguments-host.interface.ts#L45) **Part of:** [Common](subsystem-packages-common) Methods to obtain RPC data object. `RpcArgumentsHost` provides access to the data payload and transport-specific context for an RPC request. It is typically obtained from an `ArgumentsHost` through `switchToRpc()` inside guards, interceptors, filters, or pipes that support NestJS microservice transports. ## Diagram ```mermaid graph LR A[ArgumentsHost] -->|switchToRpc()| B[RpcArgumentsHost] B -->|getData()| C[RPC Data Payload] B -->|getContext()| D[Transport Context] C --> E[Guard / Interceptor / Filter] D --> E ``` ## Usage ```ts import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class RpcAuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const rpc = context.switchToRpc(); const data = rpc.getData<{ token?: string; action: string }>(); const rpcContext = rpc.getContext<{ clientId?: string }>(); if (!data.token) { return false; } console.log(`Authorizing ${data.action} for ${rpcContext.clientId}`); return true; } } ``` ## AI Coding Instructions - Obtain this interface through `context.switchToRpc()` when handling microservice or RPC requests. - Use generic type parameters with `getData()` and `getContext()` to avoid untyped payload access. - Treat `getData()` as the message payload and `getContext()` as transport-specific metadata, such as client or broker context. - Do not use HTTP-specific methods such as `switchToHttp()` when the handler is invoked through an RPC transport. - Keep transport-specific context handling isolated so shared guards and interceptors remain portable across RPC transports. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ExecutionContextHost` — `packages/core/helpers/execution-context-host.ts`:10 # ShutdownSignal **Kind:** Enum **Source:** [`packages/common/enums/shutdown-signal.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/common/enums/shutdown-signal.enum.ts#L4) **Part of:** [Common](subsystem-packages-common) System signals which shut down a process `ShutdownSignal` defines the operating-system signals that can trigger graceful process termination. It provides a shared, type-safe set of signal names for shutdown hooks, lifecycle handlers, and process cleanup logic across the application. ## Values - `SIGHUP` - `SIGINT` - `SIGQUIT` - `SIGILL` - `SIGTRAP` - `SIGABRT` - `SIGBUS` - `SIGFPE` - `SIGSEGV` - `SIGUSR2` - `SIGTERM` ## Diagram ```mermaid graph LR OS[Operating System] --> Signal[Shutdown Signal] Signal --> Enum[ShutdownSignal enum] Enum --> Handler[Application Shutdown Handler] Handler --> Cleanup[Cleanup Resources] Cleanup --> Exit[Process Exit] ``` ## Usage ```ts import { ShutdownSignal } from '@nestjs/common'; function handleShutdown(signal: ShutdownSignal) { console.log(`Received ${signal}; closing application resources.`); } process.on(ShutdownSignal.SIGTERM, () => { handleShutdown(ShutdownSignal.SIGTERM); }); process.on(ShutdownSignal.SIGINT, () => { handleShutdown(ShutdownSignal.SIGINT); }); ``` ## AI Coding Instructions - Use `ShutdownSignal` instead of hard-coded signal strings when registering shutdown handlers or lifecycle hooks. - Register cleanup logic for common termination signals such as `SIGTERM` and `SIGINT`. - Ensure shutdown handlers close database connections, message consumers, HTTP servers, and other long-lived resources. - Avoid assuming every signal is available on every operating system; verify platform compatibility when adding signal-specific behavior. - Keep signal handlers idempotent, since multiple shutdown signals may be received during process termination. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 # UseFilters **Kind:** Function **Source:** [`packages/common/decorators/core/exception-filters.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/exception-filters.decorator.ts#L29) **Part of:** [Common](subsystem-packages-common) Decorator that binds exception filters to the scope of the controller or method, depending on its context. When `@UseFilters` is used at the controller level, the filter will be applied to every handler (method) in the controller. When `@UseFilters` is used at the individual handler level, the filter will apply only to that specific method. `@UseFilters()` binds one or more exception filters to a controller or individual route handler. Controller-scoped filters handle exceptions from every handler in that controller, while method-scoped filters apply only to the decorated endpoint. It integrates with NestJS exception handling by allowing custom error response logic to run when matching exceptions are thrown. ## Signature ```ts function UseFilters(filters: (ExceptionFilter | Function)[]) ``` ## Parameters | Name | Type | |---|---| | `filters` | `(ExceptionFilter | Function)[]` | ## Diagram ```mermaid graph LR A[Incoming Request] --> B[Controller Handler] B -->|Throws exception| C{Filter scope} C -->|Method-level @UseFilters| D[Method Exception Filter] C -->|Controller-level @UseFilters| E[Controller Exception Filter] D --> F[Custom Error Response] E --> F ``` ## Usage ```ts import { Catch, Controller, ExceptionFilter, ArgumentsHost, HttpException, Get, UseFilters, } from '@nestjs/common'; @Catch(HttpException) class HttpErrorFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const response = host.switchToHttp().getResponse(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message, handledBy: 'HttpErrorFilter', }); } } // Applies the filter to every route in this controller. @Controller('users') @UseFilters(HttpErrorFilter) export class UsersController { @Get() findAll() { return []; } // A method-level filter can be used for endpoint-specific behavior. @Get('special') @UseFilters(HttpErrorFilter) findSpecialUsers() { return []; } } ``` ## AI Coding Instructions - Apply `@UseFilters()` at the controller level for shared exception handling across all controller routes. - Apply it at the handler level when an endpoint needs specialized error formatting or handling behavior. - Ensure filter classes implement `ExceptionFilter` and use `@Catch()` to define the exception types they handle. - Pass filter classes or filter instances to `@UseFilters()`; prefer classes when NestJS dependency injection is required. - Keep filters focused on translating exceptions into responses; avoid placing business logic inside exception filters. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ApplicationGateway` — `integration/websockets/src/app.gateway.ts`:12 # ControllerOptions **Kind:** Interface **Source:** [`packages/common/decorators/core/controller.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/controller.decorator.ts#L16) **Part of:** [Common](subsystem-packages-common) Interface defining options that can be passed to `@Controller()` decorator `ControllerOptions` defines configuration accepted by NestJS's `@Controller()` decorator. It lets a controller declare one or more route path prefixes and optionally restrict routing to specific hostnames or host-matching regular expressions. ## Properties | Property | Type | |---|---| | `path` | `string | string[]` | | `host` | `string | RegExp | Array` | ## Diagram ```mermaid graph LR A["@Controller(options)"] --> B["ControllerOptions"] B --> C["path: string | string[]"] B --> D["host: string | RegExp | Array"] C --> E["Controller route prefixes"] D --> F["Host-based route matching"] ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import type { ControllerOptions } from '@nestjs/common'; const controllerOptions: ControllerOptions = { path: ['users', 'members'], host: ['api.example.com', /^admin\./], }; @Controller(controllerOptions) export class UsersController { @Get() findAll() { return []; } } ``` ## AI Coding Instructions - Use `path` to define a single controller prefix or multiple equivalent prefixes. - Use `host` only when the controller should respond to specific domains or subdomains. - Prefer `RegExp` host rules for pattern-based subdomain matching, such as `/^admin\./`. - Ensure host-based routing is supported by the active HTTP adapter and deployment proxy configuration. - Keep controller options focused on routing configuration; define request handling logic in controller methods. # CUSTOM_ROUTE_ARGS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L19) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__customRouteArgs__' ``` ## Value ```ts '__customRouteArgs__' ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `ParamsFactory` — `packages/core/helpers/external-context-creator.ts`:28 - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 # CustomDecorator **Kind:** Type **Source:** [`packages/common/decorators/core/set-metadata.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/set-metadata.decorator.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts MethodDecorator & ClassDecorator & { KEY: TKey; } ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `CreateDecoratorOptions` — `packages/core/services/reflector.service.ts`:8 - `FilterByInclude` — `packages/core/discovery/discovery-service.ts`:16 # IntrinsicException **Kind:** Class **Source:** [`packages/common/exceptions/intrinsic.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/intrinsic.exception.ts#L7) **Part of:** [Common](subsystem-packages-common) Exception that represents an intrinsic error in the application. When thrown, the default exception filter will not log the error message. `IntrinsicException` represents an expected, application-level error that should not be treated as an unexpected failure. When this exception is thrown, the default exception filter handles the response without logging the exception message, making it suitable for controlled or non-actionable errors. **Extends:** `Error` ## Diagram ```mermaid graph LR A[Application code] -->|throw new IntrinsicException| B[IntrinsicException] B --> C[Default Exception Filter] C --> D[Error response returned] C -. does not log message .-> E[Application logs] ``` ## Usage ```ts import { IntrinsicException } from '@app/common/exceptions/intrinsic.exception'; export class AccountService { async getAccount(accountId: string) { const account = await this.accountRepository.findById(accountId); if (!account) { throw new IntrinsicException('Account is unavailable'); } return account; } } ``` ## AI Coding Instructions - Use `IntrinsicException` for expected application errors that should not produce default exception-filter log messages. - Provide a clear, safe message suitable for the client or the application's error-handling flow. - Do not use this exception for unexpected infrastructure failures, such as database connectivity or unhandled programming errors. - Ensure the default exception filter remains registered so `IntrinsicException` receives its intended no-log handling behavior. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `BaseExceptionFilter` — `packages/core/exceptions/base-exception-filter.ts`:17 - `ExternalExceptionFilter` — `packages/core/exceptions/external-exception-filter.ts`:3 - `BaseRpcExceptionFilter` — `packages/microservices/exceptions/base-rpc-exception-filter.ts`:15 - `ErrorPayload` — `packages/websockets/exceptions/base-ws-exception-filter.ts`:11 # isLogLevel **Kind:** Function **Source:** [`packages/common/services/utils/is-log-level.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/utils/is-log-level.util.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel ``` ## Parameters | Name | Type | |---|---| | `maybeLogLevel` | `any` | **Returns:** `maybeLogLevel is LogLevel` # ParamData **Kind:** Type **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L24) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts object | string | number ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `ParamProperties` — `packages/core/helpers/context-utils.ts`:15 - `ParamsFactory` — `packages/core/helpers/external-context-creator.ts`:28 - `ParamsMetadata` — `packages/core/helpers/interfaces/params-metadata.interface.ts`:3 # PARAMTYPES_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L11) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'design:paramtypes' ``` ## Value ```ts 'design:paramtypes' ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ParamProperties` — `packages/core/helpers/context-utils.ts`:15 - `InjectorDependency` — `packages/core/injector/injector.ts`:51 - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 # ParseBoolPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-bool.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-bool.pipe.ts#L17) **Part of:** [Common](subsystem-packages-common) `ParseBoolPipeOptions` configures the behavior of NestJS's `ParseBoolPipe`, which converts incoming request values into boolean values. It lets applications customize the HTTP status code, exception creation, and whether missing values should be accepted without parsing. ## Properties | Property | Type | |---|---| | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(error: string) => any` | | `optional` | `boolean` | ## Diagram ```mermaid graph LR A[Incoming request value] --> B[ParseBoolPipe] B --> C{Value is boolean-compatible?} C -->|Yes| D[Return boolean] C -->|No| E[exceptionFactory] E --> F[Throw configured exception] G[ParseBoolPipeOptions] --> B G --> H[errorHttpStatusCode] G --> I[exceptionFactory] G --> J[optional] ``` ## Usage ```ts import { BadRequestException, ParseBoolPipe, type ParseBoolPipeOptions, } from '@nestjs/common'; const options: ParseBoolPipeOptions = { errorHttpStatusCode: 422, optional: true, exceptionFactory: (error) => new BadRequestException({ message: 'Expected a boolean query parameter.', details: error, }), }; const parseBoolean = new ParseBoolPipe(options); // Useful for values such as "true", "false", true, or false. const enabled = await parseBoolean.transform('true', { type: 'query', data: 'enabled', metatype: Boolean, }); // enabled === true ``` ## AI Coding Instructions - Use `optional: true` when the value may be `null` or `undefined`; otherwise, invalid or absent values should trigger the configured exception. - Provide an `exceptionFactory` when the application needs a consistent custom error response format. - Use `errorHttpStatusCode` for the default exception behavior; it may be unnecessary when `exceptionFactory` creates its own HTTP exception. - Apply these options when constructing `ParseBoolPipe` for route parameters, query parameters, or request body fields that must be parsed as booleans. # ParseEnumPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-enum.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-enum.pipe.ts#L13) **Part of:** [Common](subsystem-packages-common) `ParseEnumPipeOptions` configures the behavior of NestJS's `ParseEnumPipe`, which validates that an incoming value belongs to a specified enum. It lets callers control whether a value is optional, which HTTP status code is returned for invalid values, and how validation exceptions are created. ## Properties | Property | Type | |---|---| | `optional` | `boolean` | | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(error: string) => any` | ## Diagram ```mermaid graph LR A[Incoming request value] --> B[ParseEnumPipe] B --> C{Value is optional
and missing?} C -->|Yes| D[Return value unchanged] C -->|No| E{Matches enum value?} E -->|Yes| F[Return validated enum value] E -->|No| G[ParseEnumPipeOptions] G --> H[errorHttpStatusCode] G --> I[exceptionFactory] H --> J[Throw validation exception] I --> J ``` ## Usage ```ts import { BadRequestException, ParseEnumPipe, } from '@nestjs/common'; enum UserRole { Admin = 'admin', Member = 'member', Viewer = 'viewer', } const enumPipeOptions = { optional: true, errorHttpStatusCode: 422, exceptionFactory: (error: string) => new BadRequestException({ message: 'Invalid user role', details: error, }), }; const rolePipe = new ParseEnumPipe(UserRole, enumPipeOptions); // Valid: "admin" // Optional: undefined // Invalid: "superuser" throws the custom exception ``` ## AI Coding Instructions - Pass `ParseEnumPipeOptions` as the second argument when constructing `ParseEnumPipe`. - Set `optional: true` only when missing or `null` enum values should bypass enum validation. - Use `errorHttpStatusCode` to align validation failures with the API's HTTP error conventions. - Prefer `exceptionFactory` when your application requires a consistent custom error response shape. - Ensure the supplied enum contains the exact values expected from request parameters, query strings, or request bodies. # ParseFloatPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-float.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-float.pipe.ts#L13) **Part of:** [Common](subsystem-packages-common) `ParseFloatPipeOptions` configures the behavior of a float-parsing pipe. It controls whether missing values are accepted, which HTTP status code is used for validation failures, and how parsing errors are converted into exceptions. ## Properties | Property | Type | |---|---| | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(error: string) => any` | | `optional` | `boolean` | ## Diagram ```mermaid graph LR Input[Incoming value] --> Pipe[ParseFloatPipe] Pipe --> Optional{optional enabled?} Optional -->|Empty value allowed| Result[Return empty value] Optional -->|Value required| Parse[Parse numeric float] Parse -->|Valid float| Result2[Return parsed number] Parse -->|Invalid value| Factory[exceptionFactory] Factory --> Error[Throw exception with errorHttpStatusCode] ``` ## Usage ```ts import { ParseFloatPipe } from '@nestjs/common'; import type { ParseFloatPipeOptions } from '@nestjs/common'; const options: ParseFloatPipeOptions = { optional: false, errorHttpStatusCode: 422, exceptionFactory: (error: string) => ({ statusCode: 422, message: `Invalid price: ${error}`, }), }; const parsePrice = new ParseFloatPipe(options); // Example controller usage: // @Query('price', parsePrice) price: number ``` ## AI Coding Instructions - Use `optional: true` only when empty or missing values should bypass float validation. - Provide an `exceptionFactory` when the default validation exception format does not match the application's error contract. - Ensure `errorHttpStatusCode` aligns with API validation conventions, such as `400` or `422`. - Treat successfully transformed values as JavaScript `number` values and validate domain-specific constraints separately. ## How it works `ParseFloatPipeOptions` is the optional constructor-configuration interface for `ParseFloatPipe`. It has three optional fields: [`errorHttpStatusCode`](packages/common/pipes/parse-float.pipe.ts#L17), [`exceptionFactory`](packages/common/pipes/parse-float.pipe.ts#L24), and [`optional`](packages/common/pipes/parse-float.pipe.ts#L29). - `errorHttpStatusCode` accepts the `ErrorHttpStatusCode` union, which is limited to the HTTP status codes mapped to exception classes in `HttpErrorByCode`. [packages/common/utils/http-error-by-code.util.ts:27-48](packages/common/utils/http-error-by-code.util.ts#L27-L48) [packages/common/utils/http-error-by-code.util.ts:50-72](packages/common/utils/http-error-by-code.util.ts#L50-L72) - `exceptionFactory` accepts a function receiving an error string and returning the value that `ParseFloatPipe` throws when validation fails. [packages/common/pipes/parse-float.pipe.ts:19-24](packages/common/pipes/parse-float.pipe.ts#L19-L24) [packages/common/pipes/parse-float.pipe.ts:64-67](packages/common/pipes/parse-float.pipe.ts#L64-L67) - `optional`, when truthy, causes the pipe to return an input that is `null` or `undefined` without numeric validation or parsing. `isNil` identifies exactly `null` and `undefined`. [packages/common/pipes/parse-float.pipe.ts:25-29](packages/common/pipes/parse-float.pipe.ts#L25-L29) [packages/common/pipes/parse-float.pipe.ts:60-63](packages/common/pipes/parse-float.pipe.ts#L60-L63) [packages/common/utils/shared.utils.ts:48-49](packages/common/utils/shared.utils.ts#L48-L49) When no `exceptionFactory` is configured, `ParseFloatPipe` creates one that constructs the exception class selected by `errorHttpStatusCode`; that status defaults to `HttpStatus.BAD_REQUEST`. [packages/common/pipes/parse-float.pipe.ts:43-50](packages/common/pipes/parse-float.pipe.ts#L43-L50) If numeric validation fails, the factory receives the fixed message `Validation failed (numeric string is expected)`. [packages/common/pipes/parse-float.pipe.ts:64-67](packages/common/pipes/parse-float.pipe.ts#L64-L67) The associated pipe accepts values whose runtime type is `string` or `number`, whose `parseFloat` result is not `NaN`, and which are finite; valid values are returned as `parseFloat(value)`. [packages/common/pipes/parse-float.pipe.ts:60-69](packages/common/pipes/parse-float.pipe.ts#L60-L69) [packages/common/pipes/parse-float.pipe.ts:76-81](packages/common/pipes/parse-float.pipe.ts#L76-L81) # ParseIntPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/parse-int.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-int.pipe.ts#L17) **Part of:** [Common](subsystem-packages-common) `ParseIntPipeOptions` configures how NestJS's `ParseIntPipe` validates and transforms incoming values into integers. It lets you customize the HTTP status code or exception factory used for invalid values, and optionally allow `null` or `undefined` values to pass through unchanged. ## Properties | Property | Type | |---|---| | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(error: string) => any` | | `optional` | `boolean` | ## Diagram ```mermaid graph LR A[Incoming request value] --> B[ParseIntPipe] B --> C{Value is null/undefined
and optional?} C -->|Yes| D[Return original value] C -->|No| E{Valid integer?} E -->|Yes| F[Return parsed integer] E -->|No| G[Create validation exception] G --> H[errorHttpStatusCode] G --> I[exceptionFactory] ``` ## Usage ```ts import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; import type { ParseIntPipeOptions } from '@nestjs/common'; const parseIdOptions: ParseIntPipeOptions = { errorHttpStatusCode: 422, exceptionFactory: (error) => ({ statusCode: 422, message: error, error: 'Validation Error', }), optional: false, }; @Controller('users') export class UsersController { @Get(':id') findOne( @Param('id', new ParseIntPipe(parseIdOptions)) id: number, ) { return { id }; } } ``` ## AI Coding Instructions - Pass `ParseIntPipeOptions` to `new ParseIntPipe(options)` when endpoint-specific integer validation behavior is needed. - Use `errorHttpStatusCode` for standard HTTP error customization; use `exceptionFactory` when the application requires a custom exception or response shape. - Set `optional: true` only for parameters that may legitimately be `null` or `undefined`; it does not make invalid non-empty strings valid integers. - Keep custom exception factories consistent with the application's global error-response conventions. - Type option objects as `ParseIntPipeOptions` when defining reusable pipe configuration. ## How it works `ParseIntPipeOptions` is the optional configuration interface accepted by `ParseIntPipe`’s constructor. The constructor replaces an omitted options object with `{}`. [packages/common/pipes/parse-int.pipe.ts:17-34](packages/common/pipes/parse-int.pipe.ts:17-34) [packages/common/pipes/parse-int.pipe.ts:47-50](packages/common/pipes/parse-int.pipe.ts:47-50) - `errorHttpStatusCode?: ErrorHttpStatusCode` selects the exception class used when integer validation fails, unless `exceptionFactory` is set. It defaults to `HttpStatus.BAD_REQUEST` (400). [packages/common/pipes/parse-int.pipe.ts:21](packages/common/pipes/parse-int.pipe.ts:21) [packages/common/pipes/parse-int.pipe.ts:49-54](packages/common/pipes/parse-int.pipe.ts:49-54) [packages/common/enums/http-status.enum.ts:26](packages/common/enums/http-status.enum.ts:26) `ErrorHttpStatusCode` is limited to the status codes that index `HttpErrorByCode`; that map associates each allowed code with an exception class. [packages/common/utils/http-error-by-code.util.ts:27-50](packages/common/utils/http-error-by-code.util.ts:27-50) - `exceptionFactory?: (error: string) => any` overrides status-code-based exception creation. On validation failure, the pipe calls it with the exact message `Validation failed (numeric string is expected)` and throws its return value. [packages/common/pipes/parse-int.pipe.ts:23-28](packages/common/pipes/parse-int.pipe.ts:23-28) [packages/common/pipes/parse-int.pipe.ts:52-54](packages/common/pipes/parse-int.pipe.ts:52-55) [packages/common/pipes/parse-int.pipe.ts:68-72](packages/common/pipes/parse-int.pipe.ts:68-72) - `optional?: boolean` defaults to `false`. When it is truthy and the input is `null` or `undefined`, `transform()` returns that input without numeric validation or parsing. [packages/common/pipes/parse-int.pipe.ts:30-33](packages/common/pipes/parse-int.pipe.ts:30-33) [packages/common/pipes/parse-int.pipe.ts:64-67](packages/common/pipes/parse-int.pipe.ts:64-67) [packages/common/utils/shared.utils.ts:48-49](packages/common/utils/shared.utils.ts:48-49) Without the `optional` nullish branch, the pipe accepts only string or number values whose complete text matches an optional `-` followed by one or more digits and for which `isFinite()` is true; other values trigger the configured exception. Accepted values are returned as `parseInt(value, 10)`. [packages/common/pipes/parse-int.pipe.ts:68-85](packages/common/pipes/parse-int.pipe.ts:68-85) # Patch **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L84) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP PATCH requests to the specified path. `Patch` is a method decorator that maps an HTTP `PATCH` request to a controller handler. It is used to define endpoints for partial resource updates and delegates route metadata creation to the shared request-mapping decorator infrastructure. ## Definition ```ts createMappingDecorator(RequestMethod.PATCH) ``` ## Value ```ts createMappingDecorator(RequestMethod.PATCH) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|PATCH /resource/:id| Router[Nest Router] Router --> Controller[Controller Method] Patch["@Patch(path) decorator"] -->|Registers PATCH route metadata| Controller Controller --> Handler[Update Resource Logic] ``` ## Usage ```ts import { Body, Controller, Param, Patch } from '@nestjs/common'; @Controller('users') export class UsersController { @Patch(':id') updateUser( @Param('id') id: string, @Body() updateUserDto: { displayName?: string }, ) { return { id, ...updateUserDto, }; } } ``` ## AI Coding Instructions - Apply `@Patch()` only to controller methods that handle partial updates of an existing resource. - Provide a path such as `':id'` when the handler needs to identify a specific resource. - Use DTOs with optional fields for PATCH request bodies rather than requiring a complete resource payload. - Combine `@Patch()` with parameter decorators such as `@Param()`, `@Body()`, and validation pipes as needed. - Avoid using `@Patch()` for full replacement semantics; prefer `@Put()` when clients must send the complete resource representation. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `DatabaseController` — `integration/inspector/src/database/database.controller.ts`:14 - `DogsController` — `integration/inspector/src/dogs/dogs.controller.ts`:14 - `UsersController` — `integration/inspector/src/users/users.controller.ts`:14 - `UsersController` — `integration/repl/src/users/users.controller.ts`:14 # RawBodyRequest **Kind:** Type **Source:** [`packages/common/interfaces/http/raw-body-request.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/raw-body-request.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts T & { rawBody?: Buffer } ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ExpressController` — `integration/nest-application/raw-body/src/express.controller.ts`:4 - `FastifyController` — `integration/nest-application/raw-body/src/fastify.controller.ts`:4 - `AppController` — `integration/nest-application/use-body-parser/src/app.controller.ts`:4 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # ROUTE_ARGS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L18) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__routeArguments__' ``` ## Value ```ts '__routeArguments__' ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 - `DependenciesScanner` — `packages/core/scanner.ts`:75 - `TCP_DEFAULT_PORT` — `packages/microservices/constants.ts`:3 - `MESSAGE_MAPPING_METADATA` — `packages/websockets/constants.ts`:3 # WsExceptionFilter **Kind:** Interface **Source:** [`packages/common/interfaces/exceptions/ws-exception-filter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/exceptions/ws-exception-filter.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) Interface describing implementation of a Web Sockets exception filter. `WsExceptionFilter` defines the contract for handling exceptions thrown during WebSocket message processing. Implementations receive the thrown exception and the current `ArgumentsHost`, allowing them to inspect the WebSocket client, request data, and emit an appropriate error response. Use this interface when creating custom filters for WebSocket gateways. ## Diagram ```mermaid graph LR A[WebSocket Client Event] --> B[Gateway Handler] B -->|Throws exception| C[WsExceptionFilter.catch] C --> D[ArgumentsHost] D --> E[WebSocket Client] C --> F[Emit or return error response] F --> E ``` ## Usage ```ts import { ArgumentsHost, Catch, UseFilters, WsException, WsExceptionFilter, WebSocketGateway, SubscribeMessage, } from '@nestjs/common'; @Catch(WsException) export class ChatWsExceptionFilter implements WsExceptionFilter { catch(exception: WsException, host: ArgumentsHost) { const client = host.switchToWs().getClient(); const error = exception.getError(); client.emit('exception', { status: 'error', message: typeof error === 'string' ? error : 'Unable to process message', }); } } @WebSocketGateway() @UseFilters(new ChatWsExceptionFilter()) export class ChatGateway { @SubscribeMessage('send-message') sendMessage() { throw new WsException('Message delivery failed'); } } ``` ## AI Coding Instructions - Implement a `catch(exception, host)` method that matches the `WsExceptionFilter` contract. - Use `host.switchToWs()` to access the WebSocket client and incoming message data. - Prefer handling `WsException` explicitly and safely normalize its error payload before sending it to clients. - Emit a consistent error event, such as `exception`, so WebSocket clients can handle failures predictably. - Register filters with `@UseFilters()` on a gateway or individual message handler as needed. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ErrorPayload` — `packages/websockets/exceptions/base-ws-exception-filter.ts`:11 # CustomVersioningOptions **Kind:** Interface **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L76) **Part of:** [Common](subsystem-packages-common) `CustomVersioningOptions` configures custom API version extraction for requests. It is used when `VersioningType.CUSTOM` is selected, allowing applications to define how one or more version values are read from an incoming request. ## Properties | Property | Type | |---|---| | `type` | `VersioningType.CUSTOM` | | `extractor` | `(request: unknown) => string | string[]` | ## Diagram ```mermaid graph LR Request[Incoming Request] --> Extractor[Custom extractor function] Extractor --> Versions[string or string array] Options[CustomVersioningOptions] --> Type[VersioningType.CUSTOM] Options --> Extractor Versions --> Router[Version-aware route matching] ``` ## Usage ```ts import { VersioningType } from '@nestjs/common'; import type { CustomVersioningOptions } from '@nestjs/common'; const versioningOptions: CustomVersioningOptions = { type: VersioningType.CUSTOM, extractor: (request) => { const headers = request as { headers?: Record }; // Read a version such as: x-api-version: 2 return headers.headers?.['x-api-version'] ?? '1'; }, }; // Example application integration: // app.enableVersioning(versioningOptions); ``` ## AI Coding Instructions - Always set `type` to `VersioningType.CUSTOM`; this interface is specifically for custom extraction strategies. - Ensure `extractor` returns a `string` or `string[]`; return an array when a request may map to multiple supported versions. - Keep extractors defensive because `request` is typed as `unknown`; safely narrow or cast the request before accessing headers, URLs, or metadata. - Return version values in the same format used by route version declarations to ensure version-aware routing matches correctly. - Avoid throwing from the extractor for missing version data; return a fallback version or an empty result according to the application's versioning policy. # ENHANCER_KEY_TO_SUBTYPE_MAP **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L26) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts { [GUARDS_METADATA]: 'guard', [INTERCEPTORS_METADATA]: 'interceptor', [PIPES_METADATA]: 'pipe', [EXCEPTION_FILTERS_METADATA]: 'filter', } as const ``` ## Value ```ts { [GUARDS_METADATA]: 'guard', [INTERCEPTORS_METADATA]: 'interceptor', [PIPES_METADATA]: 'pipe', [EXCEPTION_FILTERS_METADATA]: 'filter', } as const ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DependenciesScanner` — `packages/core/scanner.ts`:75 # GlobalPrefixOptions **Kind:** Interface **Source:** [`packages/common/interfaces/global-prefix-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/global-prefix-options.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) `GlobalPrefixOptions` configures routes that should be excluded when applying a global URL prefix. The generic `exclude` array lets applications provide framework-supported route exclusion definitions, such as path strings or route metadata objects. ## Properties | Property | Type | |---|---| | `exclude` | `T[]` | ## Diagram ```mermaid graph LR A[Application] --> B[Set Global Prefix] B --> C[GlobalPrefixOptions] C --> D[exclude: T[]] D --> E[Routes without global prefix] B --> F[All other routes receive prefix] ``` ## Usage ```ts import { GlobalPrefixOptions } from '@nestjs/common'; const prefixOptions: GlobalPrefixOptions = { exclude: ['health', 'metrics'], }; app.setGlobalPrefix('api', prefixOptions); // /api/users // /api/orders // /health // /metrics ``` ## AI Coding Instructions - Use `exclude` to list routes that must remain accessible without the configured global prefix. - Match the generic type `T` to the exclusion format accepted by the consuming API, such as `string` or route exclusion metadata. - Keep operational endpoints such as health checks and metrics routes in `exclude` when external infrastructure expects unprefixed paths. - Verify excluded paths against registered controller routes; incorrect path values will not bypass the global prefix. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ApplicationConfig` — `packages/core/application-config.ts`:13 - `NestApplication` — `packages/core/nest-application.ts`:54 # IntrospectionResult **Kind:** Interface **Source:** [`packages/common/interfaces/modules/introspection-result.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/introspection-result.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) `IntrospectionResult` represents the outcome of an introspection operation within the module system. It exposes the resolved `Scope`, allowing downstream code to inspect or use the context discovered during introspection. ## Properties | Property | Type | |---|---| | `scope` | `Scope` | ## Diagram ```mermaid graph LR I[Introspection Process] --> R[IntrospectionResult] R --> S[scope: Scope] S --> C[Module Context / Resolution Data] ``` ## Usage ```ts import type { IntrospectionResult } from '@common/interfaces/modules/introspection-result.interface'; function useIntrospectionResult(result: IntrospectionResult): void { const scope = result.scope; // Pass the resolved scope to code that needs module context. processScope(scope); } function processScope(scope: IntrospectionResult['scope']): void { console.log('Processing introspected scope:', scope); } ``` ## AI Coding Instructions - Treat `scope` as the primary output of an introspection operation; pass it to downstream module-resolution or analysis logic. - Keep implementations aligned with the `Scope` type rather than replacing it with loosely typed objects. - Do not add unrelated result data to this interface unless it is produced consistently by all introspection implementations. - Use `IntrospectionResult['scope']` when a function only needs the scope type and importing `Scope` directly is unnecessary. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ModuleRefGetOrResolveOpts` — `packages/core/injector/module-ref.ts`:12 # isConstructor **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L47) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function isConstructor(val: any): boolean ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `boolean` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `MetadataScanner` — `packages/core/metadata-scanner.ts`:8 # MODULE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts { IMPORTS: 'imports', PROVIDERS: 'providers', CONTROLLERS: 'controllers', EXPORTS: 'exports', } ``` ## Value ```ts { IMPORTS: 'imports', PROVIDERS: 'providers', CONTROLLERS: 'controllers', EXPORTS: 'exports', } ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DependenciesScanner` — `packages/core/scanner.ts`:75 # NestModule **Kind:** Interface **Source:** [`packages/common/interfaces/modules/nest-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/nest-module.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `CoreModule` — `integration/inspector/src/core/core.module.ts`:8 - `Module` — `packages/core/injector/module.ts`:44 # ScopeOptions **Kind:** Interface **Source:** [`packages/common/interfaces/scope-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/scope-options.interface.ts#L26) **Part of:** [Common](subsystem-packages-common) `ScopeOptions` configures how a scoped dependency or context should behave within the application. It pairs a `Scope` value with a `durable` flag that determines whether the scoped instance or state should be retained beyond its normal lifecycle. ## Properties | Property | Type | |---|---| | `scope` | `Scope` | | `durable` | `boolean` | ## Diagram ```mermaid graph LR A[ScopeOptions] --> B[scope: Scope] A --> C[durable: boolean] B --> D[Defines lifecycle boundary] C --> E[Controls persistence across lifecycle events] ``` ## Usage ```ts import type { ScopeOptions } from '@common/interfaces/scope-options.interface'; import { Scope } from '@common/enums/scope.enum'; const requestScopeOptions: ScopeOptions = { scope: Scope.REQUEST, durable: false, }; const durableScopeOptions: ScopeOptions = { scope: Scope.DEFAULT, durable: true, }; function configureScope(options: ScopeOptions): void { if (options.durable) { console.log(`Keeping ${options.scope} scope state available.`); return; } console.log(`Cleaning up ${options.scope} scope state after use.`); } configureScope(requestScopeOptions); configureScope(durableScopeOptions); ``` ## AI Coding Instructions - Always provide both `scope` and `durable`; neither field should be omitted when constructing `ScopeOptions`. - Use the project’s existing `Scope` enum or type rather than hard-coded string values. - Set `durable` to `true` only when state must survive the normal scope lifecycle, as it may affect cleanup and memory usage. - Keep lifecycle behavior consistent with the consuming dependency injection, request handling, or context-management code. ## How it works `ScopeOptions` is a public TypeScript interface for specifying the injection lifetime of a provider or controller. It contains two optional properties: `scope` and `durable`. [packages/common/interfaces/scope-options.interface.ts:21-37] - `scope?: Scope` selects a lifetime from the accompanying `Scope` enum. The enum defines: - `DEFAULT`: a provider may be shared by multiple classes; its lifetime is tied to the application lifecycle, and the source states that all providers are instantiated after application bootstrap. [packages/common/interfaces/scope-options.interface.ts:4-10] - `TRANSIENT`: a new private provider instance is instantiated for every use. [packages/common/interfaces/scope-options.interface.ts:11-14] - `REQUEST`: a new instance is instantiated for each request-processing pipeline. [packages/common/interfaces/scope-options.interface.ts:15-18] - `durable?: boolean` flags a provider as durable. The interface comments state that this is for use with a custom context-id factory strategy to construct lazy DI subtrees, and only with `scope: Scope.REQUEST`. [packages/common/interfaces/scope-options.interface.ts:31-37] `InjectableOptions` is an alias for `ScopeOptions`, so `@Injectable()` accepts these options. The decorator writes the supplied options as reflection metadata under `SCOPE_OPTIONS_METADATA` on the decorated class. [packages/common/decorators/core/injectable.decorator.ts:13,43-47] `ControllerOptions` extends `ScopeOptions`, and `@Controller()` writes an object containing its `scope` and `durable` values to the same metadata key. [packages/common/decorators/core/controller.decorator.ts:16,151-176] At runtime, core reads that metadata to obtain a class’s scope and durable flag. [packages/core/helpers/get-class-scope.ts:5-8] [packages/core/helpers/is-durable.ts:4-7] When registering a class provider, the module stores both values in its `InstanceWrapper`. [packages/core/injector/module.ts:266-278] For a request-scoped wrapper, an omitted `durable` value is treated as `false`; a supplied value becomes the dependency tree’s durable state. [packages/core/injector/instance-wrapper.ts:245-255] The interface and the decorator implementations shown do not validate option values or throw errors. [packages/common/interfaces/scope-options.interface.ts:26-37] [packages/common/decorators/core/injectable.decorator.ts:43-47] [packages/common/decorators/core/controller.decorator.ts:151-177] # StreamableFileOptions **Kind:** Interface **Source:** [`packages/common/file-stream/interfaces/streamable-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/file-stream/interfaces/streamable-options.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) Options for `StreamableFile` `StreamableFileOptions` configures HTTP response metadata for a `StreamableFile`. It defines the file MIME type, optional content disposition header value(s), and content length so clients can correctly handle streamed file responses. ## Properties | Property | Type | |---|---| | `type` | `string` | | `disposition` | `string | string[]` | | `length` | `number` | ## Diagram ```mermaid graph LR A[File stream or buffer] --> B[StreamableFile] C[StreamableFileOptions] --> B C --> D[type: Content-Type] C --> E[disposition: Content-Disposition] C --> F[length: Content-Length] B --> G[HTTP response] ``` ## Usage ```ts import { Controller, Get, StreamableFile } from '@nestjs/common'; import { createReadStream } from 'node:fs'; import { join } from 'node:path'; import type { StreamableFileOptions } from '@nestjs/common'; @Controller('reports') export class ReportsController { @Get('download') download(): StreamableFile { const filePath = join(process.cwd(), 'reports', 'monthly-report.pdf'); const options: StreamableFileOptions = { type: 'application/pdf', disposition: 'attachment; filename="monthly-report.pdf"', length: 1024 * 256, }; return new StreamableFile(createReadStream(filePath), options); } } ``` ## AI Coding Instructions - Set `type` to a valid MIME type so browsers and API clients interpret the streamed content correctly. - Use `disposition` with `attachment` to force downloads, or `inline` when the file should render in the browser. - Provide `length` when known to enable an accurate `Content-Length` response header. - Ensure the declared `length` matches the actual stream or buffer size; incorrect values can cause incomplete downloads or hanging clients. - Pass these options directly to `StreamableFile` when returning files from NestJS controllers. # ParseFileOptions **Kind:** Interface **Source:** [`packages/common/pipes/file/parse-file-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/parse-file-options.interface.ts#L7) **Part of:** [Common](subsystem-packages-common) `ParseFileOptions` configures how file uploads are validated and how validation failures are reported by file parsing pipes. It defines the validators to run, whether a file is mandatory, the HTTP status code to return on failure, and an optional factory for creating custom exceptions. ## Properties | Property | Type | |---|---| | `validators` | `FileValidator[]` | | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(error: string) => any` | | `fileIsRequired` | `boolean` | ## Diagram ```mermaid graph LR A[Incoming uploaded file] --> B[ParseFilePipe] B --> C{fileIsRequired?} C -->|Missing and required| D[exceptionFactory] C -->|Present| E[validators: FileValidator[]] E -->|Validation passes| F[Continue request handling] E -->|Validation fails| D D --> G[Error with errorHttpStatusCode] ``` ## Usage ```ts import { ParseFilePipe, MaxFileSizeValidator, FileTypeValidator, HttpStatus, } from '@nestjs/common'; const fileValidationOptions = { validators: [ new MaxFileSizeValidator({ maxSize: 5 * 1024 * 1024 }), new FileTypeValidator({ fileType: /(jpg|jpeg|png)$/ }), ], fileIsRequired: true, errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY, exceptionFactory: (error: string) => ({ statusCode: HttpStatus.UNPROCESSABLE_ENTITY, message: `Invalid upload: ${error}`, }), }; const filePipe = new ParseFilePipe(fileValidationOptions); ``` ## AI Coding Instructions - Provide `validators` in the intended execution order; each validator should enforce one clear file constraint. - Set `fileIsRequired` to `false` for optional upload endpoints, and ensure downstream code handles an absent file. - Use `errorHttpStatusCode` consistently with the API's error-handling conventions, such as `BAD_REQUEST` or `UNPROCESSABLE_ENTITY`. - Implement `exceptionFactory` when the default validation exception format does not match the application's error response contract. - Ensure custom exception factories return or throw values compatible with the framework's HTTP exception handling. # RequestHandler **Kind:** Type **Source:** [`packages/common/interfaces/http/http-server.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/http-server.interface.ts#L11) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts ( req: TRequest, res: TResponse, next?: Function, ) => any ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AbstractHttpAdapter` — `packages/core/adapters/http-adapter.ts`:8 # ResponseDecoratorOptions **Kind:** Interface **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L13) **Part of:** [Common](subsystem-packages-common) The `@Response()`/`@Res` parameter decorator options. `ResponseDecoratorOptions` configures the behavior of NestJS's `@Response()` (or `@Res()`) parameter decorator. Its `passthrough` option determines whether Nest continues its normal response-processing pipeline after injecting the underlying platform response object into a controller handler. ## Properties | Property | Type | |---|---| | `passthrough` | `boolean` | ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Controller Handler] B --> C["@Res() / @Response()"] C --> D[ResponseDecoratorOptions] D --> E{passthrough?} E -->|false or omitted| F[Handler manages response manually] E -->|true| G[Nest processes returned value] G --> H[HTTP Response] F --> H ``` ## Usage ```ts import { Controller, Get, Res } from '@nestjs/common'; import type { Response } from 'express'; @Controller('health') export class HealthController { @Get() check(@Res({ passthrough: true }) response: Response) { response.setHeader('X-Service-Status', 'healthy'); // Nest still serializes and sends this returned value. return { status: 'ok' }; } } ``` ## AI Coding Instructions - Use `@Res({ passthrough: true })` when a handler needs to set headers, cookies, or status codes while still returning a value for Nest to serialize. - Without `passthrough: true`, the handler is responsible for sending the response, such as with `response.json()` or `response.send()`. - Avoid mixing manual response sending with returned response data when passthrough is enabled; this can cause duplicate-response errors. - Keep response types aligned with the configured HTTP platform, such as Express `Response` or Fastify `FastifyReply`. # SerializeOptions **Kind:** Function **Source:** [`packages/common/serializer/decorators/serialize-options.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/serializer/decorators/serialize-options.decorator.ts#L8) **Part of:** [Common](subsystem-packages-common) ## Signature ```ts function SerializeOptions(options: ClassSerializerContextOptions) ``` ## Parameters | Name | Type | |---|---| | `options` | `ClassSerializerContextOptions` | # StreamableHandlerResponse **Kind:** Interface **Source:** [`packages/common/file-stream/interfaces/streamable-handler-response.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/file-stream/interfaces/streamable-handler-response.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) `StreamableHandlerResponse` defines the minimal response contract required by file-stream handlers. It exposes connection state, HTTP status information, and methods for sending a response body or closing the response stream. ## Properties | Property | Type | |---|---| | `destroyed` | `boolean` | | `headersSent` | `boolean` | | `statusCode` | `number` | | `send` | `(body: string) => void` | | `end` | `() => void` | ## Diagram ```mermaid graph LR Handler[File Stream Handler] --> Response[StreamableHandlerResponse] Response --> State[destroyed / headersSent] Response --> Status[statusCode] Response --> Send[send(body)] Response --> End[end()] Send --> Client[HTTP Client] End --> Client ``` ## Usage ```ts import type { StreamableHandlerResponse } from './interfaces/streamable-handler-response.interface'; function sendStreamError( response: StreamableHandlerResponse, message: string, ): void { if (response.destroyed || response.headersSent) { response.end(); return; } response.statusCode = 500; response.send(message); response.end(); } ``` ## AI Coding Instructions - Check `destroyed` before writing to avoid sending data through a closed connection. - Respect `headersSent`; do not change `statusCode` after response headers have been sent. - Set `statusCode` before calling `send()` when returning non-default HTTP responses. - Call `end()` when the handler has finished writing or needs to terminate the stream. - Keep implementations compatible with the minimal interface rather than depending on framework-specific response APIs. ## How it works ## Contract `StreamableHandlerResponse` is an exported TypeScript interface describing the response object accepted by `StreamableFile` error handlers. It declares five required members: `destroyed`, `headersSent`, `statusCode`, `send`, and `end`. [packages/common/file-stream/interfaces/streamable-handler-response.interface.ts:1-12] - `destroyed: boolean` indicates whether the connection is destroyed. [packages/common/file-stream/interfaces/streamable-handler-response.interface.ts:2-3] - `headersSent: boolean` indicates whether response headers have already been sent. [packages/common/file-stream/interfaces/streamable-handler-response.interface.ts:4-5] - `statusCode: number` is the status code to send when headers are flushed. [packages/common/file-stream/interfaces/streamable-handler-response.interface.ts:6-7] - `send(body: string): void` sends a string response body. [packages/common/file-stream/interfaces/streamable-handler-response.interface.ts:8-9] - `end(): void` signals that response headers and body have been fully sent. [packages/common/file-stream/interfaces/streamable-handler-response.interface.ts:10-11] ## Use by `StreamableFile` `StreamableFile` types both its `errorHandler` getter and `setErrorHandler()` callback parameter as functions receiving an `Error` and a `StreamableHandlerResponse`. [packages/common/file-stream/streamable-file.ts:70-80] Its default error handler reads `destroyed` first and returns without changing the response when it is `true`. [packages/common/file-stream/streamable-file.ts:20-23] If the connection is not destroyed but `headersSent` is `true`, it calls `end()` and returns. [packages/common/file-stream/streamable-file.ts:24-27] Otherwise, it sets `statusCode` to `HttpStatus.BAD_REQUEST` and calls `send()` with `err.message`. [packages/common/file-stream/streamable-file.ts:29-30] The Express adapter attaches this handler to the stream’s one-time `error` event and passes its `response` object as the second argument. [packages/platform-express/adapters/express-adapter.ts:110-118] # TransformerPackage **Kind:** Interface **Source:** [`packages/common/interfaces/external/transformer-package.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/transformer-package.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) # UriVersioningOptions **Kind:** Interface **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L48) **Part of:** [Common](subsystem-packages-common) `UriVersioningOptions` configures URI-based API versioning. It requires the versioning strategy to be `VersioningType.URI` and optionally customizes—or disables—the URI prefix used before the version segment. ## Properties | Property | Type | |---|---| | `type` | `VersioningType.URI` | | `prefix` | `string | false` | ## Diagram ```mermaid graph LR A[Application Versioning Configuration] --> B[UriVersioningOptions] B --> C[type: VersioningType.URI] B --> D[prefix: string | false] C --> E[Version read from request URI] D --> F[Generated route path] E --> F ``` ## Usage ```ts import { VersioningType } from '@nestjs/common'; import type { UriVersioningOptions } from '@nestjs/common'; const versioningOptions: UriVersioningOptions = { type: VersioningType.URI, prefix: 'v', }; // Produces routes such as: /v1/users app.enableVersioning(versioningOptions); ``` ## AI Coding Instructions - Always set `type` to `VersioningType.URI`; this interface is only valid for URI-based versioning. - Use a string `prefix` such as `'v'` when versioned routes should look like `/v1/resource`. - Set `prefix: false` when the version should appear without a prefix, such as `/1/resource`. - Pass these options to the application's versioning configuration, typically through `app.enableVersioning()`. - Keep the configured prefix consistent with API gateway routes, documentation, and client URL construction. ## How it works `UriVersioningOptions` is a public TypeScript interface for selecting URI-based API versioning. Its required discriminant is `type: VersioningType.URI`; its only URI-specific setting is the optional `prefix`, typed as `string | false`. [packages/common/interfaces/version-options.interface.ts:45-58](packages/common/interfaces/version-options.interface.ts#L45-L58) `VersioningType.URI` is the `URI` member of the versioning-type enum. [packages/common/enums/version-type.enum.ts:4-8](packages/common/enums/version-type.enum.ts#L4-L8) - Set `prefix` to a string to prepend that string to a route’s version segment. When absent, route construction selects `'v'`; when `false`, it selects an empty prefix. [packages/core/router/route-path-factory.ts:86-96](packages/core/router/route-path-factory.ts#L86-L96) - URI versioning alters generated paths only when route metadata has a truthy method or controller version and the configured type is `URI`. The version segment is placed before module, controller, and method path fragments. [packages/core/router/route-path-factory.ts:27-57](packages/core/router/route-path-factory.ts#L27-L57) - A method-level version takes precedence over a controller-level version. [packages/core/router/route-path-factory.ts:80-84](packages/core/router/route-path-factory.ts#L80-L84) Multiple versions generate one path per version. [packages/core/router/route-path-factory.ts:34-44](packages/core/router/route-path-factory.ts#L34-L44) - `VERSION_NEUTRAL` skips the version segment; in an array, it creates an additional unversioned path alongside versioned paths. [packages/core/router/route-path-factory.ts:38-51](packages/core/router/route-path-factory.ts#L38-L51) - The interface is one branch of `VersioningOptions`, which also includes the shared optional `defaultVersion`. [packages/common/interfaces/version-options.interface.ts:93-110](packages/common/interfaces/version-options.interface.ts#L93-L110) When versioning is configured, controller version metadata falls back to that shared default. [packages/core/router/routes-resolver.ts:225-235](packages/core/router/routes-resolver.ts#L225-L235) - `NestApplication.enableVersioning()` defaults to `{ type: VersioningType.URI }` when called without options and stores the supplied options in application configuration. [packages/core/nest-application.ts:288-293](packages/core/nest-application.ts#L288-L293) [packages/core/application-config.ts:138-145](packages/core/application-config.ts#L138-L145) No validation, normalization, or explicit error handling for `prefix` appears in the URI-prefix selection code; a defined string is returned as-is. [packages/core/router/route-path-factory.ts:86-96](packages/core/router/route-path-factory.ts#L86-L96) # ValidationPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/validation.pipe.ts#L26) **Part of:** [Common](subsystem-packages-common) `ValidationPipeOptions` configures how NestJS's `ValidationPipe` validates incoming request data and transforms payloads into typed DTO instances. It controls validation behavior, error responses, class-transformer integration, and optional custom validator or transformer package implementations. ## Properties | Property | Type | |---|---| | `transform` | `boolean` | | `disableErrorMessages` | `boolean` | | `transformOptions` | `ClassTransformOptions` | | `errorHttpStatusCode` | `ErrorHttpStatusCode` | | `exceptionFactory` | `(errors: ValidationError[]) => any` | | `validateCustomDecorators` | `boolean` | | `expectedType` | `Type` | | `validatorPackage` | `ValidatorPackage` | | `transformerPackage` | `TransformerPackage` | ## Diagram ```mermaid graph LR Request[Incoming request payload] --> Pipe[ValidationPipe] Pipe --> Transform{transform enabled?} Transform -- Yes --> DTO[Transform payload to DTO instance] Transform -- No --> Validate[Validate raw payload] DTO --> Validate Validate --> Valid{Validation succeeds?} Valid -- Yes --> Handler[Route handler] Valid -- No --> Factory[exceptionFactory] Factory --> Error[HTTP error response] Options[ValidationPipeOptions] --> Pipe Options --> Transform Options --> Validate Options --> Factory ``` ## Usage ```ts import { BadRequestException, ValidationPipe, ValidationError, } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes( new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true, }, disableErrorMessages: false, validateCustomDecorators: true, exceptionFactory: (errors: ValidationError[]) => { return new BadRequestException({ message: 'Request validation failed', errors, }); }, }), ); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Enable `transform` when controllers expect DTO instances or typed primitive conversion, and configure `transformOptions` for behaviors such as implicit conversion. - Use DTO validation decorators from `class-validator`; set `validateCustomDecorators` when custom decorators must be evaluated by the pipe. - Provide an `exceptionFactory` when the application requires a consistent validation-error response format. - Avoid enabling detailed error messages in production when validation errors could expose internal request or DTO details; use `disableErrorMessages` where appropriate. - Use `validatorPackage` and `transformerPackage` only when integrating compatible custom implementations of `class-validator` or `class-transformer`. # VersionOptions **Kind:** Interface **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L21) **Part of:** [Common](subsystem-packages-common) `VersionOptions` defines the version configuration used by components that need to target or describe a specific API or application version. It provides a single `version` property typed as `VersionValue`, ensuring version values remain consistent across the system. ## Properties | Property | Type | |---|---| | `version` | `VersionValue` | ## Diagram ```mermaid graph LR A[Consumer Configuration] --> B[VersionOptions] B --> C[version: VersionValue] C --> D[Version-Aware Component] ``` ## Usage ```ts import type { VersionOptions } from '@package/common'; const options: VersionOptions = { version: 'v1', }; function configureVersion(options: VersionOptions) { console.log(`Using version: ${options.version}`); } configureVersion(options); ``` ## AI Coding Instructions - Provide a valid `VersionValue` when constructing `VersionOptions`; do not use arbitrary strings unless they are supported by that type. - Use `VersionOptions` for function parameters and configuration objects that require version-specific behavior. - Keep version handling centralized through this interface rather than introducing duplicate `version` field definitions. - Import `VersionOptions` as a type-only import when it is used exclusively for TypeScript type checking. ## How it works `VersionOptions` is a public TypeScript interface for attaching an optional API version to a controller. It declares one property, `version?: VersionValue`. [`packages/common/interfaces/version-options.interface.ts:21-32`](packages/common/interfaces/version-options.interface.ts#L21-L32) - `version` may be a string, the `VERSION_NEUTRAL` symbol, or an array containing strings and/or that symbol. [`packages/common/interfaces/version-options.interface.ts:8-16`](packages/common/interfaces/version-options.interface.ts#L8-L16) - `VERSION_NEUTRAL` denotes routes that work with any request version, including no version. [`packages/common/interfaces/version-options.interface.ts:3-8`](packages/common/interfaces/version-options.interface.ts#L3-L8) - `ControllerOptions` extends `VersionOptions`, so it can be passed as `@Controller({ version: ... })`. [`packages/common/decorators/core/controller.decorator.ts:8-16`](packages/common/decorators/core/controller.decorator.ts#L8-L16) The decorator stores this value under `VERSION_METADATA`; when the value is an array, it removes duplicate entries first. [`packages/common/decorators/core/controller.decorator.ts:151-177`](packages/common/decorators/core/controller.decorator.ts#L151-L177) - A method-level version takes precedence over the controller-level version during route construction. [`packages/core/router/route-path-factory.ts:80-84`](packages/core/router/route-path-factory.ts#L80-L84) - Version-aware routing runs only when a route has either a method or controller version **and** application versioning options exist. Non-URI strategies are passed to the HTTP adapter’s version filter. [`packages/core/router/router-explorer.ts:192-208`](packages/core/router/router-explorer.ts#L192-L208) - With URI versioning, string versions become path segments using the configured prefix (default `v`); neutral versions add no version segment. [`packages/core/router/route-path-factory.ts:27-52`](packages/core/router/route-path-factory.ts#L27-L52) [`packages/core/router/route-path-factory.ts:86-95`](packages/core/router/route-path-factory.ts#L86-L95) - The interface itself contains no runtime validation, error handling, or side effects; it is only a type declaration. [`packages/common/interfaces/version-options.interface.ts:21-32`](packages/common/interfaces/version-options.interface.ts#L21-L32) # WsMessageHandler **Kind:** Interface **Source:** [`packages/common/interfaces/websockets/web-socket-adapter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/websockets/web-socket-adapter.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) `WsMessageHandler` describes a WebSocket message handler registered by an adapter or gateway. It pairs an incoming message payload with a callback that produces either an `Observable` or `Promise`, and records whether acknowledgement handling is performed manually. ## Properties | Property | Type | |---|---| | `message` | `T` | | `callback` | `(...args: any[]) => Observable | Promise` | | `isAckHandledManually` | `boolean` | ## Diagram ```mermaid graph LR Client[WebSocket Client] --> Message[Incoming Message] Message --> Handler[WsMessageHandler] Handler --> Payload[message: T] Handler --> Callback[callback(...args)] Callback --> Result[Observable or Promise] Handler --> AckFlag[isAckHandledManually] AckFlag --> Ack[WebSocket Acknowledgement] ``` ## Usage ```ts import { Observable, of } from 'rxjs'; import { WsMessageHandler } from './web-socket-adapter.interface'; interface ChatMessage { roomId: string; text: string; } const handler: WsMessageHandler = { message: { roomId: 'general', text: 'Hello, everyone!', }, callback: (client, payload: ChatMessage): Observable => { console.log(`Received message for ${payload.roomId}: ${payload.text}`); return of({ event: 'chat.message.received', data: { accepted: true }, }); }, isAckHandledManually: false, }; ``` ## AI Coding Instructions - Keep `message` strongly typed with the generic `T` so handler callbacks receive predictable payload data. - Ensure `callback` returns either an `Observable` or a `Promise`; do not return plain synchronous values. - Set `isAckHandledManually` to `true` only when the callback explicitly sends or manages the WebSocket acknowledgement. - Preserve callback argument ordering expected by the surrounding WebSocket adapter or gateway integration. ## How it works `WsMessageHandler` is an exported, public WebSocket message-handler shape with a generic message identifier type that defaults to `string`. [web-socket-adapter.interface.ts:3-10] - `message` is the message identifier and has type `T`. [web-socket-adapter.interface.ts:6-8] - `callback` accepts any number of arguments and must return either `Observable` or `Promise`. [web-socket-adapter.interface.ts:8] - `isAckHandledManually` is a required boolean. [web-socket-adapter.interface.ts:9] `WebSocketAdapter.bindMessageHandlers` accepts an array of these handlers together with a function that transforms callback data into an `Observable`. [web-socket-adapter.interface.ts:23-27] The WebSocket controller binds each callback to the gateway instance and connected client, retains `message` and `isAckHandledManually`, then passes those handler objects to the configured adapter. [web-sockets-controller.ts:172-187] Handler metadata is discovered only for gateway methods marked with message-mapping metadata; the `message` field comes from that method’s message metadata. [gateway-metadata-explorer.ts:38-57] `isAckHandledManually` is set when the method’s parameter metadata contains an ACK parameter type. [gateway-metadata-explorer.ts:60-78] In the Socket.IO adapter, each handler listens on its `message` event, invokes `callback(data, ack)`, and sends non-null transformed results either as a named socket event or through the acknowledgement function. [io-adapter.ts:50-68] When `isAckHandledManually` is `true`, that adapter skips its automatic call to the acknowledgement function. [io-adapter.ts:61-67] In the `ws` adapter, handlers are indexed by `message`; for a parsed inbound event, the matching callback is invoked with the parsed data and event name, and non-null transformed responses are serialized and sent while the client is open. [ws-adapter.ts:128-151][ws-adapter.ts:154-169] This adapter does not read `isAckHandledManually` in its message-handling code. [ws-adapter.ts:133-166] The interface declaration itself contains no validation, error handling, or side effects. [web-socket-adapter.interface.ts:6-10] ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `BaseWsInstance` — `packages/websockets/adapters/ws-adapter.ts`:8 # ASYNC_OPTIONS_METADATA_KEYS **Kind:** Constant **Source:** [`packages/common/module-utils/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/constants.ts#L11) **Part of:** [Common](subsystem-packages-common) List of keys that are specific to ConfigurableModuleAsyncOptions and should be excluded when extracting user-defined extras. `ASYNC_OPTIONS_METADATA_KEYS` defines the option property names reserved by `ConfigurableModuleAsyncOptions`. These keys are excluded when the module utilities extract user-defined “extras,” ensuring framework configuration fields such as factories and imports are not treated as custom module options. ## Definition ```ts [ 'useFactory', 'useClass', 'useExisting', 'inject', 'imports', 'provideInjectionTokensFrom', ] as const ``` ## Value ```ts [ 'useFactory', 'useClass', 'useExisting', 'inject', 'imports', 'provideInjectionTokensFrom', ] as const ``` ## Diagram ```mermaid graph LR A[ConfigurableModuleAsyncOptions] --> B[Read option keys] B --> C{Key in ASYNC_OPTIONS_METADATA_KEYS?} C -->|Yes| D[Keep as framework async metadata] C -->|No| E[Extract as user-defined extras] ``` ## Usage ```ts import { ASYNC_OPTIONS_METADATA_KEYS } from './constants'; const asyncOptions = { imports: [ConfigModule], inject: [ConfigService], useFactory: (configService: ConfigService) => ({ apiUrl: configService.get('API_URL'), }), isGlobal: true, retryAttempts: 3, }; const extras = Object.fromEntries( Object.entries(asyncOptions).filter( ([key]) => !ASYNC_OPTIONS_METADATA_KEYS.includes(key), ), ); // { isGlobal: true, retryAttempts: 3 } console.log(extras); ``` ## AI Coding Instructions - Treat this constant as the source of truth for async module option keys owned by the framework. - Add new keys here when extending `ConfigurableModuleAsyncOptions` with metadata that must not become user-defined extras. - Do not include keys intended to be forwarded to the generated module’s custom options. - Preserve the key names exactly as they appear in the async options interface and extraction logic. - Update related option-extraction tests whenever this list changes. # LOG_LEVELS **Kind:** Constant **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts [ 'verbose', 'debug', 'log', 'warn', 'error', 'fatal', ] as const satisfies string[] ``` ## Value ```ts [ 'verbose', 'debug', 'log', 'warn', 'error', 'fatal', ] as const satisfies string[] ``` # MediaTypeVersioningOptions **Kind:** Interface **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L63) **Part of:** [Common](subsystem-packages-common) `MediaTypeVersioningOptions` configures media type–based API versioning. It identifies the versioning strategy with `type: VersioningType.MEDIA_TYPE` and defines the media type parameter key used to extract the requested API version from request headers. ## Properties | Property | Type | |---|---| | `type` | `VersioningType.MEDIA_TYPE` | | `key` | `string` | ## Diagram ```mermaid graph LR Client[HTTP Client] --> Header[Accept / Content-Type Header] Header --> Key[Media Type Parameter Key] Key --> Version[Requested API Version] Version --> Router[Versioned Route Handler] Options[MediaTypeVersioningOptions] --> Type["type: VersioningType.MEDIA_TYPE"] Options --> KeyName["key: string"] KeyName --> Key ``` ## Usage ```ts import { VersioningType } from '@nestjs/common'; import type { MediaTypeVersioningOptions } from '@nestjs/common'; const versioningOptions: MediaTypeVersioningOptions = { type: VersioningType.MEDIA_TYPE, key: 'v', }; // Example request header: // Accept: application/json;v=2 // // The application resolves this request to API version "2". ``` ## AI Coding Instructions - Always set `type` to `VersioningType.MEDIA_TYPE`; this interface is specifically for media type versioning. - Choose a stable, short `key` such as `v` and keep it consistent across clients and API documentation. - Ensure clients send the configured parameter in an appropriate media type header, such as `Accept: application/json;v=2`. - Use this option with the framework's global versioning configuration rather than implementing version parsing manually. # MODULE_PATH **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L38) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__module_path__' ``` ## Value ```ts '__module_path__' ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `ROUTES` — `packages/core/router/router-module.ts`:9 - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 # NestHybridApplicationOptions **Kind:** Interface **Source:** [`packages/common/interfaces/microservices/nest-hybrid-application-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/microservices/nest-hybrid-application-options.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) `NestHybridApplicationOptions` configures how a NestJS hybrid application connects its microservice layer to the main HTTP application. It controls whether application-level configuration is inherited and whether microservice initialization is deferred until explicitly started. ## Properties | Property | Type | |---|---| | `inheritAppConfig` | `boolean` | | `deferInitialization` | `boolean` | ## Diagram ```mermaid graph LR A[Nest Application] --> B[NestHybridApplicationOptions] B --> C[inheritAppConfig] B --> D[deferInitialization] C --> E[Share application configuration with microservice] D --> F[Delay microservice initialization] A --> G[Connected Microservice] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { Transport } from '@nestjs/microservices'; import type { NestHybridApplicationOptions } from '@nestjs/common'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const hybridOptions: NestHybridApplicationOptions = { inheritAppConfig: true, deferInitialization: false, }; app.connectMicroservice( { transport: Transport.TCP, }, hybridOptions, ); await app.startAllMicroservices(); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Set `inheritAppConfig` to `true` when the connected microservice should reuse global pipes, guards, filters, and interceptors configured on the main application. - Use `deferInitialization` when microservice startup must be controlled manually, such as when configuring dependencies before calling `startAllMicroservices()`. - Ensure `startAllMicroservices()` is called before expecting the connected transport to receive messages. - Keep hybrid application options separate from transport-specific microservice options passed as the first argument to `connectMicroservice()`. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestApplication` — `packages/core/nest-application.ts`:54 # NestMicroserviceOptions **Kind:** Type **Source:** [`packages/common/interfaces/microservices/nest-microservice-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/microservices/nest-microservice-options.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts NestApplicationContextOptions ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `IEntryNestModule` — `packages/core/nest-factory.ts`:39 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingModule` — `packages/testing/testing-module.ts`:26 # OptionalFactoryDependency **Kind:** Type **Source:** [`packages/common/interfaces/modules/optional-factory-dependency.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/modules/optional-factory-dependency.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts { token: InjectionToken; optional: boolean; } ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `InjectorDependency` — `packages/core/injector/injector.ts`:51 # PATH_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L10) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'path' ``` ## Value ```ts 'path' ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `RouteDefinition` — `packages/core/router/router-explorer.ts`:49 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 # RouteParamMetadata **Kind:** Interface **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L25) **Part of:** [Common](subsystem-packages-common) `RouteParamMetadata` describes metadata for a parameter in an HTTP route handler. It records the parameter’s zero-based position (`index`) and associated route parameter configuration (`data`) so the framework can resolve and inject request values into the correct handler argument. ## Properties | Property | Type | |---|---| | `index` | `number` | | `data` | `ParamData` | ## Diagram ```mermaid graph LR Decorator[Route parameter decorator] --> Metadata[RouteParamMetadata] Metadata --> Index[index: parameter position] Metadata --> Data[data: ParamData] Metadata --> Resolver[Route argument resolver] Resolver --> Handler[Controller handler argument] ``` ## Usage ```ts import type { RouteParamMetadata } from './route-params.decorator'; const userIdParameter: RouteParamMetadata = { index: 0, data: 'id', }; // Used by route metadata processing to inject req.params.id // into the first controller method argument. ``` ## AI Coding Instructions - Keep `index` aligned with the decorated method parameter’s zero-based position. - Use `data` values compatible with the `ParamData` type; do not introduce untyped parameter keys. - Preserve this metadata shape when extending route parameter decorators, since argument resolvers depend on it. - Avoid changing property names or semantics without updating metadata readers and request-argument resolution logic. ## How it works `RouteParamMetadata` is an exported TypeScript interface for an entry in HTTP route-argument metadata. Its declared shape has: - `index: number` — the zero-based route-handler argument position. [packages/common/decorators/http/route-params.decorator.ts:25-28] - `data?: ParamData` — optional decorator data, where `ParamData` is `object | string | number`. [packages/common/decorators/http/route-params.decorator.ts:24-28] Standard route-parameter decorators read existing `ROUTE_ARGS_METADATA`, add an entry keyed as `${paramtype}:${index}`, and write the resulting object back through `Reflect.defineMetadata`. The entry records `index`, `data`, and a `pipes` array. [packages/common/decorators/http/route-params.decorator.ts:47-64] The `ROUTE_ARGS_METADATA` metadata key is the string `__routeArguments__`. [packages/common/constants.ts:18] Although `pipes` is stored and later read, it is not declared in `RouteParamMetadata`. [packages/common/decorators/http/route-params.decorator.ts:25-28] [packages/common/decorators/http/route-params.decorator.ts:37-44] Custom parameter decorators similarly create entries with `index`, `factory`, `data`, and `pipes`; `factory` is also not declared by the interface. [packages/common/utils/assign-custom-metadata.util.ts:9-25] At HTTP handler setup, the router reads these entries, uses the largest recorded `index` plus one as the argument-array length, and converts each metadata entry into parameter-processing details. [packages/core/router/router-execution-context.ts:191-221] [packages/core/helpers/context-utils.ts:52-56] For standard entries, it passes `data` and the parameter type to `RouteParamsFactory`; for example, `data` selects a body, path, query, host, or header property when it is truthy. [packages/core/router/router-execution-context.ts:315-327] [packages/core/router/route-params-factory.ts:21-44] During invocation, the extracted value is written to `args[index]`; pipeable parameter types run global and parameter pipes first. [packages/core/router/router-execution-context.ts:392-415] The interface itself has no runtime validation, executable behavior, thrown errors, or side effects; those occur in the decorators and router code that create and consume objects shaped like it. [packages/common/decorators/http/route-params.decorator.ts:25-28] ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 # RpcExceptionFilterMetadata **Kind:** Interface **Source:** [`packages/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) `RpcExceptionFilterMetadata` describes the runtime metadata Nest uses to connect an RPC exception filter's `catch` method with the exception classes it handles. It is typically produced during exception-filter discovery and consumed by the RPC exception handling pipeline to select an appropriate filter for a thrown error. ## Properties | Property | Type | |---|---| | `func` | `RpcExceptionFilter['catch']` | | `exceptionMetatypes` | `Type[]` | ## Diagram ```mermaid graph LR E[RPC handler throws exception] --> H[RPC exception handler] H --> M[RpcExceptionFilterMetadata] M --> T[exceptionMetatypes] M --> F[func: filter.catch] T -->|matches exception type| F F --> R[RPC error response] ``` ## Usage ```ts import { RpcException } from '@nestjs/microservices'; import type { RpcExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface'; const rpcExceptionFilter = { catch(exception: RpcException) { return { status: 'error', message: exception.message, }; }, }; const metadata: RpcExceptionFilterMetadata = { func: rpcExceptionFilter.catch, exceptionMetatypes: [RpcException], }; // The RPC exception layer can use `exceptionMetatypes` to determine // whether this filter should handle a thrown exception, then invoke `func`. ``` ## AI Coding Instructions - Keep `func` assigned to an exception filter's `catch` method and ensure its signature remains compatible with `RpcExceptionFilter['catch']`. - Populate `exceptionMetatypes` with exception constructors, not instances or string names. - Preserve the relationship between each filter callback and its handled exception types when creating or transforming metadata. - Use this metadata in RPC exception resolution paths; do not use it as a general HTTP or WebSocket exception-filter contract. ## How it works ## `RpcExceptionFilterMetadata` `RpcExceptionFilterMetadata` is an exported TypeScript interface for one RPC exception-filter entry. It contains a filter callback and the exception constructor types associated with that callback. [packages/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts:4-7](packages/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts#L4-L7) ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RpcExceptionsHandler` — `packages/microservices/exceptions/rpc-exceptions-handler.ts`:13 # VERSION_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L43) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__version__' ``` ## Value ```ts '__version__' ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 - `modulesContainer` — `packages/core/middleware/routes-mapper.ts`:148 # BeforeApplicationShutdown **Kind:** Interface **Source:** [`packages/common/interfaces/hooks/before-application-shutdown.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/hooks/before-application-shutdown.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `callBeforeAppShutdownHook` — `packages/core/hooks/before-app-shutdown.hook.ts`:49 # ClassSerializerInterceptorOptions **Kind:** Interface **Source:** [`packages/common/serializer/class-serializer.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/common/serializer/class-serializer.interceptor.ts#L27) **Part of:** [Common](subsystem-packages-common) `ClassSerializerInterceptorOptions` configures the transformer implementation used by NestJS's `ClassSerializerInterceptor`. Its `transformerPackage` field allows applications to provide a compatible serialization package, such as `class-transformer`, when customizing response serialization behavior. ## Properties | Property | Type | |---|---| | `transformerPackage` | `TransformerPackage` | ## Diagram ```mermaid graph LR A[Controller Response] --> B[ClassSerializerInterceptor] B --> C[ClassSerializerInterceptorOptions] C --> D[transformerPackage] D --> E[Transformer Package] E --> F[Serialized HTTP Response] ``` ## Usage ```ts import { ClassSerializerInterceptor } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import * as classTransformer from 'class-transformer'; const serializerOptions = { transformerPackage: classTransformer, }; const serializerInterceptor = new ClassSerializerInterceptor( new Reflector(), serializerOptions, ); // Register globally or apply with @UseInterceptors(serializerInterceptor). ``` ## AI Coding Instructions - Provide a `transformerPackage` implementation compatible with the APIs expected by `ClassSerializerInterceptor`. - Use `class-transformer` as the standard package unless the application intentionally supplies an alternative compatible implementation. - Ensure the configured package is installed and available at runtime; missing transformer dependencies can break response serialization. - Apply the interceptor globally or at controller/route level when serialized DTO output is required. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Injected or called by (1) - `ClassSerializerInterceptor` — `packages/common/serializer/class-serializer.interceptor.ts`:34 # ConfigurableModuleOptionsFactory **Kind:** Type **Source:** [`packages/common/module-utils/interfaces/configurable-module-async-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/interfaces/configurable-module-async-options.interface.ts#L15) **Part of:** [Common](subsystem-packages-common) Interface that must be implemented by the module options factory class. Method key varies depending on the "FactoryClassMethodKey" type argument. `ConfigurableModuleOptionsFactory` defines the contract for classes that asynchronously produce options for a configurable NestJS module. The factory method name is determined by the `FactoryClassMethodKey` generic type, allowing modules to use descriptive methods such as `createOptions` or `createCacheOptions`. ## Definition ```ts Record< `${FactoryClassMethodKey}`, () => Promise | ModuleOptions > ``` ## Diagram ```mermaid graph LR Consumer[Module Consumer] --> AsyncOptions[Async Module Options] AsyncOptions --> FactoryClass[Factory Class] FactoryClass --> FactoryInterface[ConfigurableModuleOptionsFactory] FactoryInterface --> FactoryMethod["FactoryClassMethodKey method"] FactoryMethod --> ModuleOptions[Resolved Module Options] ModuleOptions --> ConfigurableModule[Configurable Module] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ConfigurableModuleOptionsFactory } from '@nestjs/common'; interface DatabaseModuleOptions { host: string; port: number; database: string; } @Injectable() export class DatabaseOptionsFactory implements ConfigurableModuleOptionsFactory< DatabaseModuleOptions, 'createDatabaseOptions' > { async createDatabaseOptions(): Promise { return { host: process.env.DATABASE_HOST ?? 'localhost', port: Number(process.env.DATABASE_PORT ?? 5432), database: process.env.DATABASE_NAME ?? 'app', }; } } ``` ## AI Coding Instructions - Implement the method name specified by the `FactoryClassMethodKey` generic argument exactly; NestJS uses this key to invoke the factory. - Return the module options object directly or wrap it in a `Promise` for asynchronous configuration loading. - Mark factory classes with `@Injectable()` when they depend on other providers, such as `ConfigService`. - Keep configuration validation and environment-variable parsing inside the factory method before returning module options. - Ensure the resolved options type matches the configurable module's expected options interface. # CorsOptionsDelegate **Kind:** Interface **Source:** [`packages/common/interfaces/external/cors-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/cors-options.interface.ts#L61) **Part of:** [Common](subsystem-packages-common) ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 # ErrorHandler **Kind:** Type **Source:** [`packages/common/interfaces/http/http-server.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/http-server.interface.ts#L5) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts ( error: any, req: TRequest, res: TResponse, next?: Function, ) => any ``` # HeaderVersioningOptions **Kind:** Interface **Source:** [`packages/common/interfaces/version-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/version-options.interface.ts#L37) **Part of:** [Common](subsystem-packages-common) `HeaderVersioningOptions` configures header-based API versioning. It identifies the HTTP header that contains the requested API version and fixes the versioning strategy to `VersioningType.HEADER`. ## Properties | Property | Type | |---|---| | `type` | `VersioningType.HEADER` | | `header` | `string` | ## Diagram ```mermaid graph LR Client[HTTP Client] -->|Sends version header| Request[Incoming Request] Request --> HeaderName[Configured header] HeaderName --> VersionResolver[Header Version Resolver] VersionResolver --> Route[Versioned Route Handler] Options[HeaderVersioningOptions] -->|type: VersioningType.HEADER| VersionResolver Options -->|header: string| HeaderName ``` ## Usage ```ts import { VersioningType } from '@nestjs/common'; import type { HeaderVersioningOptions } from '@nestjs/common/interfaces/version-options.interface'; const versioningOptions: HeaderVersioningOptions = { type: VersioningType.HEADER, header: 'X-API-Version', }; // Example request: // GET /users // X-API-Version: 2 ``` ## AI Coding Instructions - Always set `type` to `VersioningType.HEADER`; this interface is specifically for header-based version resolution. - Provide a non-empty, stable header name such as `X-API-Version` or `API-Version`. - Ensure API clients send the configured header with every request to versioned endpoints. - Keep the configured header name consistent across application bootstrap configuration, gateways, and API documentation. - Do not use this interface when version information is supplied through a URI, media type, or custom extractor. # OnApplicationBootstrap **Kind:** Interface **Source:** [`packages/common/interfaces/hooks/on-application-bootstrap.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/hooks/on-application-bootstrap.interface.ts#L9) **Part of:** [Common](subsystem-packages-common) Interface defining method called once the application has fully started and is bootstrapped. `OnApplicationBootstrap` defines the `onApplicationBootstrap()` lifecycle hook, which Nest calls once the application has completed module initialization and bootstrapping. Implement this interface in providers that need to perform final startup work, such as warming caches, validating external dependencies, or initializing background processes. ## Diagram ```mermaid graph LR A[Nest application bootstrap] --> B[Initialize modules and providers] B --> C[Find providers implementing OnApplicationBootstrap] C --> D[Call onApplicationBootstrap()] D --> E[Run final startup tasks] E --> F[Application ready to serve requests] ``` ## Usage ```ts import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; @Injectable() export class CacheWarmupService implements OnApplicationBootstrap { async onApplicationBootstrap(): Promise { // Perform startup work after all modules are initialized. await this.warmCache(); } private async warmCache(): Promise { console.log('Warming application cache...'); } } ``` ## AI Coding Instructions - Implement `OnApplicationBootstrap` on injectable providers that require work after all application modules have initialized. - Keep `onApplicationBootstrap()` focused on startup orchestration; move substantial logic into dedicated private methods or services. - Return or await promises for asynchronous initialization so Nest can complete the lifecycle hook correctly. - Avoid placing request-specific logic in this hook, since it runs once during application startup. - Use this hook when initialization depends on providers from multiple modules being available. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `callModuleBootstrapHook` — `packages/core/hooks/on-app-bootstrap.hook.ts`:43 # Request **Kind:** Constant **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L99) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `Request` object from the underlying platform and populates the decorated parameter with the value of `Request`. Example: `logout(@Request() req)` `Request` is a route-handler parameter decorator that injects the underlying platform request object into a controller method parameter. Use it when a handler needs access to request metadata, headers, body data, cookies, or platform-specific request APIs. ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createRouteParamDecorator( RouteParamtypes.REQUEST, ) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] --> Router[Route Router] Router --> Handler[Controller Handler] RequestDecorator["@Request()"] --> Handler PlatformRequest[Underlying Request Object] --> RequestDecorator RequestDecorator --> Parameter[Decorated req Parameter] ``` ## Usage ```ts import { Controller, Get, Request } from '@nestjs/common'; @Controller('account') export class AccountController { @Get('logout') logout(@Request() req: any) { const authorization = req.headers.authorization; return { message: 'Logout request received', authorization, }; } } ``` ## AI Coding Instructions - Use `@Request()` only on route handler parameters where direct access to the platform request object is required. - Prefer dedicated decorators such as `@Body()`, `@Param()`, `@Query()`, or `@Headers()` when only a specific request value is needed. - Keep request-object usage platform-aware; its exact shape may differ between Express, Fastify, or other HTTP adapters. - Type the injected request parameter with the appropriate platform request type instead of using `any` when adapter-specific APIs are used. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AuthController` — `sample/19-auth-jwt/src/auth/auth.controller.ts`:13 # ValidatorPackage **Kind:** Interface **Source:** [`packages/common/interfaces/external/validator-package.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/validator-package.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) # GUARDS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L23) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__guards__' ``` ## Value ```ts '__guards__' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `GuardsContextCreator` — `packages/core/guards/guards-context-creator.ts`:12 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # HttpExceptionBody **Kind:** Interface **Source:** [`packages/common/interfaces/http/http-exception-body.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/http-exception-body.interface.ts#L3) **Part of:** [Common](subsystem-packages-common) `HttpExceptionBody` defines the standardized payload returned for HTTP exceptions. It combines a human-readable `message`, an error category string, and the numeric HTTP `statusCode` so clients can reliably inspect failed responses. ## Properties | Property | Type | |---|---| | `message` | `HttpExceptionBodyMessage` | | `error` | `string` | | `statusCode` | `number` | ## Diagram ```mermaid graph LR A[HTTP Exception] --> B[HttpExceptionBody] B --> C[message: HttpExceptionBodyMessage] B --> D[error: string] B --> E[statusCode: number] C --> F[Client-facing error details] D --> G[Error category] E --> H[HTTP status code] ``` ## Usage ```ts import type { HttpExceptionBody } from './http-exception-body.interface'; const responseBody: HttpExceptionBody = { message: ['Email must be valid', 'Password must contain 8 characters'], error: 'Bad Request', statusCode: 400, }; function handleError(body: HttpExceptionBody) { console.error(`${body.statusCode} ${body.error}`, body.message); } handleError(responseBody); ``` ## AI Coding Instructions - Preserve the `message`, `error`, and `statusCode` fields when constructing standardized HTTP error responses. - Treat `message` as `HttpExceptionBodyMessage`; it may represent a single message or multiple validation messages. - Use valid HTTP status codes for `statusCode` and keep `error` aligned with the corresponding error category. - Prefer this interface for serialized exception response bodies rather than exposing internal error objects or stack traces. # HttpExceptionOptions **Kind:** Interface **Source:** [`packages/common/exceptions/http.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts#L8) **Part of:** [Common](subsystem-packages-common) `HttpExceptionOptions` defines optional metadata that can be attached to an HTTP exception. It provides a human-readable `description` and an underlying `cause` value, helping applications preserve diagnostic context when errors are created and handled. ## Properties | Property | Type | |---|---| | `cause` | `unknown` | | `description` | `string` | ## Diagram ```mermaid graph LR A[Application error] --> B[HttpExceptionOptions] B --> C[cause: unknown] B --> D[description: string] B --> E[HttpException] E --> F[Exception handler / HTTP response] ``` ## Usage ```ts import { HttpException, HttpStatus } from '@nestjs/common'; function findUser(userId: string) { try { // Example operation that may fail throw new Error(`User ${userId} was not found`); } catch (error) { throw new HttpException( 'Unable to retrieve user', HttpStatus.NOT_FOUND, { description: 'The requested user does not exist or cannot be accessed.', cause: error, }, ); } } ``` ## AI Coding Instructions - Pass `HttpExceptionOptions` as the third argument when constructing an `HttpException`. - Use `description` for stable, developer-facing context; do not rely on it as the client response message. - Preserve the original thrown value in `cause` to support logging, tracing, and error debugging. - Treat `cause` as `unknown`; narrow its type before accessing properties such as `message` or `stack`. - Avoid placing sensitive data, credentials, or internal implementation details in exception descriptions. # IFile **Kind:** Interface **Source:** [`packages/common/pipes/file/interfaces/file.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/interfaces/file.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) `IFile` defines the normalized shape of a file handled by the common file pipe utilities. It stores the file MIME type, byte size, and in-memory `Buffer` content so validation and downstream processing can work with a consistent payload. ## Properties | Property | Type | |---|---| | `mimetype` | `string` | | `size` | `number` | | `buffer` | `Buffer` | ## Diagram ```mermaid graph LR Upload[Incoming file upload] --> IFile[IFile] IFile --> Mime[mimetype: string] IFile --> Size[size: number] IFile --> Content[buffer: Buffer] IFile --> Validation[File validation pipes] Validation --> Processing[Application file processing] ``` ## Usage ```ts import { IFile } from '@common/pipes/file/interfaces/file.interface'; function validateImage(file: IFile): void { if (!file.mimetype.startsWith('image/')) { throw new Error('Only image files are allowed.'); } if (file.size > 5 * 1024 * 1024) { throw new Error('File must not exceed 5 MB.'); } } const file: IFile = { mimetype: 'image/png', size: 1024, buffer: Buffer.from('image-content'), }; validateImage(file); ``` ## AI Coding Instructions - Treat `buffer` as the authoritative in-memory file content; do not assume a filesystem path or stream is available. - Validate `mimetype` and `size` before processing or persisting file data. - Keep `size` aligned with the byte length of `buffer` when constructing `IFile` objects manually. - Use this interface at file-pipe boundaries to normalize upload-provider-specific file objects. # INTERCEPTORS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L24) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__interceptors__' ``` ## Value ```ts '__interceptors__' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `InterceptorsContextCreator` — `packages/core/interceptors/interceptors-context-creator.ts`:11 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # PIPES_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L22) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__pipes__' ``` ## Value ```ts '__pipes__' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `PipesContextCreator` — `packages/core/pipes/pipes-context-creator.ts`:11 - `DependenciesScanner` — `packages/core/scanner.ts`:75 # SCOPE_OPTIONS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L16) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'scope:options' ``` ## Value ```ts 'scope:options' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `getClassScope` — `packages/core/helpers/get-class-scope.ts`:5 - `isDurable` — `packages/core/helpers/is-durable.ts`:4 # CustomOrigin **Kind:** Type **Source:** [`packages/common/interfaces/external/cors-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/cors-options.interface.ts#L12) **Part of:** [Common](subsystem-packages-common) Set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature err [object], allow [bool]) as the second. `CustomOrigin` defines a callback-based function used to determine whether a request origin is allowed for CORS. It receives the incoming origin and must invoke a callback with either an error or a boolean indicating whether the origin should be permitted. ## Definition ```ts ( requestOrigin: string | undefined, callback: (err: Error | null, origin?: StaticOrigin) => void, ) => void ``` ## Diagram ```mermaid graph LR A[Incoming request] --> B[Request Origin] B --> C[CustomOrigin function] C --> D{Custom validation logic} D -->|Allowed| E[callback(null, true)] D -->|Denied| F[callback(null, false)] D -->|Error| G[callback(error)] ``` ## Usage ```ts import type { CustomOrigin } from './cors-options.interface'; const allowedOrigins = new Set([ 'https://app.example.com', 'https://admin.example.com', ]); const validateOrigin: CustomOrigin = (origin, callback) => { // Requests without an Origin header, such as server-to-server calls. if (!origin) { return callback(null, true); } if (allowedOrigins.has(origin)) { return callback(null, true); } return callback(null, false); }; // Example CORS configuration const corsOptions = { origin: validateOrigin, }; ``` ## AI Coding Instructions - Implement `CustomOrigin` as a callback-based function; always call the callback with `(error, allowed)`. - Return `true` only after validating the supplied origin against trusted configuration or application rules. - Handle missing origins intentionally, since non-browser or same-origin requests may not include an `Origin` header. - Use `callback(null, false)` for denied origins and reserve errors for validation or configuration failures. - Keep origin validation centralized so CORS policy remains consistent across application entry points. # CustomParamFactory **Kind:** Type **Source:** [`packages/common/interfaces/features/custom-route-param-factory.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/custom-route-param-factory.interface.ts#L6) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts ( data: TData, context: ExecutionContext, ) => TOutput ``` # DescriptionAndOptions **Kind:** Interface **Source:** [`packages/common/exceptions/http.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts#L14) **Part of:** [Common](subsystem-packages-common) `DescriptionAndOptions` groups a human-readable exception description with the `HttpExceptionOptions` used to configure how an HTTP exception is created or handled. It is typically used internally when normalizing exception constructor arguments into a consistent structure. ## Properties | Property | Type | |---|---| | `description` | `string` | | `httpExceptionOptions` | `HttpExceptionOptions` | ## Diagram ```mermaid graph LR A[Exception input] --> B[DescriptionAndOptions] B --> C[description: string] B --> D[httpExceptionOptions: HttpExceptionOptions] D --> E[HTTP exception configuration] ``` ## Usage ```ts import type { HttpExceptionOptions } from './http.exception'; interface DescriptionAndOptions { description: string; httpExceptionOptions: HttpExceptionOptions; } const exceptionDetails: DescriptionAndOptions = { description: 'The requested user could not be found.', httpExceptionOptions: { cause: new Error('User lookup returned no result'), }, }; // Use the normalized values when constructing an HTTP exception. const { description, httpExceptionOptions } = exceptionDetails; ``` ## AI Coding Instructions - Keep `description` as a clear, client-safe string explaining the exception condition. - Pass exception metadata through `httpExceptionOptions` rather than adding unrelated fields to this interface. - Preserve the `cause` option when wrapping lower-level errors so error chains remain traceable. - Use this shape when normalizing overloaded HTTP exception constructor inputs into a single internal representation. # FileValidatorContext **Kind:** Type **Source:** [`packages/common/pipes/file/file-validator-context.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/file-validator-context.interface.ts#L3) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts { file?: IFile; config: TConfig; } ``` # generateOptionsInjectionToken **Kind:** Function **Source:** [`packages/common/module-utils/utils/generate-options-injection-token.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/utils/generate-options-injection-token.util.ts#L3) **Part of:** [Common](subsystem-packages-common) # HttpRedirectResponse **Kind:** Interface **Source:** [`packages/common/interfaces/http/http-redirect-response.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/http-redirect-response.interface.ts#L3) **Part of:** [Common](subsystem-packages-common) `HttpRedirectResponse` defines the data required to represent an HTTP redirect response. It pairs a destination `url` with an HTTP redirect `statusCode`, allowing HTTP adapters or controllers to consistently construct redirect behavior. ## Properties | Property | Type | |---|---| | `url` | `string` | | `statusCode` | `HttpStatus` | ## Diagram ```mermaid graph LR A[Controller or Route Handler] --> B[HttpRedirectResponse] B --> C[url: string] B --> D[statusCode: HttpStatus] B --> E[HTTP Adapter] E --> F[Redirect Response] ``` ## Usage ```ts import { HttpStatus } from '@nestjs/common'; import { HttpRedirectResponse } from './http-redirect-response.interface'; function createLoginRedirect(): HttpRedirectResponse { return { url: '/login', statusCode: HttpStatus.FOUND, }; } const redirect = createLoginRedirect(); // HTTP adapter uses: // Location: /login // Status: 302 Found ``` ## AI Coding Instructions - Always provide a valid redirect target in `url`, such as a relative application path or a fully qualified URL. - Use an appropriate redirect status from `HttpStatus`, such as `FOUND`, `MOVED_PERMANENTLY`, or `TEMPORARY_REDIRECT`. - Keep this interface limited to redirect metadata; response headers and body handling belong to the HTTP adapter layer. - Ensure controller and adapter implementations consistently map `url` to the `Location` response header. # RequestMappingMetadata **Kind:** Interface **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L4) **Part of:** [Common](subsystem-packages-common) `RequestMappingMetadata` describes the routing information attached to an HTTP request handler. It combines one or more URL paths with a `RequestMethod`, allowing request-mapping decorators and routing infrastructure to register controller endpoints consistently. ## Properties | Property | Type | |---|---| | `path` | `string | string[]` | | `method` | `RequestMethod` | ## Diagram ```mermaid graph LR A[RequestMappingMetadata] --> B[path: string | string[]] A --> C[method: RequestMethod] B --> D[Single route path] B --> E[Multiple route paths] C --> F[HTTP verb] F --> G[Router registration] ``` ## Usage ```ts import { RequestMethod } from '@nestjs/common'; import type { RequestMappingMetadata } from './request-mapping.decorator'; const mapping: RequestMappingMetadata = { path: ['/users', '/accounts'], method: RequestMethod.GET, }; // Example decorator metadata consumed by the HTTP router. function registerRoute(metadata: RequestMappingMetadata) { for (const path of Array.isArray(metadata.path) ? metadata.path : [metadata.path]) { console.log(`Registering ${RequestMethod[metadata.method]} ${path}`); } } registerRoute(mapping); ``` ## AI Coding Instructions - Use `path` as a string for a single route or a string array when the same handler supports multiple routes. - Always provide a valid `RequestMethod` enum value; do not use raw HTTP method strings unless converted first. - Normalize `path` to an array before iterating over route mappings in router integration code. - Keep this metadata focused on route path and HTTP method; add unrelated handler metadata through separate interfaces or decorators. ## How it works - **`RequestMappingMetadata`** is an exported TypeScript interface used as the `metadata` argument type for the `RequestMapping` method-decorator factory. It declares two optional fields: `path`, a string or string array, and `method`, a `RequestMethod` enum member. [packages/common/decorators/http/request-mapping.decorator.ts:4-7](packages/common/decorators/http/request-mapping.decorator.ts#L4-L7) [packages/common/decorators/http/request-mapping.decorator.ts:14-16](packages/common/decorators/http/request-mapping.decorator.ts#L14-L16) - `path` corresponds to the `PATH_METADATA` key, whose string value is `'path'`; `method` corresponds to `METHOD_METADATA`, whose string value is `'method'`. [packages/common/constants.ts:10](packages/common/constants.ts#L10) [packages/common/constants.ts:17](packages/common/constants.ts#L17) - Its `method` type is the `RequestMethod` enum. The enum contains `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `ALL`, `OPTIONS`, `HEAD`, `SEARCH`, and WebDAV-related members through `UNLOCK`. [packages/common/enums/request-method.enum.ts:1-18](packages/common/enums/request-method.enum.ts#L1-L18) - When passed to `RequestMapping`, a non-empty `path` value is retained; an omitted path, empty string, or empty array becomes `'/'`. An omitted or falsy `method` becomes `RequestMethod.GET`. [packages/common/decorators/http/request-mapping.decorator.ts:9-19](packages/common/decorators/http/request-mapping.decorator.ts#L9-L19) The decorator writes the resulting path and request method as reflection metadata on the decorated method’s function (`descriptor.value`). [packages/common/decorators/http/request-mapping.decorator.ts:21-29](packages/common/decorators/http/request-mapping.decorator.ts#L21-L29) - The interface contains no runtime validation or error handling itself. Its observable runtime effect occurs only through `RequestMapping`, which calls `Reflect.defineMetadata` for both keys. [packages/common/decorators/http/request-mapping.decorator.ts:4-7](packages/common/decorators/http/request-mapping.decorator.ts#L4-L7) [packages/common/decorators/http/request-mapping.decorator.ts:26-27](packages/common/decorators/http/request-mapping.decorator.ts#L26-L27) - During controller route discovery, the stored path and method metadata are read from the prototype method. A string path is converted to a one-element path array after adding a leading slash; an array is mapped the same way per element. If no path metadata exists, that method is not treated as a route. [packages/core/router/paths-explorer.ts:53-82](packages/core/router/paths-explorer.ts#L53-L82) # ClassSerializerContextOptions **Kind:** Interface **Source:** [`packages/common/serializer/class-serializer.interfaces.ts`](https://github.com/nestjs/nest/blob/master/packages/common/serializer/class-serializer.interfaces.ts#L7) **Part of:** [Common](subsystem-packages-common) `ClassSerializerContextOptions` provides serializer context metadata for class-based transformation operations. Its `type` field identifies the target constructor, allowing the serializer to resolve class-specific serialization behavior and metadata. ## Properties | Property | Type | |---|---| | `type` | `Type` | ## Diagram ```mermaid graph LR A[Serialization Request] --> B[ClassSerializerContextOptions] B --> C[type: Type] C --> D[Target Class Constructor] D --> E[Class Serialization Metadata] E --> F[Serialized Output] ``` ## Usage ```ts import { ClassSerializerContextOptions, Type } from '@nestjs/common'; class UserDto { id: number; email: string; } const serializerOptions: ClassSerializerContextOptions = { type: UserDto as Type, }; // Pass the options to serializer-related infrastructure function serializeWithContext(options: ClassSerializerContextOptions) { return options.type; } const targetType = serializeWithContext(serializerOptions); ``` ## AI Coding Instructions - Set `type` to the constructor of the class whose serialization metadata should be used. - Use Nest's `Type` type when declaring or passing class constructors. - Do not pass an instance (for example, `new UserDto()`); provide the class reference (`UserDto`) instead. - Integrate this interface where serializer logic needs explicit target-type information, especially when runtime type inference is unavailable. # ControllerMetadata **Kind:** Interface **Source:** [`packages/common/interfaces/controllers/controller-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/controllers/controller-metadata.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) `ControllerMetadata` defines the metadata associated with a controller, currently consisting of its route `path`. Framework decorators or registration logic can use this interface to store and retrieve the base URL segment for controller instances. ## Properties | Property | Type | |---|---| | `path` | `string` | ## Diagram ```mermaid graph LR Controller["Controller Class"] --> Metadata["ControllerMetadata"] Metadata --> Path["path: string"] Path --> Router["Route Registration"] ``` ## Usage ```ts import type { ControllerMetadata } from './controller-metadata.interface'; const metadata: ControllerMetadata = { path: '/users', }; function registerController(controller: ControllerMetadata) { console.log(`Registering controller at ${controller.path}`); } registerController(metadata); ``` ## AI Coding Instructions - Keep `path` as a string representing the controller's base route path. - Use this interface when passing or storing controller-level routing metadata. - Normalize route paths consistently in the router or decorator layer (for example, handling leading slashes). - Avoid adding request-specific or method-specific metadata here; keep those concerns in separate interfaces. # CorsOptionsCallback **Kind:** Interface **Source:** [`packages/common/interfaces/external/cors-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/cors-options.interface.ts#L58) **Part of:** [Common](subsystem-packages-common) # Next **Kind:** Constant **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L138) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts reference to the `Next` function from the underlying platform and populates the decorated parameter with the value of `Next`. `Next` is a route handler parameter decorator that injects the underlying platform’s `next` callback into a controller method parameter. It is primarily used in Express-based applications to delegate control to the next middleware or error handler in the request pipeline. ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createRouteParamDecorator( RouteParamtypes.NEXT, ) ``` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Middleware Pipeline] B --> C[Controller Route Handler] C --> D[@Next() Decorated Parameter] D --> E[next Function] E --> F[Next Middleware or Error Handler] ``` ## Usage ```ts import { Controller, Get, Next } from '@nestjs/common'; import type { NextFunction } from 'express'; @Controller('users') export class UsersController { @Get() findAll(@Next() next: NextFunction) { try { // Handle the request or delegate to later middleware. next(); } catch (error) { next(error); } } } ``` ## AI Coding Instructions - Use `@Next()` only on route-handler parameters where direct access to the platform middleware flow is required. - Type the injected value as `NextFunction` when using the Express platform. - Call `next(error)` to delegate unexpected errors to registered error-handling middleware. - Prefer NestJS guards, interceptors, pipes, and exception filters for framework-native request handling when possible. - Ensure the selected HTTP adapter supports a `next` callback before relying on this decorator. # PlainLiteralObject **Kind:** Interface **Source:** [`packages/common/serializer/class-serializer.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/common/serializer/class-serializer.interceptor.ts#L15) **Part of:** [Common](subsystem-packages-common) # Session **Kind:** Constant **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L164) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `Session` object from the underlying platform and populates the decorated parameter with the value of `Session`. `Session` is a route handler parameter decorator that injects the session object provided by the underlying HTTP platform. Use it in controller methods to access session data without manually reading it from the request object. ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createRouteParamDecorator( RouteParamtypes.SESSION, ) ``` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Underlying Platform Session] B --> C[@Session() Decorator] C --> D[Controller Method Parameter] D --> E[Route Handler Logic] ``` ## Usage ```ts import { Controller, Get, Session } from '@nestjs/common'; @Controller('account') export class AccountController { @Get('profile') getProfile(@Session() session: Record) { return { userId: session.userId, authenticated: Boolean(session.userId), }; } } ``` ## AI Coding Instructions - Apply `@Session()` only to route handler parameters where session data is required. - Treat the injected session value as platform-provided request state; ensure session middleware or adapters are configured first. - Define a typed session interface when your application stores known fields such as `userId`, roles, or preferences. - Avoid reading session data directly from the request when `@Session()` provides the required value. - Do not expose sensitive session fields directly in API responses. # yellow **Kind:** Constant **Source:** [`packages/common/utils/cli-colors.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/cli-colors.util.ts#L15) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts colorIfAllowed( (text: string) => `\x1B[38;5;3m${text}\x1B[39m`, ) ``` ## Value ```ts colorIfAllowed( (text: string) => `\x1B[38;5;3m${text}\x1B[39m`, ) ``` # CATCH_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L46) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__catch__' ``` ## Value ```ts '__catch__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DependenciesScanner` — `packages/core/scanner.ts`:75 # CONTROLLER_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L45) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__controller__' ``` ## Value ```ts '__controller__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DependenciesScanner` — `packages/core/scanner.ts`:75 # ENTRY_PROVIDER_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L47) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__entryProvider__' ``` ## Value ```ts '__entryProvider__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Module` — `packages/core/injector/module.ts`:44 # FILTER_CATCH_EXCEPTIONS **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L20) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__filterCatchExceptions__' ``` ## Value ```ts '__filterCatchExceptions__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `BaseExceptionFilterContext` — `packages/core/exceptions/base-exception-filter-context.ts`:11 # GLOBAL_MODULE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L8) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__module:global__' ``` ## Value ```ts '__module:global__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestContainer` — `packages/core/injector/container.ts`:31 # Headers **Kind:** Constant **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L325) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `headers` property from the `req` object and populates the decorated parameter with the value of `headers`. For example: `async update(@Headers('Cache-Control') cacheControl: string)` `Headers` is a route-handler parameter decorator that extracts the `headers` object from the incoming request. It can return all request headers or a specific header value when a header name is provided, allowing handlers to access HTTP metadata without manually reading from `req`. ## Definition ```ts (property?: string) => ParameterDecorator ``` ## Value ```ts createRouteParamDecorator(RouteParamtypes.HEADERS) ``` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.headers] B --> C[@Headers decorator] C --> D[Decorated route handler parameter] D --> E[Handler logic] ``` ## Usage ```ts import { Controller, Get, Headers } from '@nestjs/common'; @Controller('documents') export class DocumentsController { @Get() findAll(@Headers('cache-control') cacheControl: string) { return { cacheControl, }; } @Get('request-headers') getHeaders(@Headers() headers: Record) { return headers; } } ``` ## AI Coding Instructions - Use `@Headers()` when the handler needs the complete request headers object. - Pass a header name, such as `@Headers('authorization')`, to inject only one header value. - Prefer lowercase header names because Node.js normalizes incoming request header keys to lowercase. - Treat extracted header values as potentially missing or as `string | string[] | undefined` when applicable. - Keep request-specific parsing and validation in the route handler or a dedicated pipe/guard rather than modifying the decorator. # HEADERS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L39) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__headers__' ``` ## Value ```ts '__headers__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 # HOST_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L9) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'host' ``` ## Value ```ts 'host' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RoutesResolver` — `packages/core/router/routes-resolver.ts`:35 # HTTP_CODE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L37) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__httpCode__' ``` ## Value ```ts '__httpCode__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 # INJECTABLE_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L44) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__injectable__' ``` ## Value ```ts '__injectable__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DependenciesScanner` — `packages/core/scanner.ts`:75 # LogLevel **Kind:** Type **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L18) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts (typeof LOG_LEVELS)[number] ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 # METHOD_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L17) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'method' ``` ## Value ```ts 'method' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RouteDefinition` — `packages/core/router/paths-explorer.ts`:17 # OPTIONAL_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L13) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'optional:paramtypes' ``` ## Value ```ts 'optional:paramtypes' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `InjectorDependency` — `packages/core/injector/injector.ts`:51 # OPTIONAL_PROPERTY_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L15) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'optional:properties_metadata' ``` ## Value ```ts 'optional:properties_metadata' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `InjectorDependency` — `packages/core/injector/injector.ts`:51 # Paramtype **Kind:** Type **Source:** [`packages/common/interfaces/features/paramtype.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/paramtype.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'body' | 'query' | 'param' | 'custom' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamsTokenFactory` — `packages/core/pipes/params-token-factory.ts`:4 # PROPERTY_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L14) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'self:properties_metadata' ``` ## Value ```ts 'self:properties_metadata' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `InjectorDependency` — `packages/core/injector/injector.ts`:51 # REDIRECT_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L40) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__redirect__' ``` ## Value ```ts '__redirect__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 # RENDER_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L36) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__renderTemplate__' ``` ## Value ```ts '__renderTemplate__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 # Res **Kind:** Constant **Source:** [`packages/common/decorators/http/route-params.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/route-params.decorator.ts#L798) **Part of:** [Common](subsystem-packages-common) Route handler parameter decorator. Extracts the `Response` object from the underlying platform and populates the decorated parameter with the value of `Response`. Alias for `Res` is a route handler parameter decorator that injects the underlying platform `Response` object into a controller method parameter. It is used when a handler needs direct access to the native HTTP response for tasks such as setting headers, cookies, status codes, or sending a custom response body. Using `Res` typically hands response handling to the application code rather than Nest's automatic response serialization. ## Definition ```ts Response ``` ## Value ```ts Response ``` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[Controller Route Handler] B --> C[@Res() Decorated Parameter] C --> D[Platform Response Object] D --> E[Set headers, cookies, status, or send response] ``` ## Usage ```ts import { Controller, Get, Res } from '@nestjs/common'; import type { Response } from 'express'; @Controller('health') export class HealthController { @Get() check(@Res() response: Response) { response .status(200) .setHeader('X-Service-Status', 'healthy') .json({ status: 'ok' }); } } ``` ## AI Coding Instructions - Use `@Res()` only when direct access to the platform response object is required, such as for streaming, redirects, or custom headers. - When using `@Res()`, explicitly send or end the response with methods such as `json()`, `send()`, `redirect()`, or `end()`. - Avoid mixing manual response handling with returned handler values, since automatic Nest response serialization may be bypassed. - Keep response types aligned with the configured HTTP adapter, for example `Response` from Express when using the Express platform. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AppController` — `sample/28-sse/src/app.controller.ts`:8 # RESPONSE_PASSTHROUGH_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L41) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__responsePassthrough__' ``` ## Value ```ts '__responsePassthrough__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/helpers/context-utils.ts`:15 # SelectOptions **Kind:** Type **Source:** [`packages/common/interfaces/nest-application-context.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/nest-application-context.interface.ts#L8) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts Pick ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestApplicationContext` — `packages/core/nest-application-context.ts`:40 # SELF_DECLARED_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L12) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'self:paramtypes' ``` ## Value ```ts 'self:paramtypes' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `InjectorDependency` — `packages/core/injector/injector.ts`:51 # SSE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L42) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts '__sse__' ``` ## Value ```ts '__sse__' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ParamProperties` — `packages/core/router/router-execution-context.ts`:50 # All **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L111) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes all HTTP requests to the specified path. `All` is a route handler decorator that maps every HTTP method to a controller method for a specified path. It is useful for catch-all endpoints, method-agnostic handlers, and scenarios where the handler determines how to process the incoming request. ## Definition ```ts createMappingDecorator(RequestMethod.ALL) ``` ## Value ```ts createMappingDecorator(RequestMethod.ALL) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] --> Request[Incoming HTTP Request] Request --> Router[Router] Router --> All["@All('/path')"] All --> Handler[Controller Method] Handler --> Response[HTTP Response] ``` ## Usage ```ts import { All, Controller, Req, Res } from '@nestjs/common'; import type { Request, Response } from 'express'; @Controller('webhooks') export class WebhookController { @All('events') handleEvent(@Req() request: Request, @Res() response: Response) { console.log(`Received ${request.method} request`); response.status(200).json({ received: true, method: request.method, }); } } ``` ## AI Coding Instructions - Use `@All()` when the same handler must accept multiple HTTP methods for a route. - Prefer specific decorators such as `@Get()`, `@Post()`, or `@Patch()` when the endpoint supports only one method. - Ensure the handler safely validates `request.method`, request headers, and payloads when handling multiple methods. - Avoid overlapping `@All()` routes with more specific routes unless routing precedence is intentional. - Use a controller-level path with `@Controller()` to keep `@All()` route paths concise and organized. # ASYNC_METHOD_SUFFIX **Kind:** Constant **Source:** [`packages/common/module-utils/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/constants.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'Async' ``` ## Value ```ts 'Async' ``` # CLASS_SERIALIZER_OPTIONS **Kind:** Constant **Source:** [`packages/common/serializer/class-serializer.constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/serializer/class-serializer.constants.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'class_serializer:options' ``` ## Value ```ts 'class_serializer:options' ``` # CONFIGURABLE_MODULE_ID **Kind:** Constant **Source:** [`packages/common/module-utils/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/constants.ts#L5) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'CONFIGURABLE_MODULE_ID' ``` ## Value ```ts 'CONFIGURABLE_MODULE_ID' ``` # Constructor **Kind:** Type **Source:** [`packages/common/utils/merge-with-values.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/merge-with-values.util.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts new (...args: any[]) => T ``` # Controller **Kind:** Type **Source:** [`packages/common/interfaces/controllers/controller.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/controllers/controller.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts object ``` # Copy **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L156) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav COPY requests to the specified path. `Copy` is a route-handler method decorator for WebDAV `COPY` requests. Apply it to a controller method to map a WebDAV copy operation to a specific route path, allowing the handler to process source, destination, overwrite, and related request details. ## Definition ```ts createMappingDecorator(RequestMethod.COPY) ``` ## Value ```ts createMappingDecorator(RequestMethod.COPY) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|COPY request| Router[HTTP Router] Router -->|matching path| CopyDecorator[@Copy decorator] CopyDecorator --> Handler[Controller Method] Handler --> Response[WebDAV Response] ``` ## Usage ```ts import { Controller, Copy } from '@your-package/common'; @Controller('/files') export class FilesController { @Copy('/:sourcePath') async copyFile(request: Request): Promise { const sourcePath = request.params.sourcePath; const destination = request.headers.get('Destination'); // Copy the source resource to the requested destination. await copyResource(sourcePath, destination); return new Response(null, { status: 201 }); } } ``` ## AI Coding Instructions - Use `@Copy()` only on controller methods intended to handle WebDAV `COPY` requests. - Provide a route path that identifies the source resource being copied, such as `/:path` or `/*`. - Read the destination target from the WebDAV `Destination` request header rather than assuming it is part of the route path. - Preserve WebDAV semantics such as overwrite behavior, depth handling, and appropriate status codes (`201`, `204`, `409`, or `412`). - Keep copy logic in a dedicated service where possible; controllers should primarily map the request and return the protocol response. # DEFAULT_FACTORY_CLASS_METHOD_KEY **Kind:** Constant **Source:** [`packages/common/module-utils/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/constants.ts#L2) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'create' ``` ## Value ```ts 'create' ``` # DEFAULT_METHOD_KEY **Kind:** Constant **Source:** [`packages/common/module-utils/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/module-utils/constants.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts 'register' ``` ## Value ```ts 'register' ``` # Head **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L102) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP HEAD requests to the specified path. `Head` is a route handler decorator that maps an HTTP `HEAD` request to a controller method. It behaves like a `GET` route for path matching, but the response should contain headers without a response body. Use it for endpoints that expose resource metadata, availability, caching information, or content length. ## Definition ```ts createMappingDecorator(RequestMethod.HEAD) ``` ## Value ```ts createMappingDecorator(RequestMethod.HEAD) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|HEAD /resource| Router[HTTP Router] Router -->|Matches path and HEAD method| HeadDecorator[@Head decorator] HeadDecorator --> Controller[Controller Method] Controller --> Headers[Response Headers] Headers --> Client ``` ## Usage ```ts import { Controller, Head, HttpCode } from '@nestjs/common'; @Controller('files') export class FilesController { @Head(':id') @HttpCode(200) checkFileAvailability(): void { // Set response metadata such as ETag, Content-Length, // or Last-Modified through the response object when needed. // HEAD responses should not include a response body. } } ``` ## AI Coding Instructions - Use `@Head()` on controller methods that must handle HTTP `HEAD` requests; provide a path argument when mapping a specific route. - Keep `HEAD` handlers bodyless, since clients expect headers and status information rather than response content. - Pair `HEAD` routes with equivalent `GET` routes when clients need both metadata-only and full-resource access. - Configure cache-related headers, `Content-Length`, `ETag`, or `Last-Modified` through the framework response APIs when implementing resource checks. - Ensure the route path does not conflict with other method decorators unintentionally; `HEAD` and `GET` may share a path but serve different HTTP methods. # HttpExceptionBodyMessage **Kind:** Type **Source:** [`packages/common/interfaces/http/http-exception-body.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/http/http-exception-body.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts string | string[] | number ``` # Injectable **Kind:** Type **Source:** [`packages/common/interfaces/injectable.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/injectable.interface.ts#L1) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts unknown ``` # InjectableOptions **Kind:** Type **Source:** [`packages/common/decorators/core/injectable.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/injectable.decorator.ts#L13) **Part of:** [Common](subsystem-packages-common) Defines the injection scope. `InjectableOptions` configures how a provider is registered when using NestJS's `@Injectable()` decorator. Its primary responsibility is defining the provider's injection scope, which controls whether Nest creates a shared singleton, a per-request instance, or a transient instance. ## Definition ```ts ScopeOptions ``` ## Diagram ```mermaid graph LR A["@Injectable(options)"] --> B["InjectableOptions"] B --> C["scope?: Scope"] C --> D["DEFAULT
Shared singleton"] C --> E["REQUEST
One instance per request"] C --> F["TRANSIENT
New instance per injection"] A --> G["Nest DI Container"] ``` ## Usage ```ts import { Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.REQUEST, }) export class RequestContextService { private readonly createdAt = new Date(); getCreatedAt(): Date { return this.createdAt; } } ``` ## AI Coding Instructions - Use `InjectableOptions` as the options object passed to `@Injectable()`. - Prefer the default scope for stateless services and shared infrastructure such as repositories or API clients. - Use `Scope.REQUEST` only when a provider needs request-specific state, such as tenant or correlation context. - Use `Scope.TRANSIENT` for providers that must be recreated for every injection site. - Be aware that request-scoped or transient dependencies can cause otherwise singleton consumers to become scoped as well. # isColorAllowed **Kind:** Function **Source:** [`packages/common/utils/cli-colors.util.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/cli-colors.util.ts#L3) **Part of:** [Common](subsystem-packages-common) # Lock **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L174) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav LOCK requests to the specified path. `Lock` is a route-handler decorator for WebDAV `LOCK` requests. Apply it to a controller method to map a WebDAV lock operation to a specified route path, allowing the handler to create, refresh, or manage resource locks within the request-routing layer. ## Definition ```ts createMappingDecorator(RequestMethod.LOCK) ``` ## Value ```ts createMappingDecorator(RequestMethod.LOCK) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|LOCK request| Router[HTTP Router] Router -->|matches @Lock path| Handler[Controller Method] Handler --> LockService[Lock Handling Logic] LockService --> Response[WebDAV LOCK Response] ``` ## Usage ```ts import { Controller, Req } from '@nestjs/common'; import { Lock } from '@your-package/common/decorators/http/request-mapping.decorator'; @Controller('files') export class FilesController { @Lock(':path*') async lockFile(@Req() request: Request) { const path = request.params.path; // Create or refresh the WebDAV lock for the requested resource. return { path, status: 'locked', }; } } ``` ## AI Coding Instructions - Use `@Lock()` only on controller methods intended to handle WebDAV `LOCK` requests. - Define a route path that matches the resource hierarchy your WebDAV client may lock, such as `:path*` for nested resources. - Ensure the handler returns a response compatible with your WebDAV lock implementation, including lock token and timeout details when required. - Keep lock persistence, validation, and conflict detection in dedicated services rather than inside the decorator or routing layer. - Pair `Lock` handling with related WebDAV methods such as `UNLOCK`, `PROPFIND`, and `PUT` to enforce lock state consistently. # Mkcol **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L147) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav MKCOL requests to the specified path. `Mkcol` is a route handler decorator that maps an HTTP WebDAV `MKCOL` request to a controller method. Use it to define endpoints responsible for creating WebDAV collections (directory-like resources) at a specified path. ## Definition ```ts createMappingDecorator(RequestMethod.MKCOL) ``` ## Value ```ts createMappingDecorator(RequestMethod.MKCOL) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|MKCOL /collections/new| Router[HTTP Router] Router -->|Matches decorated path| Controller[Controller Method] Controller -->|@Mkcol()| Handler[Collection Creation Handler] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Mkcol } from '@common/decorators/http/request-mapping.decorator'; @Controller('webdav') export class WebdavController { @Mkcol('collections/:name') createCollection() { return { status: 'Collection created', }; } } ``` ## AI Coding Instructions - Apply `@Mkcol()` only to controller methods that handle WebDAV collection creation requests. - Provide a path relative to the controller prefix, following the same route conventions as other request-mapping decorators. - Ensure the handler implements appropriate WebDAV semantics, including validation for existing collections and parent resources. - Do not use standard `@Post()` as a substitute when WebDAV clients specifically issue `MKCOL` requests. - Keep authentication, authorization, and error handling consistent with the application's other WebDAV route handlers. # Move **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L165) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav MOVE requests to the specified path. `Move` is a route handler decorator for WebDAV `MOVE` requests. Apply it to a controller method to map a destination path to logic that relocates a WebDAV resource, such as a file or collection. ## Definition ```ts createMappingDecorator(RequestMethod.MOVE) ``` ## Value ```ts createMappingDecorator(RequestMethod.MOVE) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|MOVE request| Router[HTTP Router] Router -->|matched path| MoveDecorator["@Move(path)"] MoveDecorator --> Handler[Controller Method] Handler --> Resource[Move Resource] ``` ## Usage ```ts import { Move } from '@your-package/common'; class FilesController { @Move('/files/:path') async moveFile() { // Read WebDAV MOVE headers, such as Destination and Overwrite, // then move the requested resource. return { status: 201 }; } } ``` ## AI Coding Instructions - Use `@Move()` only on controller methods intended to handle WebDAV `MOVE` operations. - Define a path that matches the resource being moved; include route parameters when resource identifiers are needed. - Read and validate WebDAV-specific headers such as `Destination`, `Overwrite`, and authorization data in the handler or middleware. - Return appropriate WebDAV/HTTP status codes, including conflict or precondition failures when a move cannot be completed. - Keep move logic in a service layer where possible; the decorated handler should focus on request mapping and response handling. # Options **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L93) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP OPTIONS requests to the specified path. `Options` is a route handler decorator that maps HTTP `OPTIONS` requests to a controller method and optional path. It is typically used to expose supported operations, configure CORS preflight handling, or provide endpoint capability metadata within the application's HTTP routing layer. ## Definition ```ts createMappingDecorator(RequestMethod.OPTIONS) ``` ## Value ```ts createMappingDecorator(RequestMethod.OPTIONS) ``` ## Diagram ```mermaid graph LR Client[HTTP Client / Browser] -->|OPTIONS /resource| Router[HTTP Router] Router -->|Matches path and method| OptionsDecorator[@Options() Decorator] OptionsDecorator --> Handler[Controller Method] Handler --> Response[OPTIONS Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Options } from '@nestjs/common'; @Controller('documents') export class DocumentsController { @Options(':id') getDocumentOptions() { return { allow: ['GET', 'PUT', 'DELETE', 'OPTIONS'], }; } } ``` ## AI Coding Instructions - Apply `@Options()` only to controller methods intended to handle HTTP `OPTIONS` requests. - Pass a path argument such as `':id'` when the handler targets a route relative to the controller prefix. - Keep `OPTIONS` handlers focused on capability discovery or CORS/preflight-related responses rather than resource mutations. - Ensure the route does not conflict with another handler registered for the same `OPTIONS` method and path. - When using CORS middleware, verify whether preflight requests are handled globally before adding explicit `@Options()` routes. # ParamDecoratorEnhancer **Kind:** Type **Source:** [`packages/common/decorators/http/create-route-param-metadata.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/create-route-param-metadata.decorator.ts#L9) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts ParameterDecorator ``` # ParseArrayOptions **Kind:** Type **Source:** [`packages/common/pipes/parse-array.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-array.pipe.ts#L47) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts ParseArrayPipeOptions ``` # Propfind **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L129) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav PROPFIND requests to the specified path. `Propfind` is a route-handler decorator that maps WebDAV `PROPFIND` requests to a controller method and optional path. It integrates with the HTTP request-mapping decorator system so WebDAV resource metadata and directory listing requests can be handled alongside standard HTTP routes. ## Definition ```ts createMappingDecorator(RequestMethod.PROPFIND) ``` ## Value ```ts createMappingDecorator(RequestMethod.PROPFIND) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|PROPFIND /resources/path| Router[HTTP Router] Router -->|Matches @Propfind path| Controller[Controller Method] Controller --> Handler[WebDAV PROPFIND Handler] Handler --> Response[Resource Properties Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Propfind } from '@your-package/common'; @Controller('files') export class FilesController { @Propfind(':path') async getProperties() { return { displayname: 'example.txt', resourcetype: 'file', getcontentlength: 1024, }; } } ``` ## AI Coding Instructions - Use `@Propfind()` only for WebDAV `PROPFIND` handlers; use the corresponding request-mapping decorators for other HTTP or WebDAV methods. - Define a path argument when the handler must receive requests for a specific resource or nested resource path. - Ensure the handler returns data in the property format expected by the application's WebDAV response layer. - Keep `PROPFIND` handlers read-only; do not mutate files, metadata, or resource state during property lookup. - Place the decorator on controller methods within a controller that provides the appropriate route prefix. # Proppatch **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L138) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav PROPPATCH requests to the specified path. `Proppatch` is a route handler method decorator that maps WebDAV `PROPPATCH` requests to a specified path. Use it on controller methods that update or modify WebDAV resource properties, following the same routing pattern as other HTTP method decorators. ## Definition ```ts createMappingDecorator(RequestMethod.PROPPATCH) ``` ## Value ```ts createMappingDecorator(RequestMethod.PROPPATCH) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|PROPPATCH /resource| Router[Application Router] Router -->|Matches path| Decorator[@Proppatch()] Decorator --> Handler[Controller Method] Handler --> Response[WebDAV Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Proppatch } from '@your-package/common'; @Controller('files') export class FilesController { @Proppatch(':path') async updateProperties() { // Read and apply WebDAV property updates for the resource. return { statusCode: 207, }; } } ``` ## AI Coding Instructions - Apply `@Proppatch()` only to controller methods intended to handle WebDAV `PROPPATCH` requests. - Keep the decorator path relative to the controller-level route prefix. - Return responses appropriate for WebDAV property updates, such as a `207 Multi-Status` response when multiple properties are processed. - Preserve WebDAV request parsing and property-update behavior in the handler or its delegated service; the decorator only performs route mapping. # Put **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L75) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP PUT requests to the specified path. `Put` is a route handler decorator that maps an HTTP `PUT` request to a controller method. Use it to define endpoints that update or replace a resource at a specific path, integrating the method with the framework's request-routing metadata. ## Definition ```ts createMappingDecorator(RequestMethod.PUT) ``` ## Value ```ts createMappingDecorator(RequestMethod.PUT) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|PUT /resources/:id| Router[HTTP Router] Router -->|Matches route metadata| Controller[Controller Method] Put["@Put('resources/:id')"] --> Controller Controller --> Response[HTTP Response] ``` ## Usage ```ts import { Controller, Put, Body, Param } from '@nestjs/common'; @Controller('users') export class UsersController { @Put(':id') updateUser( @Param('id') id: string, @Body() updateUserDto: UpdateUserDto, ) { return { id, ...updateUserDto, }; } } ``` ## AI Coding Instructions - Apply `@Put()` only to controller methods that should handle HTTP `PUT` requests. - Provide a path argument such as `@Put(':id')` when the route targets a specific resource; omit it only when using the controller-level path. - Combine `@Put()` with parameter decorators such as `@Param()`, `@Body()`, and `@Query()` to access request data. - Prefer `PUT` for full resource replacement or idempotent updates; use `PATCH` when supporting partial updates. - Ensure the controller's base path and the `@Put()` path do not create unintended or duplicate route URLs. # Search **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L120) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes HTTP SEARCH requests to the specified path. `Search` is a route-handler method decorator that maps an HTTP `SEARCH` request to a controller method. Use it to declare WebDAV-style or custom SEARCH endpoints and optionally associate the handler with a specific route path. The decorator integrates with the framework’s request-mapping metadata so the router can discover the method and dispatch matching `SEARCH` requests to it. ## Definition ```ts createMappingDecorator(RequestMethod.SEARCH) ``` ## Value ```ts createMappingDecorator(RequestMethod.SEARCH) ``` ## Diagram ```mermaid graph LR Client[HTTP Client] -->|SEARCH /resources| Router[HTTP Router] Router -->|Matches route metadata| Controller[Controller Method] SearchDecorator["@Search('/resources')"] -->|Registers SEARCH mapping metadata| Controller Controller --> Response[HTTP Response] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { Search } from '@nestjs/common/decorators/http/request-mapping.decorator'; @Controller('documents') export class DocumentsController { @Search() searchDocuments() { return { results: [], }; } @Search('advanced') advancedSearch() { return { results: [], filtersApplied: true, }; } } ``` ## AI Coding Instructions - Apply `@Search()` only to controller methods that should handle HTTP `SEARCH` requests. - Pass a path argument such as `@Search('advanced')` when the handler should map to a sub-route; omit it to use the controller-level path. - Ensure the deployment server, proxy, and HTTP client support the non-standard `SEARCH` HTTP method. - Keep search-specific request parsing and validation in the handler or dedicated DTO/validation layer rather than in the decorator. - Use the framework’s other request-mapping decorators for standard HTTP verbs instead of overloading `@Search()` for `GET` or `POST` behavior. # Transform **Kind:** Type **Source:** [`packages/common/interfaces/features/pipe-transform.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/pipe-transform.interface.ts#L4) **Part of:** [Common](subsystem-packages-common) ## Definition ```ts (value: T, metadata: ArgumentMetadata) => any ``` # Unlock **Kind:** Constant **Source:** [`packages/common/decorators/http/request-mapping.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/decorators/http/request-mapping.decorator.ts#L183) **Part of:** [Common](subsystem-packages-common) Route handler (method) Decorator. Routes Webdav UNLOCK requests to the specified path. `Unlock` is a route handler decorator for WebDAV `UNLOCK` requests. Apply it to a controller method to map an `UNLOCK` request for a specific path to that handler, allowing the application to release an existing WebDAV lock. ## Definition ```ts createMappingDecorator(RequestMethod.UNLOCK) ``` ## Value ```ts createMappingDecorator(RequestMethod.UNLOCK) ``` ## Diagram ```mermaid graph LR Client[WebDAV Client] -->|UNLOCK /resource| Router[HTTP Request Router] Router -->|Matches path and UNLOCK method| Decorator["@Unlock('/resource')"] Decorator --> Handler[Controller Method] Handler --> Response[HTTP Response] ``` ## Usage ```ts import { Unlock } from '@your-package/common/decorators/http/request-mapping.decorator'; class WebDavController { @Unlock('/documents/:id') async unlockDocument() { // Release the lock for the requested document. return { statusCode: 204, }; } } ``` ## AI Coding Instructions - Use `@Unlock()` only on controller methods responsible for handling WebDAV `UNLOCK` requests. - Provide a path that matches the resource route used by the corresponding WebDAV lock handling logic. - Keep lock validation and token handling inside the decorated handler or delegated service layer. - Do not use `Unlock` for generic HTTP `DELETE` or update operations; it is specifically for the WebDAV `UNLOCK` method. - Ensure the application’s HTTP router and WebDAV middleware support the `UNLOCK` HTTP verb. # Reflector **Kind:** Class **Source:** [`packages/core/services/reflector.service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/services/reflector.service.ts#L44) **Part of:** [Core](subsystem-packages-core) Helper class providing Nest reflection capabilities. `Reflector` is Nest’s metadata access service for creating typed decorators and reading metadata attached to classes and methods. It is commonly injected into guards, interceptors, and other framework components to make runtime decisions based on decorator configuration. ## Methods | Method | Signature | Returns | |---|---|---| | `createDecorator` | `createDecorator(options: CreateDecoratorOptions)` | `ReflectableDecorator` | | `createDecorator` | `createDecorator(options: CreateDecoratorWithTransformOptions)` | `ReflectableDecorator` | | `createDecorator` | `createDecorator(options: CreateDecoratorOptions)` | `ReflectableDecorator` | | `get` | `get(decorator: T, target: Type | Function)` | `T extends ReflectableDecorator ? R : unknown` | | `get` | `get(metadataKey: TKey, target: Type | Function)` | `TResult` | | `get` | `get(metadataKeyOrDecorator: TKey, target: Type | Function)` | `TResult` | | `getAll` | `getAll(decorator: ReflectableDecorator, targets: (Type | Function)[])` | `TTransformed extends Array ? TTransformed : TTransformed[]` | | `getAll` | `getAll(metadataKey: TKey, targets: (Type | Function)[])` | `TResult` | | `getAll` | `getAll(metadataKeyOrDecorator: TKey, targets: (Type | Function)[])` | `TResult` | | `getAllAndMerge` | `getAllAndMerge(decorator: ReflectableDecorator, targets: (Type | Function)[])` | `TTransformed extends Array ? TTransformed : TTransformed extends object ? TTransformed : TTransformed[]` | | `getAllAndMerge` | `getAllAndMerge(metadataKey: TKey, targets: (Type | Function)[])` | `TResult` | | `getAllAndMerge` | `getAllAndMerge(metadataKeyOrDecorator: TKey, targets: (Type | Function)[])` | `TResult` | | `getAllAndOverride` | `getAllAndOverride(decorator: ReflectableDecorator, targets: (Type | Function)[])` | `TTransformed` | | `getAllAndOverride` | `getAllAndOverride(metadataKey: TKey, targets: (Type | Function)[])` | `TResult` | | `getAllAndOverride` | `getAllAndOverride(metadataKeyOrDecorator: TKey, targets: (Type | Function)[])` | `TResult | undefined` | ## Where it refuses work - `Reflector` stops the work with an early return when `isEmpty(metadataCollection)`. - `Reflector` stops the work with an early return when `isObject(value)`. - `Reflector` stops the work with an early return when `Array.isArray(a)`. - `Reflector` stops the work with an early return when `isObject(a) && isObject(b)`. - `Reflector` stops the work with an early return when `result !== undefined`. ## Diagram ```mermaid graph LR D[Reflector.createDecorator] --> M[Metadata decorator] M --> C[Controller class] M --> H[Route handler] C --> R[Reflector service] H --> R R --> G[Guard / Interceptor] G --> A[Authorization or runtime behavior] ``` ## Usage ```ts import { CanActivate, ExecutionContext, Injectable, } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; // Create a typed decorator for attaching role metadata. export const Roles = Reflector.createDecorator(); @Injectable() export class RolesGuard implements CanActivate { constructor(private readonly reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const roles = this.reflector.getAllAndMerge(Roles, [ context.getClass(), context.getHandler(), ]); const user = context.switchToHttp().getRequest().user; return roles.length === 0 || roles.some((role) => user.roles?.includes(role)); } } // Usage in a controller: // @Roles(['admin']) // @Get('reports') // getReports() {} ``` ## AI Coding Instructions - Prefer `Reflector.createDecorator()` for new metadata keys so decorators and metadata reads remain type-safe. - Inject `Reflector` through Nest dependency injection; do not manually instantiate it in guards or interceptors. - Pass both `context.getClass()` and `context.getHandler()` to `getAll()` or `getAllAndMerge()` when metadata may be defined at either scope. - Use `getAllAndMerge()` for cumulative metadata such as role or permission arrays; ensure the consuming code handles empty results. - Keep decorator metadata serializable and lightweight, since it is evaluated during request handling. ## Used by 12 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Injected or called by (5) - `RolesGuard` — `integration/inspector/src/common/guards/roles.guard.ts`:4 - `RolesGuard` — `sample/01-cats-app/src/common/guards/roles.guard.ts`:5 - `RolesGuard` — `sample/10-fastify/src/common/guards/roles.guard.ts`:4 - `AuthGuard` — `sample/19-auth-jwt/src/auth/auth.guard.ts`:13 - `RolesGuard` — `sample/36-hmr-esm/src/common/guards/roles.guard.ts`:5 ### Imported by (7) - `RolesGuard` — `integration/inspector/src/common/guards/roles.guard.ts`:4 - `RolesGuard` — `sample/01-cats-app/src/common/guards/roles.guard.ts`:5 - `RolesGuard` — `sample/10-fastify/src/common/guards/roles.guard.ts`:4 - `AuthGuard` — `sample/19-auth-jwt/src/auth/auth.guard.ts`:13 - `RolesGuard` — `sample/36-hmr-esm/src/common/guards/roles.guard.ts`:5 - `Roles` — `sample/01-cats-app/src/common/decorators/roles.decorator.ts`:3 - `Roles` — `sample/36-hmr-esm/src/common/decorators/roles.decorator.ts`:3 # NestContainer **Kind:** Class **Source:** [`packages/core/injector/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/container.ts#L31) **Part of:** [Core](subsystem-packages-core) `NestContainer` is NestJS’s internal registry for application modules, dynamic module metadata, global modules, and HTTP adapter references. During bootstrap, it compiles and stores modules so the injector and dependency-scanning pipeline can resolve providers, imports, and global dependencies. ## Methods | Method | Signature | Returns | |---|---|---| | `setHttpAdapter` | `setHttpAdapter(httpAdapter: any)` | `void` | | `getHttpAdapterRef` | `getHttpAdapterRef()` | `void` | | `getHttpAdapterHostRef` | `getHttpAdapterHostRef()` | `void` | | `addModule` | `addModule(metatype: ModuleMetatype, scope: ModuleScope)` | `Promise< | { moduleRef: Module; inserted: boolean; } | undefined >` | | `replaceModule` | `replaceModule(metatypeToReplace: ModuleMetatype, newMetatype: ModuleMetatype, scope: ModuleScope)` | `Promise< | { moduleRef: Module; inserted: boolean; } | undefined >` | | `addDynamicMetadata` | `addDynamicMetadata(token: string, dynamicModuleMetadata: Partial, scope: Type[])` | `void` | | `addDynamicModules` | `addDynamicModules(modules: any[], scope: Type[])` | `void` | | `isGlobalModule` | `isGlobalModule(metatype: Type, dynamicMetadata: Partial)` | `boolean` | | `addGlobalModule` | `addGlobalModule(module: Module)` | `void` | | `getModules` | `getModules()` | `ModulesContainer` | | `getModuleCompiler` | `getModuleCompiler()` | `ModuleCompiler` | | `getModuleByKey` | `getModuleByKey(moduleKey: string)` | `Module | undefined` | | `getInternalCoreModuleRef` | `getInternalCoreModuleRef()` | `Module | undefined` | | `addImport` | `addImport(relatedModule: Type | DynamicModule, token: string)` | `void` | | `addProvider` | `addProvider(provider: Provider, token: string, enhancerSubtype: EnhancerSubtype)` | `string | symbol | Function` | | `addInjectable` | `addInjectable(injectable: Provider, token: string, enhancerSubtype: EnhancerSubtype, host: Type)` | `void` | | `addExportedProviderOrModule` | `addExportedProviderOrModule(toExport: Type | DynamicModule, token: string)` | `void` | | `addController` | `addController(controller: Type, token: string)` | `void` | | `clear` | `clear()` | `void` | | `replace` | `replace(toReplace: any, options: { scope: any[] | null })` | `void` | | `bindGlobalScope` | `bindGlobalScope()` | `void` | | `bindGlobalsToImports` | `bindGlobalsToImports(moduleRef: Module)` | `void` | | `bindGlobalModuleToModule` | `bindGlobalModuleToModule(target: Module, globalModule: Module)` | `void` | | `getDynamicMetadataByToken` | `getDynamicMetadataByToken(token: string)` | `Partial` | | `getDynamicMetadataByToken` | `getDynamicMetadataByToken(token: string, metadataKey: K)` | `DynamicModule[K]` | | `getDynamicMetadataByToken` | `getDynamicMetadataByToken(token: string, metadataKey: Exclude)` | `void` | | `registerCoreModuleRef` | `registerCoreModuleRef(moduleRef: Module)` | `void` | | `getModuleTokenFactory` | `getModuleTokenFactory()` | `ModuleOpaqueKeyFactory` | | `registerRequestProvider` | `registerRequestProvider(request: T, contextId: ContextId)` | `void` | ## Where it refuses work - `NestContainer` stops the work with `UnknownModuleException` when `!this.modules.has(token)`, in 3 places. - `NestContainer` stops the work with `UndefinedForwardRefException` when `!metatype`. - `NestContainer` stops the work with `UndefinedForwardRefException` when `!metatypeToReplace || !newMetatype`. - `NestContainer` stops the work with `CircularDependencyException` when `!provider`. - `NestContainer` stops the work with `UnknownModuleException` when `!moduleRef`. - `NestContainer` stops the work with an early return when `!this.internalProvidersStorage.httpAdapterHost`. ## Diagram ```mermaid graph LR Bootstrap[Nest application bootstrap] --> Container[NestContainer] Container --> Compiler[ModuleCompiler] Compiler --> Modules[ModulesContainer] Container --> DynamicMetadata[Dynamic module metadata] Container --> GlobalModules[Global module registry] Container --> Adapter[HTTP adapter reference] Modules --> Injector[Dependency injector] GlobalModules --> Injector ``` ## Usage ```ts import { NestContainer } from '@nestjs/core/injector/container'; import { ExpressAdapter } from '@nestjs/platform-express'; import { AppModule } from './app.module'; // NestContainer is typically created internally by NestFactory. // This example demonstrates the underlying module registration flow. async function registerApplicationModule() { const container = new NestContainer(); container.setHttpAdapter(new ExpressAdapter()); const result = await container.addModule(AppModule); if (result?.inserted) { console.log(`Registered module: ${result.moduleRef.metatype.name}`); } const modules = container.getModules(); console.log(`Registered modules: ${modules.size}`); return container; } ``` ## AI Coding Instructions - Treat `NestContainer` as framework infrastructure; application code should generally use `NestFactory` instead of constructing it directly. - Register modules through `addModule()` so module compilation, dynamic metadata handling, and token generation remain consistent. - Use `replaceModule()` only for controlled overrides, such as testing or platform-level module replacement. - When adding dynamic modules, preserve their metadata through `addDynamicMetadata()` and `addDynamicModules()` rather than mutating the module registry directly. - Mark and register global modules through the container flow so their exported providers are available across the application. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Provider` - IMPORTS → `EnhancerSubtype` - IMPORTS → `GLOBAL_MODULE_METADATA` - IMPORTS → `Injectable` - IMPORTS → `Type` - IMPORTS → `NestApplicationContextOptions` ## Used by 9 references from 9 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (9) - `ExceptionFiltersContext` — `packages/microservices/context/exception-filters-context.ts`:16 - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingInjector` — `packages/testing/testing-injector.ts`:23 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 - `TestingModule` — `packages/testing/testing-module.ts`:26 - `ExceptionFiltersContext` — `packages/websockets/context/exception-filters-context.ts`:10 …and 1 more. # ApplicationConfig **Kind:** Class **Source:** [`packages/core/application-config.ts`](https://github.com/nestjs/nest/blob/master/packages/core/application-config.ts#L13) **Part of:** [Core](subsystem-packages-core) `ApplicationConfig` stores application-wide runtime configuration used by the NestJS application bootstrap process. It manages global HTTP prefix settings, WebSocket adapters, pipes, and exception filters so these concerns can be applied consistently across the application. ## Methods | Method | Signature | Returns | |---|---|---| | `setGlobalPrefix` | `setGlobalPrefix(prefix: string)` | `void` | | `getGlobalPrefix` | `getGlobalPrefix()` | `void` | | `setGlobalPrefixOptions` | `setGlobalPrefixOptions(options: GlobalPrefixOptions)` | `void` | | `getGlobalPrefixOptions` | `getGlobalPrefixOptions()` | `GlobalPrefixOptions` | | `setIoAdapter` | `setIoAdapter(ioAdapter: WebSocketAdapter)` | `void` | | `getIoAdapter` | `getIoAdapter()` | `WebSocketAdapter` | | `addGlobalPipe` | `addGlobalPipe(pipe: PipeTransform)` | `void` | | `useGlobalPipes` | `useGlobalPipes(pipes: PipeTransform[])` | `void` | | `getGlobalFilters` | `getGlobalFilters()` | `ExceptionFilter[]` | | `addGlobalFilter` | `addGlobalFilter(filter: ExceptionFilter)` | `void` | | `useGlobalFilters` | `useGlobalFilters(filters: ExceptionFilter[])` | `void` | | `getGlobalPipes` | `getGlobalPipes()` | `PipeTransform[]` | | `getGlobalInterceptors` | `getGlobalInterceptors()` | `NestInterceptor[]` | | `addGlobalInterceptor` | `addGlobalInterceptor(interceptor: NestInterceptor)` | `void` | | `useGlobalInterceptors` | `useGlobalInterceptors(interceptors: NestInterceptor[])` | `void` | | `getGlobalGuards` | `getGlobalGuards()` | `CanActivate[]` | | `addGlobalGuard` | `addGlobalGuard(guard: CanActivate)` | `void` | | `useGlobalGuards` | `useGlobalGuards(guards: CanActivate[])` | `void` | | `addGlobalRequestInterceptor` | `addGlobalRequestInterceptor(wrapper: InstanceWrapper)` | `void` | | `getGlobalRequestInterceptors` | `getGlobalRequestInterceptors()` | `InstanceWrapper[]` | | `addGlobalRequestPipe` | `addGlobalRequestPipe(wrapper: InstanceWrapper)` | `void` | | `getGlobalRequestPipes` | `getGlobalRequestPipes()` | `InstanceWrapper[]` | | `addGlobalRequestFilter` | `addGlobalRequestFilter(wrapper: InstanceWrapper)` | `void` | | `getGlobalRequestFilters` | `getGlobalRequestFilters()` | `InstanceWrapper[]` | | `addGlobalRequestGuard` | `addGlobalRequestGuard(wrapper: InstanceWrapper)` | `void` | | `getGlobalRequestGuards` | `getGlobalRequestGuards()` | `InstanceWrapper[]` | | `enableVersioning` | `enableVersioning(options: VersioningOptions)` | `void` | | `getVersioning` | `getVersioning()` | `VersioningOptions | undefined` | ## Diagram ```mermaid graph LR App[Nest Application] --> Config[ApplicationConfig] Config --> Prefix[Global Prefix] Config --> PrefixOptions[Prefix Exclusion Options] Config --> IoAdapter[WebSocket Adapter] Config --> Pipes[Global Pipes] Config --> Filters[Global Exception Filters] Prefix --> Routes[HTTP Routes] IoAdapter --> Gateways[WebSocket Gateways] Pipes --> Requests[Incoming Requests] Filters --> Errors[Unhandled Exceptions] ``` ## Usage ```ts import { RequestMethod, ValidationPipe } from '@nestjs/common'; import { ApplicationConfig } from '@nestjs/core/application-config'; import { WsAdapter } from '@nestjs/platform-ws'; const config = new ApplicationConfig(); // Configure HTTP route prefixing. config.setGlobalPrefix('api'); config.setGlobalPrefixOptions({ exclude: [{ path: 'health', method: RequestMethod.GET }], }); // Apply request validation globally. config.addGlobalPipe( new ValidationPipe({ transform: true, whitelist: true, }), ); // Configure the WebSocket transport adapter. config.setIoAdapter(new WsAdapter()); // Inspect configured values when integrating with application bootstrap. console.log(config.getGlobalPrefix()); // "api" console.log(config.getIoAdapter()); console.log(config.getGlobalFilters()); ``` ## AI Coding Instructions - Use `setGlobalPrefix()` and `setGlobalPrefixOptions()` together when routes need a shared prefix with explicit exclusions. - Prefer `useGlobalPipes(...pipes)` when registering multiple pipes at once; use `addGlobalPipe()` for incremental registration. - Ensure global pipes and filters are registered during application setup, before handling requests or initializing gateways. - Provide a valid `WebSocketAdapter` implementation through `setIoAdapter()` before starting WebSocket gateway infrastructure. - Treat values returned by getters as application-wide configuration state; avoid mutating returned collections directly. ## Relationships - IMPORTS → `CanActivate` - IMPORTS → `ExceptionFilter` - IMPORTS → `NestInterceptor` - IMPORTS → `PipeTransform` - IMPORTS → `VersioningOptions` - IMPORTS → `WebSocketAdapter` - IMPORTS → `GlobalPrefixOptions` ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `ExceptionFiltersContext` — `packages/microservices/context/exception-filters-context.ts`:16 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 - `TestingModule` — `packages/testing/testing-module.ts`:26 - `SocketModule` — `packages/websockets/socket-module.ts`:27 - `SocketServerProvider` — `packages/websockets/socket-server-provider.ts`:8 - `WebSocketsController` — `packages/websockets/web-sockets-controller.ts`:29 # InstanceWrapper **Kind:** Class **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L66) **Part of:** [Core](subsystem-packages-core) `InstanceWrapper` is the internal dependency-injection record for a provider, storing its token, metatype, scope, and resolved instances. It manages provider instances per request context or transient inquirer, while also retaining constructor and property dependency metadata used during resolution. ## Methods | Method | Signature | Returns | |---|---|---| | `getInstanceByContextId` | `getInstanceByContextId(contextId: ContextId, inquirerId: string)` | `InstancePerContext` | | `getInstanceByInquirerId` | `getInstanceByInquirerId(contextId: ContextId, inquirerId: string)` | `InstancePerContext` | | `setInstanceByContextId` | `setInstanceByContextId(contextId: ContextId, value: InstancePerContext, inquirerId: string)` | `void` | | `setInstanceByInquirerId` | `setInstanceByInquirerId(contextId: ContextId, inquirerId: string, value: InstancePerContext)` | `void` | | `removeInstanceByContextId` | `removeInstanceByContextId(contextId: ContextId, inquirerId: string)` | `void` | | `removeInstanceByInquirerId` | `removeInstanceByInquirerId(contextId: ContextId, inquirerId: string)` | `void` | | `addCtorMetadata` | `addCtorMetadata(index: number, wrapper: InstanceWrapper)` | `void` | | `getCtorMetadata` | `getCtorMetadata()` | `InstanceWrapper[]` | | `addPropertiesMetadata` | `addPropertiesMetadata(key: symbol | string, wrapper: InstanceWrapper)` | `void` | | `getPropertiesMetadata` | `getPropertiesMetadata()` | `PropertyMetadata[]` | | `addEnhancerMetadata` | `addEnhancerMetadata(wrapper: InstanceWrapper)` | `void` | | `getEnhancersMetadata` | `getEnhancersMetadata()` | `InstanceWrapper[]` | | `isDependencyTreeDurable` | `isDependencyTreeDurable(lookupRegistry: string[])` | `boolean` | | `introspectDepsAttribute` | `introspectDepsAttribute(callback: ( collection: InstanceWrapper[], lookupRegistry: string[], ) => boolean, lookupRegistry: string[])` | `boolean` | | `isDependencyTreeStatic` | `isDependencyTreeStatic(lookupRegistry: string[])` | `boolean` | | `cloneStaticInstance` | `cloneStaticInstance(contextId: ContextId)` | `InstancePerContext` | | `cloneTransientInstance` | `cloneTransientInstance(contextId: ContextId, inquirerId: string)` | `InstancePerContext` | | `createPrototype` | `createPrototype(contextId: ContextId)` | `void` | | `isInRequestScope` | `isInRequestScope(contextId: ContextId, inquirer: InstanceWrapper)` | `boolean` | | `isLazyTransient` | `isLazyTransient(contextId: ContextId, inquirer: InstanceWrapper | undefined)` | `boolean` | | `isExplicitlyRequested` | `isExplicitlyRequested(contextId: ContextId, inquirer: InstanceWrapper)` | `boolean` | | `isStatic` | `isStatic(contextId: ContextId, inquirer: InstanceWrapper | undefined)` | `boolean` | | `attachRootInquirer` | `attachRootInquirer(inquirer: InstanceWrapper)` | `void` | | `getRootInquirer` | `getRootInquirer()` | `InstanceWrapper | undefined` | | `getStaticTransientInstances` | `getStaticTransientInstances()` | `void` | | `mergeWith` | `mergeWith(provider: Provider)` | `void` | ## Properties | Property | Type | |---|---| | `name` | `any` | | `token` | `InjectionToken` | | `async` | `boolean` | | `host` | `Module` | | `isAlias` | `boolean` | | `subtype` | `EnhancerSubtype` | | `scope` | `Scope` | | `metatype` | `Type | Function | null` | | `inject` | `FactoryProvider['inject'] | null` | | `forwardRef` | `boolean` | | `durable` | `boolean` | | `initTime` | `number` | | `settlementSignal` | `SettlementSignal` | ## Where it refuses work - `InstanceWrapper` stops the work with an early return when `this.scope === Scope.TRANSIENT && inquirerId`, in 3 places. - `InstanceWrapper` stops the work with an early return when `!this.isTransient`, in 2 places. - `InstanceWrapper` stops the work with an early return when `!collection`. - `InstanceWrapper` stops the work with an early return when `!isUndefined(this.isTreeDurable)`. - `InstanceWrapper` stops the work with an early return when `isStatic`. - `InstanceWrapper` stops the work with an early return when `lookupRegistry.includes(this[INSTANCE_ID_SYMBOL])`. ## Diagram ```mermaid graph LR Injector[Injector / Resolver] --> Wrapper[InstanceWrapper] Wrapper --> Metadata[Constructor & Property Metadata] Wrapper --> ContextStore[Context ID Instance Store] Wrapper --> TransientStore[Inquirer ID Instance Store] ContextStore --> RequestInstance[InstancePerContext] TransientStore --> TransientInstance[InstancePerContext] ``` ## Usage ```ts import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; import { ContextIdFactory } from '@nestjs/core/helpers/context-id-factory'; class LoggerService { log(message: string) { console.log(message); } } const loggerWrapper = new InstanceWrapper({ token: LoggerService, name: LoggerService.name, metatype: LoggerService, }); const contextId = ContextIdFactory.create(); loggerWrapper.setInstanceByContextId(contextId, { instance: new LoggerService(), isResolved: true, }); const instanceRecord = loggerWrapper.getInstanceByContextId(contextId); instanceRecord.instance.log('Resolved from the current context'); // Remove request-scoped data when the context is no longer needed. loggerWrapper.removeInstanceByContextId(contextId); ``` ## AI Coding Instructions - Treat `InstanceWrapper` as DI-container infrastructure; application code should normally consume providers through injection instead of creating wrappers directly. - Use `getInstanceByContextId()` and `setInstanceByContextId()` for request- or context-specific provider state. - For transient providers, preserve the inquirer ID when reading or storing instances so each consumer receives the correct instance. - Register constructor dependencies with `addCtorMetadata()` and property dependencies with `addPropertiesMetadata()` using the resolved dependency wrappers. - Remove context-bound instances after a request or custom context completes to avoid retaining unnecessary scoped instances. ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `ExceptionFiltersContext` — `packages/microservices/context/exception-filters-context.ts`:16 - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `TestingInjector` — `packages/testing/testing-injector.ts`:23 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # GraphInspector **Kind:** Class **Source:** [`packages/core/inspector/graph-inspector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/graph-inspector.ts#L13) **Part of:** [Core](subsystem-packages-core) `GraphInspector` builds and enriches Nest’s serialized dependency graph by inspecting modules, providers, controllers, and instance wrappers. It records class nodes, entry points, and enhancer relationships, while tracking partial graphs when inspection cannot complete successfully. This class is primarily used by Nest’s internal scanning and diagnostics infrastructure. ## Methods | Method | Signature | Returns | |---|---|---| | `inspectModules` | `inspectModules(modules: Map)` | `void` | | `registerPartial` | `registerPartial(error: unknown)` | `void` | | `inspectInstanceWrapper` | `inspectInstanceWrapper(source: InstanceWrapper, moduleRef: Module)` | `void` | | `insertEnhancerMetadataCache` | `insertEnhancerMetadataCache(entry: EnhancerMetadataCacheEntry)` | `void` | | `insertOrphanedEnhancer` | `insertOrphanedEnhancer(entry: OrphanedEnhancerDefinition)` | `void` | | `insertAttachedEnhancer` | `insertAttachedEnhancer(wrapper: InstanceWrapper)` | `void` | | `insertEntrypointDefinition` | `insertEntrypointDefinition(definition: Entrypoint, parentId: string)` | `void` | | `insertClassNode` | `insertClassNode(moduleRef: Module, wrapper: InstanceWrapper, type: Exclude)` | `void` | ## Diagram ```mermaid graph LR Modules[Module container] --> InspectModules[inspectModules()] InspectModules --> Wrappers[Instance wrappers] Wrappers --> InspectWrapper[inspectInstanceWrapper()] InspectWrapper --> ClassNode[insertClassNode()] InspectWrapper --> Entrypoint[insertEntrypointDefinition()] InspectWrapper --> Enhancers[Enhancer metadata] Enhancers --> Cache[insertEnhancerMetadataCache()] Cache --> Attached[insertAttachedEnhancer()] Cache --> Orphaned[insertOrphanedEnhancer()] ClassNode --> Graph[SerializedGraph] Entrypoint --> Graph Attached --> Graph Orphaned --> Graph InspectModules -. inspection failure .-> Partial[registerPartial()] Partial --> Graph ``` ## Usage ```ts import { GraphInspector } from '@nestjs/core/inspector/graph-inspector'; import { SerializedGraph } from '@nestjs/core/inspector/serialized-graph'; // Typically created and used internally during Nest application scanning. const graph = new SerializedGraph(); const inspector = new GraphInspector(graph); try { // `container` represents Nest's internal module container. inspector.inspectModules(container.getModules()); } catch (error) { // Preserve the graph and mark it as incomplete when inspection fails. inspector.registerPartial(error); } // The serialized graph can then be consumed by diagnostics or tooling. console.log(graph); ``` ## AI Coding Instructions - Treat `GraphInspector` as internal infrastructure: preserve its relationship with `SerializedGraph`, module scanning, and dependency-wrapper metadata. - When adding a new graph element, ensure it is inserted consistently through the appropriate node, entry-point, or enhancer method. - Cache enhancer metadata before resolving attached or orphaned enhancers; enhancer relationships may be discovered after their source wrapper is inspected. - Use `registerPartial()` when inspection failures should not prevent application startup or diagnostic graph output. - Avoid assuming every wrapper has a concrete class or host relationship; dynamic providers, aliases, and orphaned enhancers require defensive handling. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 - `TestingModule` — `packages/testing/testing-module.ts`:26 - `SocketModule` — `packages/websockets/socket-module.ts`:27 - `WebSocketsController` — `packages/websockets/web-sockets-controller.ts`:29 # Injector **Kind:** Class **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L93) **Part of:** [Core](subsystem-packages-core) `Injector` is Nest’s internal dependency-injection runtime responsible for creating class, factory, controller, middleware, and provider instances. It resolves constructor dependencies, tracks circular or asynchronous resolution through settlement signals, and stores resolved instances in their module collections and execution contexts. ## Methods | Method | Signature | Returns | |---|---|---| | `loadPrototype` | `loadPrototype({ token }: InstanceWrapper, collection: Map>, contextId: undefined)` | `void` | | `loadInstance` | `loadInstance(wrapper: InstanceWrapper, collection: Map, moduleRef: Module, resolutionContext: ResolutionContext)` | `void` | | `loadMiddleware` | `loadMiddleware(wrapper: InstanceWrapper, collection: Map, moduleRef: Module, contextId: undefined, inquirer: InstanceWrapper)` | `void` | | `loadController` | `loadController(wrapper: InstanceWrapper, moduleRef: Module, contextId: undefined)` | `void` | | `loadInjectable` | `loadInjectable(wrapper: InstanceWrapper, moduleRef: Module, contextId: undefined, inquirer: InstanceWrapper)` | `void` | | `loadProvider` | `loadProvider(wrapper: InstanceWrapper, moduleRef: Module, resolutionContext: ResolutionContext)` | `void` | | `applySettlementSignal` | `applySettlementSignal(instancePerContext: InstancePerContext, host: InstanceWrapper)` | `void` | | `resolveConstructorParams` | `resolveConstructorParams(wrapper: InstanceWrapper, moduleRef: Module, inject: InjectorDependency[] | undefined, callback: (args: unknown[]) => void | Promise, resolutionContext: ResolutionContext, parentInquirer: InstanceWrapper)` | `void` | | `getClassDependencies` | `getClassDependencies(wrapper: InstanceWrapper)` | `[InjectorDependency[], number[]]` | | `getFactoryProviderDependencies` | `getFactoryProviderDependencies(wrapper: InstanceWrapper)` | `[InjectorDependency[], number[]]` | | `reflectConstructorParams` | `reflectConstructorParams(type: Type | Function)` | `any[]` | | `reflectOptionalParams` | `reflectOptionalParams(type: Type | Function)` | `any[]` | | `reflectSelfParams` | `reflectSelfParams(type: Type | Function)` | `any[]` | | `resolveSingleParam` | `resolveSingleParam(wrapper: InstanceWrapper, param: Type | string | symbol, dependencyContext: InjectorDependencyContext, moduleRef: Module, resolutionContext: ResolutionContext, keyOrIndex: symbol | string | number)` | `void` | | `resolveParamToken` | `resolveParamToken(wrapper: InstanceWrapper, param: Type | string | symbol | ForwardReference)` | `void` | | `resolveComponentWrapper` | `resolveComponentWrapper(moduleRef: Module, token: InjectionToken, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper, resolutionContext: ResolutionContext, keyOrIndex: symbol | string | number)` | `Promise` | | `resolveComponentHost` | `resolveComponentHost(moduleRef: Module, instanceWrapper: InstanceWrapper>, resolutionContext: ResolutionContext)` | `Promise` | | `lookupComponent` | `lookupComponent(providers: Map, moduleRef: Module, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper, resolutionContext: ResolutionContext, keyOrIndex: symbol | string | number)` | `Promise>` | | `lookupComponentInParentModules` | `lookupComponentInParentModules(dependencyContext: InjectorDependencyContext, moduleRef: Module, wrapper: InstanceWrapper, resolutionContext: ResolutionContext, keyOrIndex: symbol | string | number)` | `void` | | `lookupComponentInImports` | `lookupComponentInImports(moduleRef: Module, name: InjectionToken, wrapper: InstanceWrapper, moduleRegistry: Set, resolutionContext: ResolutionContext, keyOrIndex: symbol | string | number, isTraversing: boolean)` | `Promise` | | `resolveProperties` | `resolveProperties(wrapper: InstanceWrapper, moduleRef: Module, inject: InjectorDependency[], resolutionContext: ResolutionContext, parentInquirer: InstanceWrapper)` | `Promise` | | `reflectProperties` | `reflectProperties(type: Type)` | `PropertyDependency[]` | | `applyProperties` | `applyProperties(instance: T, properties: PropertyDependency[])` | `void` | | `instantiateClass` | `instantiateClass(instances: any[], wrapper: InstanceWrapper, targetMetatype: InstanceWrapper, resolutionContext: ResolutionContext)` | `Promise` | | `loadPerContext` | `loadPerContext(instance: T, moduleRef: Module, collection: Map, ctx: ContextId, wrapper: InstanceWrapper)` | `Promise` | | `loadEnhancersPerContext` | `loadEnhancersPerContext(wrapper: InstanceWrapper, ctx: ContextId, inquirer: InstanceWrapper)` | `void` | | `loadCtorMetadata` | `loadCtorMetadata(metadata: InstanceWrapper[], contextId: ContextId, inquirer: InstanceWrapper, parentInquirer: InstanceWrapper)` | `Promise` | | `loadPropertiesMetadata` | `loadPropertiesMetadata(metadata: PropertyMetadata[], contextId: ContextId, inquirer: InstanceWrapper)` | `Promise` | | `addDependencyMetadata` | `addDependencyMetadata(keyOrIndex: symbol | string | number, hostWrapper: InstanceWrapper, instanceWrapper: InstanceWrapper)` | `void` | ## Where it refuses work - `Injector` stops the work with `CircularDependencyException` when `resolutionContext.inquirer && settlementSignal?.isCycle(resolutionContext.inquirer.id)`. - `Injector` stops the work with `RuntimeException` when `isUndefined(targetWrapper)`. - `Injector` stops the work with `UnknownDependenciesException` when `wrapper && token === name`. - `Injector` stops the work with `UnknownDependenciesException` when `isNil(instanceWrapper)`. - `Injector` stops the work with an early return when `!this.isDebugMode()`, in 3 places. - `Injector` stops the work with an early return when `!collection`. ## When something fails - `Injector` handles failure in 3 places: it lets it reach the caller in all 3. ## Diagram ```mermaid graph LR A[Module collections] --> B[Injector] B --> C[loadProvider / loadInjectable] B --> D[loadController / loadMiddleware] B --> E[loadPrototype] C --> F[resolveConstructorParams] D --> F F --> G[getClassDependencies] F --> H[getFactoryProviderDependencies] G --> I[Instantiate class or factory] H --> I I --> J[applySettlementSignal] J --> K[Resolved instance in InstanceWrapper] ``` ## Usage ```ts import { Injector } from '@nestjs/core/injector/injector'; import { Module } from '@nestjs/core/injector/module'; import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; // This is typically performed by Nest internals during application bootstrap. async function loadCustomProvider( moduleRef: Module, providerWrapper: InstanceWrapper, ) { const injector = new Injector(); // Resolves constructor dependencies and creates the provider instance. await injector.loadProvider(providerWrapper, moduleRef); return providerWrapper.instance; } ``` ## AI Coding Instructions - Treat `Injector` as framework-internal infrastructure; prefer Nest’s public module and provider APIs in application code. - Use `loadProvider`, `loadInjectable`, `loadController`, and `loadMiddleware` with the matching `InstanceWrapper` collection owned by a `Module`. - Preserve the `contextId` and `inquirer` arguments when working with request-scoped or transient providers. - Do not manually bypass `resolveConstructorParams` or `applySettlementSignal`; they handle dependency ordering, async resolution, and circular dependency coordination. - When adding provider types, ensure both class-based and factory-provider dependency paths are represented in `getClassDependencies` or `getFactoryProviderDependencies`. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingInjector` — `packages/testing/testing-injector.ts`:23 # Module **Kind:** Class **Source:** [`packages/core/injector/module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/module.ts#L44) **Part of:** [Core](subsystem-packages-core) `Module` is Nest’s internal runtime representation of an application module within the dependency-injection container. It registers the module itself, `ModuleRef`, application configuration, injectable classes, and custom providers so dependencies can be resolved within the module scope. ## Methods | Method | Signature | Returns | |---|---|---| | `addCoreProviders` | `addCoreProviders()` | `void` | | `addModuleRef` | `addModuleRef()` | `void` | | `addModuleAsProvider` | `addModuleAsProvider()` | `void` | | `addApplicationConfig` | `addApplicationConfig()` | `void` | | `addInjectable` | `addInjectable(injectable: Provider, enhancerSubtype: EnhancerSubtype, host: Type)` | `void` | | `addProvider` | `addProvider(provider: Provider)` | `InjectionToken` | | `addProvider` | `addProvider(provider: Provider, enhancerSubtype: EnhancerSubtype)` | `InjectionToken` | | `addProvider` | `addProvider(provider: Provider, enhancerSubtype: EnhancerSubtype)` | `void` | | `isCustomProvider` | `isCustomProvider(provider: Provider)` | `provider is | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider` | | `addCustomProvider` | `addCustomProvider(provider: | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider, collection: Map, enhancerSubtype: EnhancerSubtype)` | `void` | | `isCustomClass` | `isCustomClass(provider: any)` | `provider is ClassProvider` | | `isCustomValue` | `isCustomValue(provider: any)` | `provider is ValueProvider` | | `isCustomFactory` | `isCustomFactory(provider: any)` | `provider is FactoryProvider` | | `isCustomUseExisting` | `isCustomUseExisting(provider: any)` | `provider is ExistingProvider` | | `isDynamicModule` | `isDynamicModule(exported: any)` | `exported is DynamicModule` | | `addCustomClass` | `addCustomClass(provider: ClassProvider, collection: Map, enhancerSubtype: EnhancerSubtype)` | `void` | | `addCustomValue` | `addCustomValue(provider: ValueProvider, collection: Map, enhancerSubtype: EnhancerSubtype)` | `void` | | `addCustomFactory` | `addCustomFactory(provider: FactoryProvider, collection: Map, enhancerSubtype: EnhancerSubtype)` | `void` | | `addCustomUseExisting` | `addCustomUseExisting(provider: ExistingProvider, collection: Map, enhancerSubtype: EnhancerSubtype)` | `void` | | `addExportedProviderOrModule` | `addExportedProviderOrModule(toExport: Provider | string | symbol | DynamicModule)` | `void` | | `addCustomExportedProvider` | `addCustomExportedProvider(provider: | FactoryProvider | ValueProvider | ClassProvider | ExistingProvider)` | `void` | | `validateExportedProvider` | `validateExportedProvider(token: InjectionToken)` | `void` | | `addController` | `addController(controller: Type)` | `void` | | `assignControllerUniqueId` | `assignControllerUniqueId(controller: Type)` | `void` | | `addImport` | `addImport(moduleRef: Module)` | `void` | | `replace` | `replace(toReplace: InjectionToken, options: any)` | `void` | | `hasProvider` | `hasProvider(token: InjectionToken)` | `boolean` | | `hasInjectable` | `hasInjectable(token: InjectionToken)` | `boolean` | | `getProviderByKey` | `getProviderByKey(name: InjectionToken)` | `InstanceWrapper` | | `getProviderById` | `getProviderById(id: string)` | `InstanceWrapper | undefined` | | `getControllerById` | `getControllerById(id: string)` | `InstanceWrapper | undefined` | | `getInjectableById` | `getInjectableById(id: string)` | `InstanceWrapper | undefined` | | `getMiddlewareById` | `getMiddlewareById(id: string)` | `InstanceWrapper | undefined` | | `getNonAliasProviders` | `getNonAliasProviders()` | `Array< [InjectionToken, InstanceWrapper] >` | | `createModuleReferenceType` | `createModuleReferenceType()` | `Type` | ## Where it refuses work - `Module` stops the work with `RuntimeException` when `!this._providers.has(this._metatype)`. - `Module` stops the work with `InvalidClassException` when `!(type && isFunction(type) && type.prototype)`. - `Module` stops the work with an early return when `this.isCustomProvider(injectable)`. - `Module` stops the work with an early return when `(this.isTransientProvider(provider) || this.isRequestScopeProvider(provider)) && isAlread…`. - `Module` stops the work with an early return when `isString(provide) || isSymbol(provide)`. - `Module` stops the work with an early return when `this._providers.has(token)`. ## Diagram ```mermaid graph LR A[Module Metadata] --> B[Module Instance] B --> C[Core Providers] C --> C1[Module Class Provider] C --> C2[ModuleRef] C --> C3[ApplicationConfig] B --> D[addProvider] B --> E[addInjectable] D --> F{Custom Provider?} F -->|No| G[Class Provider Wrapper] F -->|Yes| H[Factory / Value / Existing / Class Provider] G --> I[Provider Registry] H --> I E --> J[Injectable Registry] ``` ## Usage ```ts import { Module as RuntimeModule } from '@nestjs/core/injector/module'; import { NestContainer } from '@nestjs/core/injector/container'; import { ApplicationConfig } from '@nestjs/core/application-config'; class UsersService { findAll() { return ['Ada', 'Grace']; } } class AppModule {} const applicationConfig = new ApplicationConfig(); const container = new NestContainer(applicationConfig); // RuntimeModule is typically created by Nest internally during scanning. const moduleRef = new RuntimeModule(AppModule, container); // Register a standard class provider. moduleRef.addProvider(UsersService); // Register a custom value provider. moduleRef.addProvider({ provide: 'API_URL', useValue: 'https://api.example.com', }); // Register an injectable used by framework features such as guards or pipes. moduleRef.addInjectable(UsersService); ``` ## AI Coding Instructions - Treat `Module` as an internal Nest container type; application code should usually register providers through the `@Module()` decorator instead. - Use `addProvider()` for both class providers and custom provider objects; custom providers are detected through `isCustomProvider()`. - Preserve provider tokens when adding or modifying registrations, since tokens are the keys used for dependency resolution. - Ensure new providers are associated with the correct module instance so module-scoped resolution and exports continue to work. - Do not remove the core-provider setup path: module classes, `ModuleRef`, and application configuration must remain registered for Nest runtime behavior. ## How it works `Module` is a mutable runtime record for one module metatype within the dependency-injection container. It stores the module class, container reference, an ID, imports, exports, providers, injectables, middleware wrappers, controller wrappers, and entry-provider tokens. [packages/core/injector/module.ts:44-77] The container creates it from a compiled module type, assigns its container token afterward, stores it in the container’s module map, and may mark it global, set its distance to `Number.MAX_VALUE`, and register it among global modules. [packages/core/injector/container.ts:163-184] ## Relationships - IMPORTS → `EnhancerSubtype` - IMPORTS → `ENTRY_PROVIDER_WATERMARK` - IMPORTS → `ClassProvider` - IMPORTS → `Controller` - IMPORTS → `DynamicModule` - IMPORTS → `ExistingProvider` - IMPORTS → `FactoryProvider` - IMPORTS → `Injectable` - IMPORTS → `InjectionToken` - IMPORTS → `NestModule` - IMPORTS → `Provider` - IMPORTS → `Scope` - IMPORTS → `Type` - IMPORTS → `ValueProvider` - IMPORTS → `randomStringGenerator` - IMPORTS → `isFunction` - IMPORTS → `isNil` - IMPORTS → `isObject` - IMPORTS → `isString` - IMPORTS → `isSymbol` - IMPORTS → `isUndefined` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `TestingInjector` — `packages/testing/testing-injector.ts`:23 - `TestingInstanceLoader` — `packages/testing/testing-instance-loader.ts`:6 - `TestingModule` — `packages/testing/testing-module.ts`:26 # AbstractHttpAdapter **Kind:** Class **Source:** [`packages/core/adapters/http-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/adapters/http-adapter.ts#L8) **Part of:** [Core](subsystem-packages-core) `AbstractHttpAdapter` defines the common HTTP server adapter contract used by NestJS platform integrations. It delegates middleware and route registration methods such as `use()`, `get()`, `post()`, and `head()` to the underlying HTTP framework instance, allowing Nest applications to work with different server implementations. **Implements:** `HttpServer` ## Methods | Method | Signature | Returns | |---|---|---| | `init` | `init()` | `void` | | `use` | `use(args: any[])` | `void` | | `get` | `get(handler: RequestHandler)` | `void` | | `get` | `get(path: any, handler: RequestHandler)` | `void` | | `get` | `get(args: any[])` | `void` | | `post` | `post(handler: RequestHandler)` | `void` | | `post` | `post(path: any, handler: RequestHandler)` | `void` | | `post` | `post(args: any[])` | `void` | | `head` | `head(handler: RequestHandler)` | `void` | | `head` | `head(path: any, handler: RequestHandler)` | `void` | | `head` | `head(args: any[])` | `void` | | `delete` | `delete(handler: RequestHandler)` | `void` | | `delete` | `delete(path: any, handler: RequestHandler)` | `void` | | `delete` | `delete(args: any[])` | `void` | | `put` | `put(handler: RequestHandler)` | `void` | | `put` | `put(path: any, handler: RequestHandler)` | `void` | | `put` | `put(args: any[])` | `void` | | `patch` | `patch(handler: RequestHandler)` | `void` | | `patch` | `patch(path: any, handler: RequestHandler)` | `void` | | `patch` | `patch(args: any[])` | `void` | | `propfind` | `propfind(handler: RequestHandler)` | `void` | | `propfind` | `propfind(path: any, handler: RequestHandler)` | `void` | | `propfind` | `propfind(args: any[])` | `void` | | `proppatch` | `proppatch(handler: RequestHandler)` | `void` | | `proppatch` | `proppatch(path: any, handler: RequestHandler)` | `void` | | `proppatch` | `proppatch(args: any[])` | `void` | | `mkcol` | `mkcol(handler: RequestHandler)` | `void` | | `mkcol` | `mkcol(path: any, handler: RequestHandler)` | `void` | | `mkcol` | `mkcol(args: any[])` | `void` | | `copy` | `copy(handler: RequestHandler)` | `void` | | `copy` | `copy(path: any, handler: RequestHandler)` | `void` | | `copy` | `copy(args: any[])` | `void` | | `move` | `move(handler: RequestHandler)` | `void` | | `move` | `move(path: any, handler: RequestHandler)` | `void` | | `move` | `move(args: any[])` | `void` | | `lock` | `lock(handler: RequestHandler)` | `void` | | `lock` | `lock(path: any, handler: RequestHandler)` | `void` | | `lock` | `lock(args: any[])` | `void` | | `unlock` | `unlock(handler: RequestHandler)` | `void` | | `unlock` | `unlock(path: any, handler: RequestHandler)` | `void` | | `unlock` | `unlock(args: any[])` | `void` | | `all` | `all(handler: RequestHandler)` | `void` | | `all` | `all(path: any, handler: RequestHandler)` | `void` | | `all` | `all(args: any[])` | `void` | | `search` | `search(handler: RequestHandler)` | `void` | | `search` | `search(path: any, handler: RequestHandler)` | `void` | | `search` | `search(args: any[])` | `void` | | `options` | `options(handler: RequestHandler)` | `void` | | `options` | `options(path: any, handler: RequestHandler)` | `void` | | `options` | `options(args: any[])` | `void` | ## Properties | Property | Type | |---|---| | `httpServer` | `TServer` | | `onRouteTriggered` | `| ((requestMethod: RequestMethod, path: string) => void) | undefined` | ## Diagram ```mermaid graph LR Nest[Nest Application] --> Adapter[AbstractHttpAdapter] Adapter --> Instance[Underlying HTTP Framework Instance] Adapter --> Init[init()] Adapter --> Middleware[use()] Adapter --> Routes[get() / post() / head()] Middleware --> Instance Routes --> Instance Instance --> Server[HTTP Server] ``` ## Usage ```ts import * as express from 'express'; import { NestFactory } from '@nestjs/core'; import { ExpressAdapter } from '@nestjs/platform-express'; import { AppModule } from './app.module'; async function bootstrap() { const expressApp = express(); const httpAdapter = new ExpressAdapter(expressApp); // Register framework-native middleware through the adapter. httpAdapter.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); // Register routes directly on the underlying platform. httpAdapter.get('/health', (_req, res) => { res.status(200).json({ status: 'ok' }); }); httpAdapter.head('/health', (_req, res) => { res.status(200).end(); }); const app = await NestFactory.create(AppModule, httpAdapter); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Extend `AbstractHttpAdapter` only when integrating a new HTTP platform; use concrete adapters such as `ExpressAdapter` or `FastifyAdapter` in application code. - Delegate route and middleware methods to the underlying framework instance so native platform behavior is preserved. - Keep `get()`, `post()`, and `head()` overload behavior compatible with the target framework’s route-registration API. - Use `use()` for platform middleware registration, but prefer Nest middleware, guards, interceptors, and controllers for application-level concerns. - Ensure the adapter is initialized and passed to `NestFactory.create()` when configuring a custom HTTP server instance. ## How it works `AbstractHttpAdapter` is a public abstract base class for HTTP platform adapters. It implements the `HttpServer` contract and stores both a platform instance and, separately, an HTTP server value. Its type parameters default to `any`. [`packages/core/adapters/http-adapter.ts:5-18`](packages/core/adapters/http-adapter.ts#L5-L18) ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `RequestMethod` - IMPORTS → `VersioningOptions` - IMPORTS → `RequestHandler` - IMPORTS → `VersionValue` - IMPORTS → `NestApplicationOptions` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 - `TestingModule` — `packages/testing/testing-module.ts`:26 # NestApplication **Kind:** Class **Source:** [`packages/core/nest-application.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-application.ts#L54) **Part of:** [Core](subsystem-packages-core) `NestApplication` is the core runtime class behind a Nest HTTP application. It coordinates HTTP server creation, module registration, WebSocket integration, parser middleware, and application lifecycle initialization. Applications are typically created through `NestFactory`, which configures and returns a `NestApplication` instance. **Extends:** `NestApplicationContext` **Implements:** `INestApplication` ## Methods | Method | Signature | Returns | |---|---|---| | `dispose` | `dispose()` | `Promise` | | `getHttpAdapter` | `getHttpAdapter()` | `AbstractHttpAdapter` | | `registerHttpServer` | `registerHttpServer()` | `void` | | `getUnderlyingHttpServer` | `getUnderlyingHttpServer()` | `T` | | `applyOptions` | `applyOptions()` | `void` | | `createServer` | `createServer()` | `T` | | `registerModules` | `registerModules()` | `void` | | `registerWsModule` | `registerWsModule()` | `void` | | `init` | `init()` | `Promise` | | `registerParserMiddleware` | `registerParserMiddleware()` | `void` | | `registerRouter` | `registerRouter()` | `void` | | `registerRouterHooks` | `registerRouterHooks()` | `void` | | `connectMicroservice` | `connectMicroservice(microserviceOptions: T, hybridAppOptions: NestHybridApplicationOptions)` | `INestMicroservice` | | `getMicroservices` | `getMicroservices()` | `INestMicroservice[]` | | `getHttpServer` | `getHttpServer()` | `void` | | `startAllMicroservices` | `startAllMicroservices()` | `Promise` | | `use` | `use(args: [any, any?])` | `this` | | `useBodyParser` | `useBodyParser(args: [any, any?])` | `this` | | `enableCors` | `enableCors(options: any)` | `void` | | `enableVersioning` | `enableVersioning(options: VersioningOptions)` | `this` | | `listen` | `listen(port: number | string)` | `Promise` | | `listen` | `listen(port: number | string, hostname: string)` | `Promise` | | `listen` | `listen(port: number | string, args: any[])` | `Promise` | | `getUrl` | `getUrl()` | `Promise` | | `setGlobalPrefix` | `setGlobalPrefix(prefix: string, options: GlobalPrefixOptions)` | `this` | | `useWebSocketAdapter` | `useWebSocketAdapter(adapter: WebSocketAdapter)` | `this` | | `useGlobalFilters` | `useGlobalFilters(filters: ExceptionFilter[])` | `this` | | `useGlobalPipes` | `useGlobalPipes(pipes: PipeTransform[])` | `this` | | `useGlobalInterceptors` | `useGlobalInterceptors(interceptors: NestInterceptor[])` | `this` | | `useGlobalGuards` | `useGlobalGuards(guards: CanActivate[])` | `this` | | `useStaticAssets` | `useStaticAssets(options: any)` | `this` | | `useStaticAssets` | `useStaticAssets(path: string, options: any)` | `this` | | `useStaticAssets` | `useStaticAssets(pathOrOptions: any, options: any)` | `this` | | `setBaseViewsDir` | `setBaseViewsDir(path: string | string[])` | `this` | | `setViewEngine` | `setViewEngine(engineOrOptions: any)` | `this` | ## Properties | Property | Type | |---|---| | `logger` | `any` | ## Where it refuses work - `NestApplication` stops the work with an early return when `!this.appOptions || !this.appOptions.cors`. - `NestApplication` stops the work with an early return when `!passCustomOptions`. - `NestApplication` stops the work with an early return when `!this.socketModule`. - `NestApplication` stops the work with an early return when `this.isInitialized`. - `NestApplication` stops the work with an early return when `originalCallbackArgs[0] instanceof Error`. - `NestApplication` stops the work with an early return when `platform() === 'win32'`. ## Diagram ```mermaid graph LR A[NestFactory.create()] --> B[NestApplication] B --> C[createServer()] B --> D[registerModules()] B --> E[registerWsModule()] B --> F[registerParserMiddleware()] B --> G[init()] G --> H[HTTP Adapter] H --> I[Underlying HTTP Server] B --> J[dispose()] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Initialize registered modules, middleware, and adapters. await app.init(); const httpAdapter = app.getHttpAdapter(); const server = app.getUnderlyingHttpServer(); console.log(`Using adapter: ${httpAdapter.getType()}`); console.log(`Server available: ${Boolean(server)}`); await app.listen(3000); process.on('SIGTERM', async () => { await app.close(); await app.dispose(); }); } bootstrap(); ``` ## AI Coding Instructions - Create application instances through `NestFactory.create()` rather than constructing `NestApplication` directly. - Preserve the initialization order: register modules and infrastructure before calling `init()`. - Use `getHttpAdapter()` for adapter-specific integrations; avoid assuming Express or Fastify APIs are always available. - Use `getUnderlyingHttpServer()` only when direct access to the native HTTP server is required. - Ensure shutdown paths clean up resources through the application lifecycle, including disposal when appropriate. ## Relationships - IMPORTS → `CanActivate` - IMPORTS → `ExceptionFilter` - IMPORTS → `HttpServer` - IMPORTS → `INestApplication` - IMPORTS → `INestMicroservice` - IMPORTS → `NestHybridApplicationOptions` - IMPORTS → `NestInterceptor` - IMPORTS → `PipeTransform` - IMPORTS → `VersioningOptions` - IMPORTS → `VersioningType` - IMPORTS → `WebSocketAdapter` - IMPORTS → `GlobalPrefixOptions` - IMPORTS → `NestApplicationOptions` - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `addLeadingSlash` - IMPORTS → `isFunction` - IMPORTS → `isObject` - IMPORTS → `isString` - IMPORTS → `SocketModule` - IMPORTS → `MicroservicesModule` - IMPORTS → `-nestjs-microservices` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `TestingModule` — `packages/testing/testing-module.ts`:26 - `BaseWsInstance` — `packages/websockets/adapters/ws-adapter.ts`:8 # NestApplicationContext **Kind:** Class **Source:** [`packages/core/nest-application-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-application-context.ts#L40) **Part of:** [Core](subsystem-packages-core) `NestApplicationContext` provides a non-HTTP NestJS application runtime for resolving providers, selecting modules, and managing dependency injection. It underpins application contexts created through `NestFactory.createApplicationContext()`, allowing scripts, CLI tools, workers, and tests to access Nest-managed services without starting a web server. **Extends:** `AbstractInstanceResolver` **Implements:** `INestApplicationContext` ## Methods | Method | Signature | Returns | |---|---|---| | `selectContextModule` | `selectContextModule()` | `void` | | `select` | `select(moduleType: Type | DynamicModule, selectOptions: SelectOptions)` | `INestApplicationContext` | | `get` | `get(typeOrToken: Type | Function | string | symbol)` | `TResult` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: { strict?: boolean; each?: undefined | false; })` | `TResult` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: { strict?: boolean; each: true; })` | `Array` | | `get` | `get(typeOrToken: Type | Abstract | string | symbol, options: GetOrResolveOptions)` | `TResult | Array` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol)` | `Promise` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number; })` | `Promise` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number; }, options: { strict?: boolean; each?: undefined | false; })` | `Promise` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number; }, options: { strict?: boolean; each: true; })` | `Promise>` | | `resolve` | `resolve(typeOrToken: Type | Abstract | string | symbol, contextId: undefined, options: GetOrResolveOptions)` | `Promise>` | | `registerRequestByContextId` | `registerRequestByContextId(request: T, contextId: ContextId)` | `void` | | `init` | `init()` | `Promise` | | `close` | `close(signal: string)` | `Promise` | | `useLogger` | `useLogger(logger: LoggerService | LogLevel[] | false)` | `void` | | `flushLogs` | `flushLogs()` | `void` | | `flushLogsOnOverride` | `flushLogsOnOverride()` | `void` | | `enableShutdownHooks` | `enableShutdownHooks(signals: (ShutdownSignal | string)[], options: ShutdownHooksOptions)` | `this` | | `dispose` | `dispose()` | `Promise` | | `listenToShutdownSignals` | `listenToShutdownSignals(signals: string[], options: ShutdownHooksOptions)` | `void` | | `unsubscribeFromProcessSignals` | `unsubscribeFromProcessSignals()` | `void` | | `callInitHook` | `callInitHook()` | `Promise` | | `callDestroyHook` | `callDestroyHook()` | `Promise` | | `callBootstrapHook` | `callBootstrapHook()` | `Promise` | | `callShutdownHook` | `callShutdownHook(signal: string)` | `Promise` | | `callBeforeShutdownHook` | `callBeforeShutdownHook(signal: string)` | `Promise` | | `assertNotInPreviewMode` | `assertNotInPreviewMode(methodName: string)` | `void` | ## Properties | Property | Type | |---|---| | `isInitialized` | `any` | | `injector` | `Injector` | | `logger` | `any` | ## Where it refuses work - `NestApplicationContext` stops the work with `UnknownModuleException` when `!selectedModule`. - `NestApplicationContext` stops the work with an early return when `this.isInitialized`. - `NestApplicationContext` stops the work with an early return when `receivedSignal`. - `NestApplicationContext` stops the work with an early return when `!this.shutdownCleanupRef`. - `NestApplicationContext` stops the work with an early return when `this._moduleRefsForHooksByDistance`. ## When something fails - `NestApplicationContext` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR A[NestFactory.createApplicationContext] --> B[NestApplicationContext] B --> C[Module Container] C --> D[Root Module] C --> E[Feature Modules] B --> F[get Provider] B --> G[resolve Scoped Provider] B --> H[select Module Context] H --> I[get Provider from Module] ``` ## Usage ```ts import { Injectable, Module } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; @Injectable() class ReportService { generate() { return 'Report generated'; } } @Module({ providers: [ReportService], exports: [ReportService], }) class ReportsModule {} @Module({ imports: [ReportsModule], }) class AppModule {} async function bootstrap() { const app = await NestFactory.createApplicationContext(AppModule); // Resolve a singleton provider from the application context. const reports = app.get(ReportService); console.log(reports.generate()); // Select a module before resolving providers from its module scope. const reportsContext = app.select(ReportsModule); const scopedReports = reportsContext.get(ReportService); await app.close(); } bootstrap(); ``` ## AI Coding Instructions - Use `get()` for singleton or static-scope providers; use `resolve()` when working with request-scoped or transient providers. - Call `select(ModuleClass)` before retrieving a provider when module-specific lookup or strict module boundaries are required. - Prefer injection tokens or provider classes consistently; ensure queried providers are registered and exported when accessed across module boundaries. - Always close application contexts created for scripts, tests, or workers with `await app.close()` to release lifecycle resources. - Do not instantiate `NestApplicationContext` directly in application code; create it through `NestFactory.createApplicationContext()`. ## How it works `NestApplicationContext` is a public class that extends `AbstractInstanceResolver` and implements `INestApplicationContext`. It represents an application context backed by a `NestContainer`, with an optionally selected module and a module-navigation scope. [packages/core/nest-application-context.ts:40-46] [packages/core/nest-application-context.ts:68-81] The constructor stores the container and options, creates an `Injector`, obtains the container’s `ModuleCompiler`, and logs a preview-mode warning when `appOptions.preview` is true. [packages/core/nest-application-context.ts:68-81] Its instance-link registry is created lazily from the container on the first lookup. [packages/core/nest-application-context.ts:61-66] ## Relationships - IMPORTS → `INestApplicationContext` - IMPORTS → `Logger` - IMPORTS → `LoggerService` - IMPORTS → `LogLevel` - IMPORTS → `ShutdownSignal` - IMPORTS → `Abstract` - IMPORTS → `DynamicModule` - IMPORTS → `GetOrResolveOptions` - IMPORTS → `SelectOptions` - IMPORTS → `ShutdownHooksOptions` - IMPORTS → `Type` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `isEmpty` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `TestingModule` — `packages/testing/testing-module.ts`:26 # DependenciesScanner **Kind:** Class **Source:** [`packages/core/scanner.ts`](https://github.com/nestjs/nest/blob/master/packages/core/scanner.ts#L75) **Part of:** [Core](subsystem-packages-core) `DependenciesScanner` discovers an application’s module tree and reflects Nest metadata for imports, providers, controllers, exports, and dynamic module configuration. It populates the `NestContainer` during application initialization so the dependency injection system can resolve modules and their registered components. ## Methods | Method | Signature | Returns | |---|---|---| | `scan` | `scan(module: Type, options: { overrides?: ModuleOverride[] })` | `void` | | `scanForModules` | `scanForModules({ moduleDefinition, lazy, scope = [], ctxRegistry = [], overrides = [], }: ModulesScanParameters)` | `Promise` | | `insertModule` | `insertModule(moduleDefinition: any, scope: Type[])` | `Promise< | { moduleRef: Module; inserted: boolean; } | undefined >` | | `scanModulesForDependencies` | `scanModulesForDependencies(modules: Map)` | `void` | | `reflectImports` | `reflectImports(module: Type, token: string, context: string)` | `void` | | `reflectProviders` | `reflectProviders(module: Type, token: string)` | `void` | | `reflectControllers` | `reflectControllers(module: Type, token: string)` | `void` | | `reflectDynamicMetadata` | `reflectDynamicMetadata(cls: Type, token: string)` | `void` | | `reflectExports` | `reflectExports(module: Type, token: string)` | `void` | | `reflectInjectables` | `reflectInjectables(component: Type, token: string, metadataKey: string)` | `void` | | `reflectParamInjectables` | `reflectParamInjectables(component: Type, token: string, metadataKey: string)` | `void` | | `reflectKeyMetadata` | `reflectKeyMetadata(component: Type, key: string, methodKey: string)` | `{ methodKey: string; metadata: any } | undefined` | | `calculateModulesDistance` | `calculateModulesDistance()` | `void` | | `insertImport` | `insertImport(related: any, token: string, context: string)` | `void` | | `isCustomProvider` | `isCustomProvider(provider: Provider)` | `provider is | ClassProvider | ValueProvider | FactoryProvider | ExistingProvider` | | `insertProvider` | `insertProvider(provider: Provider, token: string)` | `void` | | `insertInjectable` | `insertInjectable(injectable: Type | object, token: string, host: Type, subtype: EnhancerSubtype, methodKey: string)` | `void` | | `insertExportedProviderOrModule` | `insertExportedProviderOrModule(toExport: ForwardReference | DynamicModule | Type, token: string)` | `void` | | `insertController` | `insertController(controller: Type, token: string)` | `void` | | `reflectMetadata` | `reflectMetadata(metadataKey: string, metatype: Type)` | `T[]` | | `registerCoreModule` | `registerCoreModule(overrides: ModuleOverride[])` | `void` | | `addScopedEnhancersMetadata` | `addScopedEnhancersMetadata()` | `void` | | `applyApplicationProviders` | `applyApplicationProviders()` | `void` | | `getApplyProvidersMap` | `getApplyProvidersMap()` | `{ [type: string]: Function }` | | `getApplyRequestProvidersMap` | `getApplyRequestProvidersMap()` | `{ [type: string]: Function }` | | `isDynamicModule` | `isDynamicModule(module: Type | DynamicModule)` | `module is DynamicModule` | ## Where it refuses work - `DependenciesScanner` stops the work with `UndefinedModuleException` when `innerModule === undefined`. - `DependenciesScanner` stops the work with `InvalidModuleException` when `!innerModule`. - `DependenciesScanner` stops the work with `InvalidClassModuleException` when `this.isInjectable(moduleToAdd)`. - `DependenciesScanner` stops the work with `InvalidClassModuleException` when `this.isController(moduleToAdd)`. - `DependenciesScanner` stops the work with `InvalidClassModuleException` when `this.isExceptionFilter(moduleToAdd)`. - `DependenciesScanner` stops the work with `CircularDependencyException` when `isUndefined(related)`. ## Diagram ```mermaid graph LR A[Root Module] --> B[DependenciesScanner.scan] B --> C[scanForModules] C --> D[insertModule] D --> E[NestContainer] B --> F[scanModulesForDependencies] F --> G[reflectImports] F --> H[reflectProviders] F --> I[reflectControllers] F --> J[reflectDynamicMetadata] F --> K[reflectExports] F --> L[reflectInjectables] G --> E H --> E I --> E J --> E K --> E L --> E ``` ## Usage ```ts import { DependenciesScanner } from '@nestjs/core/scanner'; import { NestContainer } from '@nestjs/core/injector/container'; import { MetadataScanner } from '@nestjs/core/metadata-scanner'; import { GraphInspector } from '@nestjs/core/inspector/graph-inspector'; import { ApplicationConfig } from '@nestjs/core/application-config'; import { AppModule } from './app.module'; // These dependencies are normally created and managed by Nest's core bootstrap flow. declare const container: NestContainer; declare const metadataScanner: MetadataScanner; declare const graphInspector: GraphInspector; declare const applicationConfig: ApplicationConfig; async function scanApplicationModules() { const scanner = new DependenciesScanner( container, metadataScanner, graphInspector, applicationConfig, ); await scanner.scan(AppModule); // The container now includes discovered modules, providers, and controllers. } ``` ## AI Coding Instructions - Treat `DependenciesScanner` as framework bootstrap infrastructure; application code should normally rely on `NestFactory` rather than instantiate it directly. - Preserve the scanning order: register modules before reflecting imports, providers, controllers, exports, and injectable metadata. - When adding metadata reflection behavior, ensure discovered components are registered through `NestContainer` so dependency resolution remains consistent. - Account for dynamic modules and module overrides when changing `scanForModules()` or `insertModule()`. - Avoid duplicate module registration; use the `inserted` result from `insertModule()` when subsequent work should only run for newly added modules. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `Provider` - IMPORTS → `CATCH_WATERMARK` - IMPORTS → `CONTROLLER_WATERMARK` - IMPORTS → `ENHANCER_KEY_TO_SUBTYPE_MAP` - IMPORTS → `EXCEPTION_FILTERS_METADATA` - IMPORTS → `EnhancerSubtype` - IMPORTS → `GUARDS_METADATA` - IMPORTS → `INJECTABLE_WATERMARK` - IMPORTS → `INTERCEPTORS_METADATA` - IMPORTS → `MODULE_METADATA` - IMPORTS → `PIPES_METADATA` - IMPORTS → `ROUTE_ARGS_METADATA` - IMPORTS → `CanActivate` - IMPORTS → `ClassProvider` - IMPORTS → `Controller` - IMPORTS → `ExceptionFilter` - IMPORTS → `ExistingProvider` - IMPORTS → `FactoryProvider` - IMPORTS → `Injectable` - IMPORTS → `InjectionToken` - IMPORTS → `NestInterceptor` - IMPORTS → `PipeTransform` - IMPORTS → `Scope` - IMPORTS → `Type` - IMPORTS → `ValueProvider` - IMPORTS → `isFunction` - IMPORTS → `isNil` - IMPORTS → `isUndefined` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # ExecutionContextHost **Kind:** Class **Source:** [`packages/core/helpers/execution-context-host.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/execution-context-host.ts#L10) **Part of:** [Core](subsystem-packages-core) `ExecutionContextHost` is the concrete implementation of Nest’s execution context abstraction. It stores the current invocation arguments, controller class, handler function, and transport type, then exposes transport-specific views for HTTP, RPC, and WebSocket execution. **Implements:** `ExecutionContext` ## Methods | Method | Signature | Returns | |---|---|---| | `setType` | `setType(type: TContext)` | `void` | | `getType` | `getType()` | `TContext` | | `getClass` | `getClass()` | `Type` | | `getHandler` | `getHandler()` | `Function` | | `getArgs` | `getArgs()` | `T` | | `getArgByIndex` | `getArgByIndex(index: number)` | `T` | | `switchToRpc` | `switchToRpc()` | `RpcArgumentsHost` | | `switchToHttp` | `switchToHttp()` | `HttpArgumentsHost` | | `switchToWs` | `switchToWs()` | `WsArgumentsHost` | ## Diagram ```mermaid graph LR A[Invocation Arguments] --> B[ExecutionContextHost] C[Controller Class] --> B D[Handler Method] --> B B --> E[getArgs / getArgByIndex] B --> F[getClass / getHandler] B --> G[setType / getType] B --> H[switchToHttp] B --> I[switchToRpc] B --> J[switchToWs] H --> K[HttpArgumentsHost] I --> L[RpcArgumentsHost] J --> M[WsArgumentsHost] ``` ## Usage ```ts import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host'; class UsersController { findOne() { return { id: 1 }; } } const request = { params: { id: '1' } }; const response = {}; const next = () => undefined; const context = new ExecutionContextHost( [request, response, next], UsersController, UsersController.prototype.findOne, ); context.setType('http'); const http = context.switchToHttp(); console.log(context.getType()); // "http" console.log(context.getClass()); // UsersController console.log(context.getHandler()); // findOne console.log(http.getRequest().params.id); // "1" ``` ## AI Coding Instructions - Preserve argument ordering when creating a context: HTTP uses `[request, response, next]`, while RPC and WebSocket adapters use transport-specific argument positions. - Call `setType()` when manually constructing a host so guards, interceptors, and metadata consumers can identify the active transport. - Use `switchToHttp()`, `switchToRpc()`, or `switchToWs()` instead of directly indexing arguments when writing transport-aware integrations. - Treat `getClass()` and `getHandler()` as metadata lookup targets for decorators, reflection, guards, and interceptors. - Avoid reusing one `ExecutionContextHost` instance across unrelated requests or message handlers. ## How it works `ExecutionContextHost` is a concrete `ExecutionContext` implementation that stores a handler argument array, an optional class reference, an optional handler reference, and a mutable context-type string. Its initial context type is `'http'`. [packages/core/helpers/execution-context-host.ts:10-17] - Its constructor accepts `args`, `constructorRef`, and `handler`; the latter two default to `null`. [packages/core/helpers/execution-context-host.ts:13-17] - `getArgs()` returns the stored argument array, and `getArgByIndex(index)` reads the element at that index. [packages/core/helpers/execution-context-host.ts:35-41] - `getClass()` returns the stored class reference and `getHandler()` returns the stored handler reference. Both use TypeScript non-null assertions, although their constructor values may be `null` when omitted. [packages/core/helpers/execution-context-host.ts:13-17] [packages/core/helpers/execution-context-host.ts:27-33] - `setType(type)` replaces the stored context type only when `type` is truthy; a falsy value leaves the existing type unchanged. `getType()` returns the stored value. [packages/core/helpers/execution-context-host.ts:19-25] - `switchToRpc()` assigns `getData()` and `getContext()` methods onto the host itself and returns that same object; those methods read argument indexes `0` and `1`, respectively. [packages/core/helpers/execution-context-host.ts:43-48] - `switchToHttp()` assigns `getRequest()`, `getResponse()`, and `getNext()` onto the same host and maps them to argument indexes `0`, `1`, and `2`. [packages/core/helpers/execution-context-host.ts:50-56] - `switchToWs()` assigns `getClient()` and `getData()` onto the same host for argument indexes `0` and `1`; `getPattern()` reads the final element of the current argument array. [packages/core/helpers/execution-context-host.ts:58-64] - The switch methods use `Object.assign(this, ...)`; therefore, each call has the side effect of adding or replacing those accessor methods on the existing instance rather than creating a separate adapter object. [packages/core/helpers/execution-context-host.ts:43-64] - The class contains no explicit runtime validation, bounds checks, or thrown errors for the argument array, indexes, class reference, handler reference, or context type. [packages/core/helpers/execution-context-host.ts:13-64] Core code creates this host for guards with the invocation arguments, `instance.constructor`, and callback, then sets the optional guard context type before passing the host to each guard’s `canActivate`. [packages/core/guards/guards-consumer.ts:18-22] [packages/core/guards/guards-consumer.ts:37-46] Shared context helpers also construct it from invocation arguments and optionally set its type for custom parameter factories. [packages/core/helpers/context-utils.ts:77-85] [packages/core/helpers/context-utils.ts:87-97] ## Relationships - IMPORTS → `ExecutionContext` - IMPORTS → `Type` - IMPORTS → `ContextType` - IMPORTS → `HttpArgumentsHost` - IMPORTS → `RpcArgumentsHost` - IMPORTS → `WsArgumentsHost` ## Used by 5 references from 5 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (5) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `RpcProxy` — `packages/microservices/context/rpc-proxy.ts`:6 - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `WsProxy` — `packages/websockets/context/ws-proxy.ts`:6 # MetadataScanner **Kind:** Class **Source:** [`packages/core/metadata-scanner.ts`](https://github.com/nestjs/nest/blob/master/packages/core/metadata-scanner.ts#L8) **Part of:** [Core](subsystem-packages-core) `MetadataScanner` inspects a class prototype and its inheritance chain to discover callable method names. It is used by the framework to scan providers, controllers, and other instances for methods that may carry metadata or require registration. ## Methods | Method | Signature | Returns | |---|---|---| | `scanFromPrototype` | `scanFromPrototype(instance: T, prototype: object | null, callback: (name: string) => R)` | `R[]` | | `getAllFilteredMethodNames` | `getAllFilteredMethodNames(prototype: object)` | `IterableIterator` | | `getAllMethodNames` | `getAllMethodNames(prototype: object | null)` | `string[]` | ## Where it refuses work - `MetadataScanner` stops the work with an early return when `!prototype`, in 2 places. - `MetadataScanner` stops the work with an early return when `this.cachedScannedPrototypes.has(prototype)`. ## Diagram ```mermaid graph LR A[Class Instance] --> B[Prototype] B --> C[MetadataScanner] C --> D[getAllFilteredMethodNames] D --> E[Inherited Method Names] E --> F[scanFromPrototype Callback] F --> G[Collected Results] ``` ## Usage ```ts import { MetadataScanner } from '@nestjs/core/metadata-scanner'; const ROUTE_METADATA = 'custom:route'; class UserController { @Reflect.metadata(ROUTE_METADATA, '/users') findAll() { return []; } findOne() { return {}; } } const controller = new UserController(); const scanner = new MetadataScanner(); const routes = scanner.scanFromPrototype( controller, Object.getPrototypeOf(controller), (methodName) => { const handler = controller[methodName]; const path = Reflect.getMetadata(ROUTE_METADATA, handler); return path ? { methodName, path } : undefined; }, ).filter(Boolean); console.log(routes); // [{ methodName: 'findAll', path: '/users' }] ``` ## AI Coding Instructions - Pass the instance and its prototype to `scanFromPrototype()` so inherited methods can be discovered correctly. - Use the scan callback to read method-level metadata and transform discovered methods into framework-specific definitions. - Do not rely on getters or setters being returned; the scanner is intended for callable prototype methods. - Prefer `scanFromPrototype()` when processing methods, and use `getAllMethodNames()` only when raw method names are needed. - Avoid scanning the same prototype repeatedly in custom integrations; the scanner caches discovered prototype method names. ## Relationships - IMPORTS → `Injectable` - IMPORTS → `isConstructor` - IMPORTS → `isFunction` - IMPORTS → `isNil` ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `WebhooksExplorer` — `integration/discovery/src/webhooks.explorer.ts`:5 - `ClientProperties` — `packages/microservices/listener-metadata-explorer.ts`:16 - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `Test` — `packages/testing/test.ts`:8 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 - `MessageMappingProperties` — `packages/websockets/gateway-metadata-explorer.ts`:15 - `WebSocketsController` — `packages/websockets/web-sockets-controller.ts`:29 # PipesContextCreator **Kind:** Class **Source:** [`packages/core/pipes/pipes-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/pipes/pipes-context-creator.ts#L11) **Part of:** [Core](subsystem-packages-core) `PipesContextCreator` is a framework-level base class that resolves pipe metadata into executable `PipeTransform` instances for a handler or controller. It combines locally declared pipes with globally configured pipes, resolves request-scoped instances through the module container, and tracks the active module context during resolution. **Extends:** `ContextCreator` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (...args: unknown[]) => unknown, moduleKey: string, contextId: undefined, inquirerId: string)` | `PipeTransform[]` | | `createConcreteContext` | `createConcreteContext(metadata: T, contextId: undefined, inquirerId: string)` | `R` | | `getPipeInstance` | `getPipeInstance(pipe: Function | PipeTransform, contextId: undefined, inquirerId: string)` | `PipeTransform | null` | | `getInstanceByMetatype` | `getInstanceByMetatype(metatype: Type)` | `InstanceWrapper | undefined` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: undefined, inquirerId: string)` | `T` | | `setModuleContext` | `setModuleContext(context: string)` | `void` | ## Where it refuses work - `PipesContextCreator` stops the work with an early return when `isEmpty(metadata)`. - `PipesContextCreator` stops the work with an early return when `isObject`. - `PipesContextCreator` stops the work with an early return when `!instanceWrapper`. - `PipesContextCreator` stops the work with an early return when `!this.moduleContext`. - `PipesContextCreator` stops the work with an early return when `!moduleRef`. - `PipesContextCreator` stops the work with an early return when `!this.config`. ## Diagram ```mermaid graph LR A[Controller / Handler Metadata] --> B[PipesContextCreator.create] B --> C[Local Pipe Metadata] B --> D[Global Pipe Metadata] C --> E[createConcreteContext] D --> E E --> F[getPipeInstance] F --> G[Module Container] G --> H[InstanceWrapper] H --> I[PipeTransform instances] ``` ## Usage ```ts import { Injectable, PipeTransform } from '@nestjs/common'; import { PipesContextCreator } from '@nestjs/core/pipes/pipes-context-creator'; @Injectable() class TrimPipe implements PipeTransform { transform(value: unknown) { return typeof value === 'string' ? value.trim() : value; } } // PipesContextCreator is intended for framework adapters and internal // integrations. Concrete implementations provide container/config access. class CustomPipesContextCreator extends PipesContextCreator { protected pipesContainer = appContainer; protected config = applicationConfig; createConcreteContext(metadata: unknown[]): PipeTransform[] { return metadata .map(pipe => this.getPipeInstance(pipe)) .filter((pipe): pipe is PipeTransform => pipe !== null); } } const pipesCreator = new CustomPipesContextCreator(); // Resolve pipes declared on a handler within its owning module. const pipes = pipesCreator.create( UsersController, UsersController.prototype.create, 'UsersModule', ); // Example result: [TrimPipe instance, ...global pipes] const transformedValue = await pipes[0].transform(' Ada ', {}); ``` ## AI Coding Instructions - Treat `PipesContextCreator` as infrastructure code: extend it through a concrete context creator rather than instantiating it directly. - Always set or pass the correct module context before resolving metatype-based pipes; pipe providers are resolved from the active module’s injectable collection. - Support both pipe instances and pipe classes: existing objects with a `transform()` method should be reused, while classes should be resolved through the container. - Preserve request-scoped behavior by forwarding `contextId` and `inquirerId` when resolving pipe instances. - Include global pipe metadata when building a concrete pipe context, including request-scoped global pipes when the context is non-static. ## How it works **`PipesContextCreator`** is a `ContextCreator` subclass that builds arrays of `PipeTransform` instances from global configuration and pipe metadata attached to a controller class or handler callback. It stores a `NestContainer` and optional `ApplicationConfig`; the constructor performs no other work. [packages/core/pipes/pipes-context-creator.ts:11-19] - `create(instance, callback, moduleKey, contextId, inquirerId)` records `moduleKey` as its current module context, then delegates to the inherited `createContext` with the `PIPES_METADATA` key. [packages/core/pipes/pipes-context-creator.ts:21-35] - The inherited operation reads global metadata, metadata on `instance`’s prototype constructor, and metadata on `callback`; it converts each group through `createConcreteContext` and returns them in global, class, then method order. [packages/core/helpers/context-creator.ts:16-40] - `@UsePipes` writes pipe classes or instances into `PIPES_METADATA` on either the controller target or a method descriptor’s callback, which is the metadata consumed by `create`. [packages/common/decorators/core/use-pipes.decorator.ts:29-47] **Concrete-pipe resolution** - `createConcreteContext(metadata, contextId, inquirerId)` returns an empty array when `metadata` is empty or absent. [packages/core/pipes/pipes-context-creator.ts:38-45] - Otherwise, it discards falsy entries and entries that have neither a `name` nor `transform` property, resolves each remaining item with `getPipeInstance`, then retains only resolved values whose `transform` member exists and is a function. [packages/core/pipes/pipes-context-creator.ts:46-50] - `getPipeInstance` returns an input object directly when it has a truthy `transform` property. For a non-object pipe reference, it looks up an `InstanceWrapper` by metatype; if none is found, it returns `null`. [packages/core/pipes/pipes-context-creator.ts:53-65] - For a found wrapper, it retrieves the instance for a context ID and optional inquirer ID, returning the host’s `instance`. Before lookup, the context ID is replaced by a parent context when the supplied context ID has `getParent`; the parent lookup receives the wrapper token and dependency-tree durability flag. [packages/core/pipes/pipes-context-creator.ts:66-70] [packages/core/helpers/context-creator.ts:55-65] - Metatype lookup requires a current module context and a matching module in `container.getModules()`; missing context or module returns `undefined`. A matching module is queried through `moduleRef.injectables.get(metatype)`. [packages/core/pipes/pipes-context-creator.ts:73-85] - `setModuleContext(context)` changes the stored module context used by later class-based pipe lookups. [packages/core/pipes/pipes-context-creator.ts:114-116] **Global pipes and scoped contexts** - Without an `ApplicationConfig`, `getGlobalMetadata` returns an empty array. [packages/core/pipes/pipes-context-creator.ts:87-93] - With configuration, a static context with no inquirer ID returns the configured global pipe array directly. [packages/core/pipes/pipes-context-creator.ts:94-97] - For another context or when an inquirer ID is present, it obtains configured request-scoped global pipe wrappers, gets each wrapper’s contextual instance with the adjusted context ID and inquirer ID, drops missing hosts, and appends their instances after the ordinary global pipes. [packages/core/pipes/pipes-context-creator.ts:98-111] - `ApplicationConfig` stores ordinary global pipes separately from global request-pipe wrappers; its accessors return those respective arrays. [packages/core/application-config.ts:16-21] [packages/core/application-config.ts:76-78] [packages/core/application-config.ts:114-120] **Execution boundary** - This class assembles pipe instances; it does not call `transform`. `PipesConsumer.applyPipes` invokes each selected pipe’s `transform` in array order, passing the prior result and argument metadata. [packages/core/pipes/pipes-consumer.ts:19-29] - In the external-context path, `ExternalContextCreator` constructs this class with the container and application config, calls `create` while creating a handler context, and combines handler-level pipes with parameter-specific pipes before passing them to the pipe consumer. [packages/core/helpers/external-context-creator.ts:56-88] [packages/core/helpers/external-context-creator.ts:109-120] [packages/core/helpers/external-context-creator.ts:292-329] - For parameter-specific metadata in that path, `exchangeKeysForValues` first sets this creator’s module context and then calls `createConcreteContext` for each parameter’s pipe collection. [packages/core/helpers/external-context-creator.ts:255-289] **Visible validation and failure behavior** - The class has no explicit `throw` statements or error translation. Its visible rejection behavior is omission: empty metadata yields no pipes, unresolved class references yield `null` and are filtered out, and values without a callable `transform` are filtered out. [packages/core/pipes/pipes-context-creator.ts:43-50] [packages/core/pipes/pipes-context-creator.ts:62-65] - Its visible mutable side effect is assignment of `moduleContext` by `create` or `setModuleContext`. [packages/core/pipes/pipes-context-creator.ts:28] [packages/core/pipes/pipes-context-creator.ts:114-116] ## Relationships - IMPORTS → `PIPES_METADATA` - IMPORTS → `Controller` - IMPORTS → `PipeTransform` - IMPORTS → `Type` - IMPORTS → `isEmpty` - IMPORTS → `isFunction` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # ContextUtils **Kind:** Class **Source:** [`packages/core/helpers/context-utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-utils.ts#L23) **Part of:** [Core](subsystem-packages-core) `ContextUtils` centralizes reflection and execution-context helpers used when NestJS resolves handler parameters. It reads callback metadata, aligns parameter metadata with reflected types, builds argument placeholders, and creates `ExecutionContextHost` instances for custom parameter factories. ## Methods | Method | Signature | Returns | |---|---|---| | `mapParamType` | `mapParamType(key: string)` | `string` | | `reflectCallbackParamtypes` | `reflectCallbackParamtypes(instance: Controller, methodName: string)` | `any[]` | | `reflectCallbackMetadata` | `reflectCallbackMetadata(instance: Controller, methodName: string, metadataKey: string)` | `T` | | `reflectPassthrough` | `reflectPassthrough(instance: Controller, methodName: string)` | `boolean` | | `getArgumentsLength` | `getArgumentsLength(keys: string[], metadata: T)` | `number` | | `createNullArray` | `createNullArray(length: number)` | `any[]` | | `mergeParamsMetatypes` | `mergeParamsMetatypes(paramsProperties: ParamProperties[], paramtypes: any[])` | `(ParamProperties & { metatype?: any })[]` | | `getCustomFactory` | `getCustomFactory(factory: (...args: unknown[]) => void, data: unknown, contextFactory: (args: unknown[]) => ExecutionContextHost)` | `(...args: unknown[]) => unknown` | | `getContextFactory` | `getContextFactory(contextType: TContext, instance: object, callback: Function)` | `(args: unknown[]) => ExecutionContextHost` | ## Where it refuses work - `ContextUtils` stops the work with an early return when `!paramtypes`. ## Diagram ```mermaid graph LR Handler[Controller/Resolver Handler] --> Reflection[Reflect Metadata] Reflection --> ContextUtils ContextUtils --> ParamTypes[Parameter Metatypes] ContextUtils --> Arguments[Argument Array] ContextUtils --> ContextFactory[ExecutionContextHost Factory] ContextFactory --> CustomFactory[Custom Parameter Factory] Arguments --> Handler CustomFactory --> Handler ``` ## Usage ```ts import { ContextUtils } from '@nestjs/core/helpers/context-utils'; import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host'; class UsersController { findOne(id: string) { return { id }; } } const contextUtils = new ContextUtils(); const controller = new UsersController(); // Read TypeScript design:paramtypes metadata for the handler. const paramTypes = contextUtils.reflectCallbackParamtypes( controller, 'findOne', ); // Create an execution-context factory for custom parameter decorators. const createContext = contextUtils.getContextFactory('http'); const args = [{ params: { id: '42' } }, {}, () => undefined]; const context: ExecutionContextHost = createContext(args); console.log(paramTypes); // Example: [String] console.log(context.getType()); // "http" ``` ## AI Coding Instructions - Use `reflectCallbackParamtypes()` and `reflectCallbackMetadata()` instead of reading `Reflect` metadata directly in parameter-resolution code. - Keep parameter indexes aligned when using `getArgumentsLength()`, `createNullArray()`, and `mergeParamsMetatypes()`. - Create contexts through `getContextFactory()` so the resulting `ExecutionContextHost` has the correct transport type. - Wrap custom parameter decorators with `getCustomFactory()` to ensure they receive both decorator data and the generated execution context. - Treat missing reflection metadata as valid; handlers may not have emitted design-time metadata. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `MessageMappingProperties` — `packages/websockets/gateway-metadata-explorer.ts`:15 # InterceptorsContextCreator **Kind:** Class **Source:** [`packages/core/interceptors/interceptors-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/interceptors/interceptors-context-creator.ts#L11) **Part of:** [Core](subsystem-packages-core) `InterceptorsContextCreator` resolves the interceptors that apply to a Nest handler, including global, controller-level, and method-level metadata. It converts interceptor classes or instances into concrete `NestInterceptor` instances using the current module and request context. **Extends:** `ContextCreator` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (...args: unknown[]) => unknown, module: string, contextId: undefined, inquirerId: string)` | `NestInterceptor[]` | | `createConcreteContext` | `createConcreteContext(metadata: T, contextId: undefined, inquirerId: string)` | `R` | | `getInterceptorInstance` | `getInterceptorInstance(metatype: Function | NestInterceptor, contextId: undefined, inquirerId: string)` | `NestInterceptor | null` | | `getInstanceByMetatype` | `getInstanceByMetatype(metatype: Type)` | `InstanceWrapper | undefined` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: undefined, inquirerId: string)` | `T` | ## Where it refuses work - `InterceptorsContextCreator` stops the work with an early return when `isEmpty(metadata)`. - `InterceptorsContextCreator` stops the work with an early return when `isObject`. - `InterceptorsContextCreator` stops the work with an early return when `!instanceWrapper`. - `InterceptorsContextCreator` stops the work with an early return when `!this.moduleContext`. - `InterceptorsContextCreator` stops the work with an early return when `!moduleRef`. - `InterceptorsContextCreator` stops the work with an early return when `!this.config`. ## Diagram ```mermaid graph LR A[Global Interceptors] --> D[InterceptorsContextCreator.create] B[Controller @UseInterceptors] --> D C[Handler @UseInterceptors] --> D D --> E[createConcreteContext] E --> F[getInterceptorInstance] F --> G[Module Injectable Wrapper] G --> H[NestInterceptor[]] ``` ## Usage ```ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class LoggingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable { const handlerName = context.getHandler().name; console.log(`Before ${handlerName}`); return next.handle().pipe( tap(() => console.log(`After ${handlerName}`)), ); } } @UseInterceptors(LoggingInterceptor) export class UsersController { findAll() { return []; } } ``` Nest internally uses `InterceptorsContextCreator` to collect `LoggingInterceptor` metadata, resolve its injectable instance, and execute it around the controller handler. ## AI Coding Instructions - Preserve interceptor resolution order: global interceptors should be applied before controller- and handler-scoped interceptors. - Support both interceptor instances (`{ intercept() {} }`) and interceptor classes resolved through the module injector. - Return only valid `NestInterceptor` instances; unresolved providers should be filtered out rather than causing downstream failures. - Respect request-scoped providers by resolving instances with the active `ContextId` and optional inquirer identifier. - When adding interceptor metadata, use Nest’s `@UseInterceptors()` integration rather than directly constructing this internal context creator. ## Relationships - IMPORTS → `INTERCEPTORS_METADATA` - IMPORTS → `Controller` - IMPORTS → `NestInterceptor` - IMPORTS → `Type` - IMPORTS → `isEmpty` - IMPORTS → `isFunction` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # GuardsContextCreator **Kind:** Class **Source:** [`packages/core/guards/guards-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/guards/guards-context-creator.ts#L12) **Part of:** [Core](subsystem-packages-core) `GuardsContextCreator` resolves the guards that apply to a controller handler, including method/class metadata and globally registered guards. It converts guard classes or instances into executable `CanActivate` instances while respecting module scope, request context, and dependency injection. **Extends:** `ContextCreator` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (...args: unknown[]) => unknown, module: string, contextId: undefined, inquirerId: string)` | `CanActivate[]` | | `createConcreteContext` | `createConcreteContext(metadata: T, contextId: undefined, inquirerId: string)` | `R` | | `getGuardInstance` | `getGuardInstance(metatype: Function | CanActivate, contextId: undefined, inquirerId: string)` | `CanActivate | null` | | `getInstanceByMetatype` | `getInstanceByMetatype(metatype: Type)` | `InstanceWrapper | undefined` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: undefined, inquirerId: string)` | `T` | ## Where it refuses work - `GuardsContextCreator` stops the work with an early return when `isEmpty(metadata)`. - `GuardsContextCreator` stops the work with an early return when `isObject`. - `GuardsContextCreator` stops the work with an early return when `!instanceWrapper`. - `GuardsContextCreator` stops the work with an early return when `!this.moduleContext`. - `GuardsContextCreator` stops the work with an early return when `!moduleRef`. - `GuardsContextCreator` stops the work with an early return when `!this.config`. ## Diagram ```mermaid graph LR A[Controller handler] --> B[GuardsContextCreator.create] B --> C[Read @UseGuards metadata] B --> D[Read global guard metadata] C --> E[createConcreteContext] D --> E E --> F[getGuardInstance] F --> G[Resolve injectable from module container] G --> H[CanActivate[]] ``` ## Usage ```ts import { ApplicationConfig } from '@nestjs/core/application-config'; import { GuardsContextCreator } from '@nestjs/core/guards/guards-context-creator'; import { NestContainer } from '@nestjs/core/injector/container'; const container = new NestContainer(); const applicationConfig = new ApplicationConfig(); const guardsContextCreator = new GuardsContextCreator( container, applicationConfig, ); // `moduleToken` should identify the module that owns the controller. const guards = guardsContextCreator.create( usersController, usersController.findAll, moduleToken, ); for (const guard of guards) { const allowed = await guard.canActivate(executionContext); if (!allowed) { throw new Error('Request denied by guard'); } } ``` ## AI Coding Instructions - Use `create()` when resolving guards for a controller method; it combines handler, controller, and global guard metadata. - Ensure the supplied module token matches the module containing guard providers, or class-based guards cannot be resolved from the container. - Guard metadata may contain either guard instances or injectable guard classes; preserve support for both when extending resolution logic. - Pass the correct request `contextId` and `inquirerId` for request-scoped guards instead of always relying on the static context. - Treat this as core framework infrastructure; application code should normally configure guards with `@UseGuards()` or global guard registration rather than instantiate this class directly. ## Relationships - IMPORTS → `CanActivate` - IMPORTS → `GUARDS_METADATA` - IMPORTS → `Controller` - IMPORTS → `Type` - IMPORTS → `isEmpty` - IMPORTS → `isFunction` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # ModuleRef **Kind:** Class **Source:** [`packages/core/injector/module-ref.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/module-ref.ts#L26) **Part of:** [Core](subsystem-packages-core) `ModuleRef` provides programmatic access to providers registered in the current NestJS module. Use it to retrieve existing singleton providers with `get()`, resolve request- or transient-scoped providers with `resolve()`, or instantiate classes dynamically with dependency injection through `create()`. **Extends:** `AbstractInstanceResolver` ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(typeOrToken: Type | Function | string | symbol)` | `TResult` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: { strict?: boolean; each?: undefined | false; })` | `TResult` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: { strict?: boolean; each: true; })` | `Array` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: ModuleRefGetOrResolveOpts)` | `TResult | Array` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol)` | `Promise` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number })` | `Promise` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number }, options: { strict?: boolean; each?: undefined | false })` | `Promise` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number }, options: { strict?: boolean; each: true })` | `Promise>` | | `resolve` | `resolve(typeOrToken: Type | Function | string | symbol, contextId: { id: number }, options: ModuleRefGetOrResolveOpts)` | `Promise>` | | `create` | `create(type: Type, contextId: ContextId)` | `Promise` | | `introspect` | `introspect(token: Type | string | symbol)` | `IntrospectionResult` | | `registerRequestByContextId` | `registerRequestByContextId(request: T, contextId: ContextId)` | `void` | | `instantiateClass` | `instantiateClass(type: Type, moduleRef: Module, contextId: ContextId)` | `Promise` | ## Properties | Property | Type | |---|---| | `injector` | `Injector` | ## When something fails - `ModuleRef` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR Consumer[Service / Controller] --> ModuleRef ModuleRef -->|get()| Singleton[Registered singleton provider] ModuleRef -->|resolve()| Scoped[Request or transient provider instance] ModuleRef -->|create()| Dynamic[New dynamically created class] ModuleRef --> Container[Nest dependency injection container] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ModuleRef } from '@nestjs/core'; @Injectable() export class ReportsService { constructor(private readonly moduleRef: ModuleRef) {} async generateReport() { // Retrieve an existing singleton provider. const configService = this.moduleRef.get(ConfigService, { strict: false, }); // Create or retrieve a scoped provider instance. const reportContext = await this.moduleRef.resolve(ReportContextService); // Instantiate a class while allowing Nest to inject its dependencies. const exporter = await this.moduleRef.create(CsvReportExporter); return exporter.export({ timezone: configService.get('TIMEZONE'), context: reportContext, }); } } ``` ## AI Coding Instructions - Use `get()` for providers that are already registered and safe to access as singleton instances. - Use `resolve()` for request-scoped or transient providers; it may create a new instance for the current resolution context. - Pass `{ strict: false }` to `get()` only when intentionally searching providers outside the current module boundary. - Use `create()` when dynamically constructing a class that is not necessarily registered as a provider but still requires dependency injection. - Prefer constructor injection for known dependencies; use `ModuleRef` only when runtime or lazy resolution is required. ## How it works `ModuleRef` is an abstract DI-container reference type. Each `Module` registers a resolved instance under the `ModuleRef` token; that instance is created from a module-specific subclass returned by `createModuleReferenceType()` and is hosted by that module. [packages/core/injector/module.ts:161-179] The subclass closes over its host `Module`, so its lookup and resolution operations can apply that module’s ID and context. [packages/core/injector/module.ts:602-641] The abstract class stores the `NestContainer`, creates an `Injector` from the container’s preview, snapshot, and instance-decorator context options, and lazily builds an `InstanceLinksHost` from the container on first use. [packages/core/injector/module-ref.ts:26-47] `InstanceLinksHost` snapshots links for every module’s providers, injectables, and controllers when constructed. [packages/core/injector/instance-links-host.ts:17-22][packages/core/injector/instance-links-host.ts:55-68] # RouterExecutionContext **Kind:** Class **Source:** [`packages/core/router/router-execution-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-execution-context.ts#L62) **Part of:** [Core](subsystem-packages-core) `RouterExecutionContext` builds the runtime execution layer for a router handler. It reflects handler metadata such as status codes, redirects, templates, headers, SSE configuration, and parameter bindings, then resolves request values and applies supported pipes before invoking the handler. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (...args: any[]) => unknown, methodName: string, moduleKey: string, requestMethod: RequestMethod, contextId: undefined, inquirerId: string)` | `void` | | `getMetadata` | `getMetadata(instance: Controller, callback: (...args: any[]) => any, methodName: string, moduleKey: string, requestMethod: RequestMethod, contextType: TContext)` | `HandlerMetadata` | | `reflectRedirect` | `reflectRedirect(callback: (...args: unknown[]) => unknown)` | `RedirectResponse` | | `reflectHttpStatusCode` | `reflectHttpStatusCode(callback: (...args: unknown[]) => unknown)` | `number` | | `reflectRenderTemplate` | `reflectRenderTemplate(callback: (...args: unknown[]) => unknown)` | `string` | | `reflectResponseHeaders` | `reflectResponseHeaders(callback: (...args: unknown[]) => unknown)` | `CustomHeader[]` | | `reflectSse` | `reflectSse(callback: (...args: unknown[]) => unknown)` | `string` | | `exchangeKeysForValues` | `exchangeKeysForValues(keys: string[], metadata: Record, moduleContext: string, contextId: undefined, inquirerId: string, contextFactory: (args: unknown[]) => ExecutionContextHost)` | `ParamProperties[]` | | `getParamValue` | `getParamValue(value: T, { metatype, type, data, }: { metatype: unknown; type: RouteParamtypes; data: unknown }, pipes: PipeTransform[])` | `Promise` | | `isPipeable` | `isPipeable(type: number | string)` | `boolean` | | `createGuardsFn` | `createGuardsFn(guards: CanActivate[], instance: Controller, callback: (...args: any[]) => any, contextType: TContext)` | `((args: any[]) => Promise) | null` | | `createPipesFn` | `createPipesFn(pipes: PipeTransform[], paramsOptions: (ParamProperties & { metatype?: any })[])` | `void` | | `createHandleResponseFn` | `createHandleResponseFn(callback: (...args: unknown[]) => unknown, isResponseHandled: boolean, redirectResponse: RedirectResponse, httpStatusCode: number)` | `HandleResponseFn` | ## Where it refuses work - `RouterExecutionContext` stops the work with `ForbiddenException` when `!canActivate`. - `RouterExecutionContext` stops the work with an early return when `cacheMetadata`. - `RouterExecutionContext` stops the work with an early return when `!isEmpty(pipes)`. - `RouterExecutionContext` stops the work with an early return when `renderTemplate`. - `RouterExecutionContext` stops the work with an early return when `redirectResponse && isString(redirectResponse.url)`. - `RouterExecutionContext` stops the work with an early return when `isSseHandler`. ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[RouterExecutionContext] B --> C[getMetadata] C --> D[Reflect route metadata] D --> E[exchangeKeysForValues] E --> F[getParamValue] F --> G[Apply pipes when isPipeable] G --> H[Execute route handler] H --> I[Apply response metadata] I --> J[HTTP Response] ``` ## Usage ```ts import { RouterExecutionContext } from '@core/router/router-execution-context'; // The context is typically created by the router during route registration. // Its dependencies, handler, controller instance, and metadata are configured // before creating the request-time handler. const executionContext = new RouterExecutionContext( /* framework dependencies */ ); const handler = executionContext.create(); // Register the generated callback with the underlying HTTP router. router.get('/users/:id', handler); // Internally, the generated handler can: // - resolve @Param(), @Query(), @Body(), and other parameter values // - run supported parameter pipes // - invoke the controller method // - apply redirect, status, header, template, or SSE metadata ``` ## AI Coding Instructions - Keep route-handler execution logic inside `RouterExecutionContext`; router adapters should only register the callback returned by `create()`. - Use the `reflect*()` methods to read handler metadata instead of duplicating decorator or reflection lookups elsewhere. - Resolve request arguments through `exchangeKeysForValues()` and `getParamValue()` so parameter decorators and pipes follow the same execution path. - Check `isPipeable()` before applying transformation or validation pipes; not every resolved parameter value should be piped. - Preserve response metadata behavior for redirects, HTTP status codes, templates, custom headers, and SSE responses when changing handler execution flow. # RuntimeException **Kind:** Class **Source:** [`packages/core/errors/exceptions/runtime.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/runtime.exception.ts#L1) **Part of:** [Core](subsystem-packages-core) `RuntimeException` represents an error that occurs during application execution and can be propagated through the core error-handling flow. It provides a `what()` method for retrieving a human-readable description of the failure. Use it when an operation cannot continue because of an unexpected runtime condition. **Extends:** `Error` ## Methods | Method | Signature | Returns | |---|---|---| | `what` | `what()` | `void` | ## Diagram ```mermaid graph LR A[Application operation] --> B{Runtime failure?} B -- Yes --> C[RuntimeException] C --> D[what()] D --> E[Readable error description] B -- No --> F[Continue execution] ``` ## Usage ```ts import { RuntimeException } from '@your-package/core/errors/exceptions/runtime.exception'; function loadConfiguration(configPath?: string): void { if (!configPath) { throw new RuntimeException('Configuration path is required.'); } // Continue loading the configuration... } try { loadConfiguration(); } catch (error) { if (error instanceof RuntimeException) { console.error(error.what()); } else { throw error; } } ``` ## AI Coding Instructions - Throw `RuntimeException` for runtime conditions that prevent an operation from completing normally. - Provide actionable, human-readable error messages when constructing the exception. - Use `instanceof RuntimeException` when handling this specific error type. - Prefer `what()` when consuming the exception description to follow the established exception API. - Avoid using this exception for expected control flow; validate inputs and return normal results where appropriate. ## How it works `RuntimeException` is an exported subclass of the built-in `Error` class. [`packages/core/errors/exceptions/runtime.exception.ts:1`](packages/core/errors/exceptions/runtime.exception.ts#L1) It is also re-exported through the core exceptions barrel. [`packages/core/errors/exceptions/index.ts:2`](packages/core/errors/exceptions/index.ts#L2) - Its constructor accepts an optional `message` argument, defaulting to an empty string, and passes that value to `Error`; consequently, the inherited `message` is initialized from that argument. [`packages/core/errors/exceptions/runtime.exception.ts:2-4`](packages/core/errors/exceptions/runtime.exception.ts#L2-L4) - `what()` returns the instance’s current inherited `message` property. [`packages/core/errors/exceptions/runtime.exception.ts:6-8`](packages/core/errors/exceptions/runtime.exception.ts#L6-L8) - The class has no code-visible input validation, custom error fields, logging, or other side effects beyond calling the `Error` constructor. [`packages/core/errors/exceptions/runtime.exception.ts:1-8`](packages/core/errors/exceptions/runtime.exception.ts#L1-L8) In this repository, it is both a base class for more specific exceptions—including `CircularDependencyException`, `UnknownDependenciesException`, and `InvalidClassException`—and a directly thrown error type. [`packages/core/errors/exceptions/circular-dependency.exception.ts:1-3`](packages/core/errors/exceptions/circular-dependency.exception.ts#L1-L3) [`packages/core/errors/exceptions/unknown-dependencies.exception.ts:1-6`](packages/core/errors/exceptions/unknown-dependencies.exception.ts#L1-L6) [`packages/core/errors/exceptions/invalid-class.exception.ts:1-4`](packages/core/errors/exceptions/invalid-class.exception.ts#L1-L4) Direct call sites throw a message-less `RuntimeException` when an injector cannot find a token in its collection, when a module’s provider map lacks its metatype, or when middleware resolution cannot find an instance wrapper. [`packages/core/injector/injector.ts:171-174`](packages/core/injector/injector.ts#L171-L174) [`packages/core/injector/module.ts:141-144`](packages/core/injector/module.ts#L141-L144) [`packages/core/middleware/middleware-module.ts:203-206`](packages/core/middleware/middleware-module.ts#L203-L206) ## Used by 11 references from 11 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (11) - `RpcDecoratorMetadata` — `packages/microservices/errors/invalid-grpc-message-decorator.exception.ts`:3 - `InvalidGrpcPackageDefinitionMissingPackageDefinitionException` — `packages/microservices/errors/invalid-grpc-package-definition-missing-package-definition.exception.ts`:3 - `InvalidGrpcPackageDefinitionMutexException` — `packages/microservices/errors/invalid-grpc-package-definition-mutex.exception.ts`:3 - `InvalidGrpcPackageException` — `packages/microservices/errors/invalid-grpc-package.exception.ts`:6 - `InvalidGrpcServiceException` — `packages/microservices/errors/invalid-grpc-service.exception.ts`:6 - `InvalidKafkaClientTopicException` — `packages/microservices/errors/invalid-kafka-client-topic.exception.ts`:6 - `InvalidMessageException` — `packages/microservices/errors/invalid-message.exception.ts`:6 - `InvalidProtoDefinitionException` — `packages/microservices/errors/invalid-proto-definition.exception.ts`:6 …and 3 more. # DiscoveryService **Kind:** Class **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L49) **Part of:** [Core](subsystem-packages-core) `DiscoveryService` provides runtime access to registered NestJS modules, providers, and controllers. It also creates typed discoverable decorators and retrieves metadata associated with those decorators, enabling convention-based discovery patterns such as plugin registries or handler scanning. ## Methods | Method | Signature | Returns | |---|---|---| | `createDecorator` | `createDecorator()` | `DiscoverableDecorator` | | `getProviders` | `getProviders(options: DiscoveryOptions, modules: Module[])` | `InstanceWrapper[]` | | `getControllers` | `getControllers(options: DiscoveryOptions, modules: Module[])` | `InstanceWrapper[]` | | `getMetadataByDecorator` | `getMetadataByDecorator(decorator: T, instanceWrapper: InstanceWrapper, methodKey: string)` | `T extends DiscoverableDecorator ? R | undefined : T | undefined` | | `getModules` | `getModules(options: DiscoveryOptions)` | `Module[]` | ## Where it refuses work - `DiscoveryService` stops the work with an early return when `methodKey`. ## Diagram ```mermaid graph LR A[DiscoveryService] --> B[ModulesContainer] B --> C[Module] C --> D[Providers
InstanceWrapper] C --> E[Controllers
InstanceWrapper] A --> F[createDecorator] F --> G[DiscoverableDecorator] G --> H[Metadata on classes] A --> I[getMetadataByDecorator] I --> H ``` ## Usage ```ts import { Injectable, OnModuleInit } from '@nestjs/common'; import { DiscoveryService, InstanceWrapper, } from '@nestjs/core'; // Create a reusable decorator for classes that implement application jobs. export const JobHandler = DiscoveryService.createDecorator<{ queue: string; }>(); @JobHandler({ queue: 'emails' }) @Injectable() export class SendEmailJob { async execute() { // Send email work } } @Injectable() export class JobRegistry implements OnModuleInit { constructor(private readonly discoveryService: DiscoveryService) {} onModuleInit() { const providers = this.discoveryService.getProviders(); const jobHandlers = providers .map((provider: InstanceWrapper) => ({ provider, metadata: this.discoveryService.getMetadataByDecorator( JobHandler, provider, ), })) .filter(({ metadata }) => metadata !== undefined); for (const { provider, metadata } of jobHandlers) { console.log( `Registered ${provider.name} for the "${metadata.queue}" queue.`, ); } } } ``` ## AI Coding Instructions - Use `createDecorator()` to define typed metadata contracts for discoverable providers or controllers. - Call discovery methods after module initialization (for example, in `onModuleInit`) so the NestJS container has been populated. - Always handle `undefined` from `getMetadataByDecorator()`; not every discovered wrapper has the requested decorator. - Inspect `InstanceWrapper.metatype` or `InstanceWrapper.instance` carefully, since wrappers can represent aliases, factories, or unresolved providers. - Use `getProviders()`, `getControllers()`, and `getModules()` for framework integration and registry-building logic rather than maintaining duplicate manual registries. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `NonAppliedDecorator` — `integration/discovery/src/decorators/non-applied.decorator.ts`:9 - `Webhook` — `integration/discovery/src/decorators/webhook.decorators.ts`:3 - `WebhooksExplorer` — `integration/discovery/src/webhooks.explorer.ts`:5 # ExternalContextCreator **Kind:** Class **Source:** [`packages/core/helpers/external-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/external-context-creator.ts#L38) **Part of:** [Core](subsystem-packages-core) `ExternalContextCreator` builds executable handlers for framework-managed entry points outside the standard HTTP request pipeline. It resolves parameter metadata, guards, pipes, interceptors, and request-scoped providers, then wraps the target method in an external execution context. ## Methods | Method | Signature | Returns | |---|---|---| | `fromContainer` | `fromContainer(container: NestContainer)` | `ExternalContextCreator` | | `create` | `create(instance: Controller, callback: (...args: unknown[]) => unknown, methodName: string, metadataKey: string, paramsFactory: ParamsFactory, contextId: undefined, inquirerId: string, options: ExternalContextOptions, contextType: TContext)` | `void` | | `getMetadata` | `getMetadata(instance: Controller, methodName: string, metadataKey: string, paramsFactory: ParamsFactory, contextType: TContext)` | `ExternalHandlerMetadata` | | `getContextModuleKey` | `getContextModuleKey(moduleCtor: Function | undefined)` | `string` | | `exchangeKeysForValues` | `exchangeKeysForValues(keys: string[], metadata: TMetadata, moduleContext: string, paramsFactory: ParamsFactory, contextId: undefined, inquirerId: string, contextFactory: undefined)` | `ParamProperties[]` | | `createPipesFn` | `createPipesFn(pipes: PipeTransform[], paramsOptions: (ParamProperties & { metatype?: unknown })[])` | `void` | | `getParamValue` | `getParamValue(value: T, { metatype, type, data }: { metatype: any; type: any; data: any }, pipes: PipeTransform[])` | `Promise` | | `transformToResult` | `transformToResult(resultOrDeferred: any)` | `void` | | `createGuardsFn` | `createGuardsFn(guards: any[], instance: Controller, callback: (...args: any[]) => any, contextType: TContext)` | `Function | null` | | `registerRequestProvider` | `registerRequestProvider(request: T, contextId: ContextId)` | `void` | ## Where it refuses work - `ExternalContextCreator` stops the work with `ForbiddenException` when `!canActivate`. - `ExternalContextCreator` stops the work with an early return when `cacheMetadata`. - `ExternalContextCreator` stops the work with an early return when `!moduleCtor`. - `ExternalContextCreator` stops the work with an early return when `moduleRef.hasProvider(moduleCtor)`. - `ExternalContextCreator` stops the work with an early return when `isObservable(resultOrDeferred)`. ## Diagram ```mermaid graph LR A[DI Container] --> B[ExternalContextCreator.fromContainer] B --> C[ExternalContextCreator] D[Target Instance and Method] --> E[create] C --> E E --> F[Read Handler Metadata] F --> G[Resolve Parameters] G --> H[Run Guards] H --> I[Apply Pipes] I --> J[Execute Interceptors] J --> K[Invoke Target Method] K --> L[Transform Result] ``` ## Usage ```ts import { ExternalContextCreator } from '@nestjs/core/helpers/external-context-creator'; // `container` is the application's NestContainer instance. const contextCreator = ExternalContextCreator.fromContainer(container); class ReportService { async rebuild(): Promise<{ status: string }> { return { status: 'completed' }; } } const reportService = new ReportService(); const handler = contextCreator.create( reportService, reportService.rebuild, 'rebuild', ); // Executes the method through Nest's external context pipeline. const result = await handler(); console.log(result.status); // "completed" ``` ## AI Coding Instructions - Create instances through `ExternalContextCreator.fromContainer()` so guards, pipes, interceptors, and module references use the application container. - Pass the target instance, callback, and method name consistently to `create()`; the method name is used to retrieve handler metadata. - Preserve the execution order: resolve parameters first, then guards, pipes, interceptors, and finally the target callback. - Use `registerRequestProvider()` when creating request-scoped execution contexts; otherwise scoped dependencies may not resolve correctly. - Avoid invoking decorated handlers directly when framework behavior is required; use the created proxy to retain metadata-driven processing. # RouterResponseController **Kind:** Class **Source:** [`packages/core/router/router-response-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-response-controller.ts#L28) **Part of:** [Core](subsystem-packages-core) `RouterResponseController` centralizes how route handler results are converted into HTTP responses. It manages status codes, headers, redirects, rendered views, server-sent events, and final response application so router behavior remains consistent across handlers. ## Methods | Method | Signature | Returns | |---|---|---| | `apply` | `apply(result: TInput, response: TResponse, httpStatusCode: number)` | `void` | | `redirect` | `redirect(resultOrDeferred: TInput, response: TResponse, redirectResponse: RedirectResponse)` | `void` | | `render` | `render(resultOrDeferred: TInput, response: TResponse, template: string)` | `void` | | `transformToResult` | `transformToResult(resultOrDeferred: any)` | `void` | | `getStatusByMethod` | `getStatusByMethod(requestMethod: RequestMethod)` | `number` | | `setHeaders` | `setHeaders(response: TResponse, headers: CustomHeader[])` | `void` | | `setStatus` | `setStatus(response: TResponse, statusCode: number)` | `void` | | `sse` | `sse(result: TInput | Promise, response: TResponse, request: TRequest, options: { additionalHeaders?: AdditionalHeaders; statusCode?: number; })` | `void` | ## Where it refuses work - `RouterResponseController` stops the work with `ReferenceError` when `!isObservable(value)` — “You must return an Observable stream to use Server-Sent Events (SSE).”. - `RouterResponseController` stops the work with an early return when `settled`, in 4 places. - `RouterResponseController` stops the work with an early return when `isObservable(resultOrDeferred)`. - `RouterResponseController` stops the work with an early return when `response.writableEnded`. - `RouterResponseController` stops the work with an early return when `settled || closeRequested`. - `RouterResponseController` stops the work with an early return when `isObject(message)`. ## Diagram ```mermaid graph LR Handler[Route Handler] --> Controller[RouterResponseController] Controller --> Status[setStatus / getStatusByMethod] Controller --> Headers[setHeaders] Controller --> Result[transformToResult] Result --> Apply[apply] Controller --> Redirect[redirect] Controller --> Render[render] Controller --> SSE[sse] Apply --> Response[HTTP Response] Redirect --> Response Render --> Response SSE --> Response ``` ## Usage ```ts import { RouterResponseController } from '@your-package/core/router'; // The router typically creates and provides the controller to handler code. function createUser( responseController: RouterResponseController, user: { id: string; email: string }, ) { responseController.setStatus(201); responseController.setHeaders({ 'content-type': 'application/json', 'x-resource-created': 'user', }); return responseController.apply({ data: user, }); } // Other response patterns: // responseController.redirect('/sign-in'); // responseController.render('profile', { user }); // responseController.sse(eventStream); ``` ## AI Coding Instructions - Use `setStatus()` and `setHeaders()` before calling `apply()` so response metadata is finalized with the result. - Prefer `redirect()`, `render()`, and `sse()` for their dedicated response types instead of manually constructing equivalent raw HTTP responses. - Let `getStatusByMethod()` provide method-aware defaults when no explicit status code is required. - Do not write directly to the underlying HTTP response after `apply()`, `redirect()`, `render()`, or `sse()` has finalized it. - Keep route handlers focused on producing data; rely on `transformToResult()` and `apply()` to normalize handler output into router-compatible responses. ## How it works `RouterResponseController` is a router-layer class that applies a route handler’s result to an HTTP response through an injected `HttpServer` adapter. Its constructor stores that adapter, and `RouterExecutionContext` creates one instance from its application adapter. [`router-response-controller.ts:28-31`](packages/core/router/router-response-controller.ts#L28-L31) [`router-execution-context.ts:62-78`](packages/core/router/router-execution-context.ts#L62-L78) # InterceptorsConsumer **Kind:** Class **Source:** [`packages/core/interceptors/interceptors-consumer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/interceptors/interceptors-consumer.ts#L13) **Part of:** [Core](subsystem-packages-core) `InterceptorsConsumer` executes a chain of NestJS interceptors around a route handler or other framework callback. It creates an `ExecutionContextHost`, invokes interceptors in order, and defers execution of the final handler so synchronous values, promises, and observables can be handled consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(interceptors: NestInterceptor[], args: unknown[], instance: Controller, callback: (...args: unknown[]) => unknown, next: () => Promise, type: TContext)` | `Promise` | | `createContext` | `createContext(args: unknown[], instance: Controller, callback: (...args: unknown[]) => unknown)` | `ExecutionContextHost` | | `transformDeferred` | `transformDeferred(next: () => Promise)` | `Observable` | ## Where it refuses work - `InterceptorsConsumer` stops the work with an early return when `isEmpty(interceptors)`. - `InterceptorsConsumer` stops the work with an early return when `i >= interceptors.length`. ## Diagram ```mermaid graph LR A[InterceptorsConsumer.intercept] --> B[createContext] B --> C[ExecutionContextHost] A --> D{Interceptors available?} D -->|No| E[Invoke next handler] D -->|Yes| F[Invoke current interceptor] F --> G[CallHandler.handle] G --> H[Next interceptor] H --> I[transformDeferred] I --> J[Route handler / callback result] J --> K[Observable, Promise, or value] ``` ## Usage ```ts import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common'; import { map } from 'rxjs/operators'; class AddMetadataInterceptor implements NestInterceptor { intercept(_context: ExecutionContext, next: CallHandler) { return next.handle().pipe( map((result) => ({ data: result, processedBy: 'AddMetadataInterceptor', })), ); } } async function runInterceptors() { const consumer = new InterceptorsConsumer(); const result = await consumer.intercept( [new AddMetadataInterceptor()], [{ id: '42' }], {} as object, () => ({ id: '42', name: 'Ada' }), async () => ({ id: '42', name: 'Ada' }), 'http', ); return result; } ``` ## AI Coding Instructions - Preserve interceptor ordering: each interceptor must receive a `CallHandler` that continues to the next interceptor in the chain. - Use `createContext()` when constructing execution contexts so interceptors receive the expected arguments, instance, callback, and context type. - Keep handler execution deferred through `transformDeferred()`; do not eagerly invoke `next()` before an interceptor calls `next.handle()`. - Support route handler results that are plain values, promises, or observables when changing deferred-result handling. - This class is core framework infrastructure; application code should normally register interceptors through NestJS decorators or providers rather than invoking `InterceptorsConsumer` directly. ## Relationships - IMPORTS → `NestInterceptor` - IMPORTS → `Type` - IMPORTS → `CallHandler` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `isEmpty` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # GuardsConsumer **Kind:** Class **Source:** [`packages/core/guards/guards-consumer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/guards/guards-consumer.ts#L7) **Part of:** [Core](subsystem-packages-core) `GuardsConsumer` evaluates a sequence of NestJS `CanActivate` guards for an incoming execution context. It creates an `ExecutionContextHost`, runs guards in order, supports synchronous, Promise-based, and Observable results, and stops when a guard denies access. ## Methods | Method | Signature | Returns | |---|---|---| | `tryActivate` | `tryActivate(guards: CanActivate[], args: unknown[], instance: Controller, callback: (...args: unknown[]) => unknown, type: TContext)` | `Promise` | | `createContext` | `createContext(args: unknown[], instance: Controller, callback: (...args: unknown[]) => unknown)` | `ExecutionContextHost` | | `pickResult` | `pickResult(result: boolean | Promise | Observable)` | `Promise` | ## Where it refuses work - `GuardsConsumer` stops the work with an early return when `!guards || isEmpty(guards)`. - `GuardsConsumer` stops the work with an early return when `!result`. - `GuardsConsumer` stops the work with an early return when `result instanceof Observable`. ## Diagram ```mermaid graph LR A[Route Handler Arguments] --> B[GuardsConsumer.tryActivate] B --> C[createContext] C --> D[ExecutionContextHost] B --> E[Guard.canActivate] E --> F[pickResult] F -->|true| G[Evaluate Next Guard] F -->|false| H[Reject Request] G -->|All guards pass| I[Allow Handler Execution] ``` ## Usage ```ts import { GuardsConsumer } from '@nestjs/core/guards/guards-consumer'; import { CanActivate, ExecutionContext } from '@nestjs/common'; class ApiKeyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return request.headers['x-api-key'] === process.env.API_KEY; } } async function checkGuards(request: any, response: any) { const consumer = new GuardsConsumer(); const guards = [new ApiKeyGuard()]; const isAllowed = await consumer.tryActivate( guards, [request, response, () => undefined], ExampleController.prototype, ExampleController.prototype.getProfile, 'http', ); if (!isAllowed) { throw new Error('Access denied'); } } class ExampleController { getProfile() { return { id: 1 }; } } ``` ## AI Coding Instructions - Preserve short-circuit behavior: stop evaluating guards immediately when any guard returns `false`. - Ensure `tryActivate()` continues to support `boolean`, `Promise`, and `Observable` guard results through `pickResult()`. - Use `createContext()` to construct the execution context so guards receive the controller instance, handler callback, and request arguments consistently. - Set the context type (`http`, `rpc`, or `ws`) before invoking guards so transport-specific guard logic can use the correct context switcher. - Avoid swallowing errors thrown by guards; failures should propagate through NestJS's normal exception handling flow. ## Relationships - IMPORTS → `CanActivate` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `isEmpty` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # SerializedGraph **Kind:** Class **Source:** [`packages/core/inspector/serialized-graph.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/serialized-graph.ts#L26) **Part of:** [Core](subsystem-packages-core) `SerializedGraph` builds an inspector-friendly representation of a graph by collecting nodes, edges, entrypoints, and enhancer relationships. It provides lookup support during graph construction and exposes `toJSON()` and `toString()` for exporting the completed graph to tooling, logs, or persisted inspector output. ## Methods | Method | Signature | Returns | |---|---|---| | `insertNode` | `insertNode(nodeDefinition: Node)` | `void` | | `insertEdge` | `insertEdge(edgeDefinition: WithOptionalId)` | `void` | | `insertEntrypoint` | `insertEntrypoint(definition: Entrypoint, parentId: string)` | `void` | | `insertOrphanedEnhancer` | `insertOrphanedEnhancer(entry: OrphanedEnhancerDefinition)` | `void` | | `insertAttachedEnhancer` | `insertAttachedEnhancer(nodeId: string)` | `void` | | `getNodeById` | `getNodeById(id: string)` | `void` | | `toJSON` | `toJSON()` | `SerializedGraphJson` | | `toString` | `toString()` | `void` | ## Where it refuses work - `SerializedGraph` stops the work with an early return when `this.nodes.has(nodeDefinition.id)`. - `SerializedGraph` stops the work with an early return when `typeof value === 'symbol'`. ## Diagram ```mermaid graph LR Entrypoint[Entrypoint] --> NodeA[Serialized Node] NodeA -->|edge| NodeB[Serialized Node] NodeA -->|attached enhancer| EnhancerA[Enhancer] OrphanedEnhancer[Orphaned Enhancer] --> Graph[SerializedGraph] NodeB --> Graph EnhancerA --> Graph Graph --> JSON[toJSON()] Graph --> Text[toString()] ``` ## Usage ```ts import { SerializedGraph } from './serialized-graph'; const graph = new SerializedGraph(); // Add graph entities using the inspector's serialized descriptor types. graph.insertNode({ id: 'user-service', label: 'UserService', }); graph.insertNode({ id: 'user-repository', label: 'UserRepository', }); graph.insertEdge({ from: 'user-service', to: 'user-repository', }); graph.insertEntrypoint({ id: 'get-user', nodeId: 'user-service', }); graph.insertAttachedEnhancer({ nodeId: 'user-service', enhancer: { id: 'auth-guard', type: 'guard', }, }); // Export the completed graph for inspector consumers. const serialized = graph.toJSON(); console.log(serialized); // Use the string form for diagnostics or snapshots. console.log(graph.toString()); // Look up a previously inserted node while building relationships. const serviceNode = graph.getNodeById('user-service'); ``` ## AI Coding Instructions - Insert nodes before adding edges or attached enhancers that reference their IDs; use stable, unique IDs throughout graph construction. - Use `getNodeById()` when extending an existing node rather than duplicating node records. - Represent enhancers attached to a known node with `insertAttachedEnhancer()`; use `insertOrphanedEnhancer()` only when no owning node can be resolved. - Treat `toJSON()` as the structured integration boundary for inspector consumers, snapshots, and transport layers. - Keep `toString()` usage limited to debugging and diagnostics; prefer `toJSON()` for programmatic processing. ## How it works `SerializedGraph` is a mutable in-memory representation of an inspected application graph. It stores nodes and edges by ID, entrypoints grouped by parent ID, enhancer-related extras, a graph status, and optional failure metadata. Its initial status is `'complete'`; its extras start with empty orphaned- and attached-enhancer arrays. [`packages/core/inspector/serialized-graph.ts:26-35`](packages/core/inspector/serialized-graph.ts#L26-L35) - A node has an `id` and `label`, and is either: - a module node with `global`, `dynamic`, and `internal` metadata; or - a class node—provider, controller, middleware, or injectable—with its parent module ID and class-related metadata such as token, scope, lifecycle flags, export state, and initialization time. [`packages/core/inspector/interfaces/node.interface.ts:4-47`](packages/core/inspector/interfaces/node.interface.ts#L4-L47) - An edge connects `source` and `target` node IDs. Edge metadata describes either a module import connection or a class-to-class dependency, including injection type and, where applicable, the constructor parameter, property, or decorator key/index. [`packages/core/inspector/interfaces/edge.interface.ts:3-31`](packages/core/inspector/interfaces/edge.interface.ts#L3-L31) - Entrypoints are stored as arrays under a caller-supplied parent ID. Each entrypoint includes its type, method name, class name, class node ID, and metadata with a `key`. [`packages/core/inspector/serialized-graph.ts:29`](packages/core/inspector/serialized-graph.ts#L29) [`packages/core/inspector/serialized-graph.ts:102-109`](packages/core/inspector/serialized-graph.ts#L102-L109) [`packages/core/inspector/interfaces/entrypoint.interface.ts:17-24`](packages/core/inspector/interfaces/entrypoint.interface.ts#L17-L24) `insertNode(node)` marks provider nodes as `internal: true` when their token is one of the class’s listed framework-internal tokens, such as `ApplicationConfig`, `ModuleRef`, `HttpAdapterHost`, `LazyModuleLoader`, `ExternalContextCreator`, `ModulesContainer`, `Reflector`, `SerializedGraph`, `REQUEST`, or `INQUIRER`. [`packages/core/inspector/serialized-graph.ts:37-50`](packages/core/inspector/serialized-graph.ts#L37-L50) [`packages/core/inspector/serialized-graph.ts:60-69`](packages/core/inspector/serialized-graph.ts#L60-L69) It then inserts the node only when its ID is absent; for an existing ID, it returns the already stored node rather than replacing it. The internal-marker mutation occurs before that duplicate check. [`packages/core/inspector/serialized-graph.ts:60-75`](packages/core/inspector/serialized-graph.ts#L60-L75) `insertEdge(edge)` accepts an edge with an optional ID. For a class-to-class edge, it marks the edge metadata as internal when either class token is in that same internal-token list. [`packages/core/inspector/serialized-graph.ts:77-91`](packages/core/inspector/serialized-graph.ts#L77-L91) When no ID is supplied, it serializes the edge definition with `JSON.stringify` and passes the resulting string to `DeterministicUuidRegistry.get()`. [`packages/core/inspector/serialized-graph.ts:92-99`](packages/core/inspector/serialized-graph.ts#L92-L99) The registry derives an ID from a 31-based integer hash and retries with an incremented suffix if that ID is already registered. [`packages/core/inspector/deterministic-uuid-registry.ts:4-10`](packages/core/inspector/deterministic-uuid-registry.ts#L4-L10) The completed edge is stored under its ID, replacing any edge currently stored under that ID, and is returned. [`packages/core/inspector/serialized-graph.ts:94-99`](packages/core/inspector/serialized-graph.ts#L94-L99) `insertEntrypoint(definition, parentId)` appends the definition to the existing collection for `parentId`, or creates a one-item collection when none exists. [`packages/core/inspector/serialized-graph.ts:102-109`](packages/core/inspector/serialized-graph.ts#L102-L109) `insertOrphanedEnhancer(entry)` appends an enhancer definition to `extras.orphanedEnhancers`, while `insertAttachedEnhancer(nodeId)` appends `{ nodeId }` to `extras.attachedEnhancers`; neither method removes duplicates. [`packages/core/inspector/serialized-graph.ts:111-119`](packages/core/inspector/serialized-graph.ts#L111-L119) The corresponding types identify orphaned enhancers by subtype and reference, and attached enhancers by node ID. [`packages/core/inspector/interfaces/extras.interface.ts:3-21`](packages/core/inspector/interfaces/extras.interface.ts#L3-L21) `getNodeById(id)` returns the node associated with `id`, or the map’s missing-value result when no such node exists. [`packages/core/inspector/serialized-graph.ts:121-123`](packages/core/inspector/serialized-graph.ts#L121-L123) The `status` and `metadata` setters directly replace their respective private fields. [`packages/core/inspector/serialized-graph.ts:52-58`](packages/core/inspector/serialized-graph.ts#L52-L58) Status is limited by its TypeScript type to `'partial'` or `'complete'`. [`packages/core/inspector/serialized-graph.ts:22`](packages/core/inspector/serialized-graph.ts#L22) Metadata records either an `unknown-dependencies` cause with optional dependency context, module ID, and node ID, or an `unknown` cause with an optional error value. [`packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts:3-11`](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L3-L11) `toJSON()` converts the node, edge, and entrypoint maps into plain object records, retains the `extras` object by reference, always includes the initialized status, and adds metadata only when it is set. [`packages/core/inspector/serialized-graph.ts:125-140`](packages/core/inspector/serialized-graph.ts#L125-L140) `toString()` JSON-formats that result with two-space indentation; its replacer converts symbol values to their string form and function values to their name, falling back to `'Function'`. [`packages/core/inspector/serialized-graph.ts:142-150`](packages/core/inspector/serialized-graph.ts#L142-L150) The container owns one graph instance and exposes it through `serializedGraph`. [`packages/core/injector/container.ts:31-40`](packages/core/injector/container.ts#L31-L64) The internal core module also registers that same instance under the `SerializedGraph` injection token. [`packages/core/injector/internal-core-module/internal-core-module-factory.ts:69-72`](packages/core/injector/internal-core-module/internal-core-module-factory.ts#L69-L72) `GraphInspector` populates it from modules, class wrappers, imports, dependency metadata, enhancers, and entrypoint definitions. [`packages/core/inspector/graph-inspector.ts:22-36`](packages/core/inspector/graph-inspector.ts#L22-L36) [`packages/core/inspector/graph-inspector.ts:100-150](packages/core/inspector/graph-inspector.ts#L100-L150) On inspection failure, `GraphInspector.registerPartial()` sets the graph status to `'partial'`, records cause metadata, and registers this graph with `PartialGraphHost`. [`packages/core/inspector/graph-inspector.ts:38-59`](packages/core/inspector/graph-inspector.ts#L38-L59) There is no explicit runtime input validation or class-defined error handling in these mutation and serialization methods; callers must supply values whose accessed fields match the declared node, edge, entrypoint, enhancer, status, and metadata shapes. [`packages/core/inspector/serialized-graph.ts:52-155`](packages/core/inspector/serialized-graph.ts#L52-L155) # BaseExceptionFilterContext **Kind:** Class **Source:** [`packages/core/exceptions/base-exception-filter-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/base-exception-filter-context.ts#L11) **Part of:** [Core](subsystem-packages-core) `BaseExceptionFilterContext` resolves exception filter metadata into executable `ExceptionFilter` instances. It supports both direct filter objects and dependency-injected filter classes, using module context and reflection metadata to locate registered providers. **Extends:** `ContextCreator` ## Methods | Method | Signature | Returns | |---|---|---| | `createConcreteContext` | `createConcreteContext(metadata: T, contextId: undefined, inquirerId: string)` | `R` | | `getFilterInstance` | `getFilterInstance(filter: Function | ExceptionFilter, contextId: undefined, inquirerId: string)` | `ExceptionFilter | null` | | `getInstanceByMetatype` | `getInstanceByMetatype(metatype: Type)` | `InstanceWrapper | undefined` | | `reflectCatchExceptions` | `reflectCatchExceptions(instance: ExceptionFilter)` | `Type[]` | ## Properties | Property | Type | |---|---| | `moduleContext` | `string` | ## Where it refuses work - `BaseExceptionFilterContext` stops the work with an early return when `isEmpty(metadata)`. - `BaseExceptionFilterContext` stops the work with an early return when `isObject`. - `BaseExceptionFilterContext` stops the work with an early return when `!instanceWrapper`. - `BaseExceptionFilterContext` stops the work with an early return when `!this.moduleContext`. - `BaseExceptionFilterContext` stops the work with an early return when `!moduleRef`. ## Diagram ```mermaid graph LR A[Exception filter metadata] --> B[BaseExceptionFilterContext] B --> C{Filter is an object?} C -->|Yes| D[Use filter instance] C -->|No| E[Find InstanceWrapper in module injectables] E --> F[Resolve instance for context ID] D --> G[Validate catch() method] F --> G G --> H[Concrete ExceptionFilter instances] ``` ## Usage ```ts import { ArgumentsHost, Catch, ExceptionFilter, } from '@nestjs/common'; import { BaseExceptionFilterContext } from '@nestjs/core/exceptions'; // A filter object can be resolved without looking up a DI provider. @Catch(Error) class LogErrorFilter implements ExceptionFilter { catch(exception: Error, host: ArgumentsHost) { console.error('Request failed:', exception.message); } } // In framework integration code, `container` is Nest's NestContainer instance. const filterContext = new BaseExceptionFilterContext(container); const filters = filterContext.createConcreteContext< ExceptionFilter[], ExceptionFilter[] >([new LogErrorFilter()]); // `filters` contains only valid objects that implement catch(). filters.forEach(filter => filter.catch(new Error('Example'), host)); ``` ## AI Coding Instructions - Resolve filter classes through `getFilterInstance()` so request-scoped and dependency-injected providers use the correct context ID. - Ensure every resolved filter implements a callable `catch()` method; invalid or unresolved filters are excluded from the concrete context. - Set the active module context before resolving class-based filters, since `getInstanceByMetatype()` searches that module’s injectable providers. - Use `reflectCatchExceptions()` to read `@Catch()` metadata rather than manually inspecting decorator metadata keys. ## Relationships - IMPORTS → `FILTER_CATCH_EXCEPTIONS` - IMPORTS → `Type` - IMPORTS → `ExceptionFilter` - IMPORTS → `isEmpty` - IMPORTS → `isFunction` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ExceptionFiltersContext` — `packages/microservices/context/exception-filters-context.ts`:16 - `ExceptionFiltersContext` — `packages/websockets/context/exception-filters-context.ts`:10 # DiscoverableMetaHostCollection **Kind:** Class **Source:** [`packages/core/discovery/discoverable-meta-host-collection.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discoverable-meta-host-collection.ts#L5) **Part of:** [Core](subsystem-packages-core) `DiscoverableMetaHostCollection` tracks Nest providers and controllers by discoverable metadata keys. It records class-to-metadata links, inspects framework-managed `InstanceWrapper` objects during discovery, and exposes indexed sets for metadata-based lookup. ## Methods | Method | Signature | Returns | |---|---|---| | `addClassMetaHostLink` | `addClassMetaHostLink(target: Type | Function, metadataKey: string)` | `void` | | `inspectProvider` | `inspectProvider(hostContainerRef: ModulesContainer, instanceWrapper: InstanceWrapper)` | `void` | | `inspectController` | `inspectController(hostContainerRef: ModulesContainer, instanceWrapper: InstanceWrapper)` | `void` | | `insertByMetaKey` | `insertByMetaKey(metaKey: string, instanceWrapper: InstanceWrapper, collection: Map>)` | `void` | | `getProvidersByMetaKey` | `getProvidersByMetaKey(hostContainerRef: ModulesContainer, metaKey: string)` | `Set` | | `getControllersByMetaKey` | `getControllersByMetaKey(hostContainerRef: ModulesContainer, metaKey: string)` | `Set` | ## Properties | Property | Type | |---|---| | `metaHostLinks` | `any` | ## Where it refuses work - `DiscoverableMetaHostCollection` stops the work with an early return when `!metaKey`. ## Diagram ```mermaid graph LR Decorator[Custom decorator] -->|addClassMetaHostLink| Links[Class metadata links] Provider[Provider InstanceWrapper] -->|inspectProvider| Collection[DiscoverableMetaHostCollection] Controller[Controller InstanceWrapper] -->|inspectController| Collection Links --> Collection Collection --> ProviderIndex[providersByMetaKey] Collection --> ControllerIndex[controllersByMetaKey] ProviderIndex -->|getProvidersByMetaKey| Result[Set of InstanceWrapper] ControllerIndex -->|getControllersByMetaKey| Result ``` ## Usage ```ts import { SetMetadata } from '@nestjs/common'; import { DiscoverableMetaHostCollection } from '@nestjs/core/discovery/discoverable-meta-host-collection'; import type { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; const FEATURE_KEY = Symbol('feature'); // A custom discoverable decorator should register both metadata and the class link. export function FeatureHandler(): ClassDecorator { return (target) => { SetMetadata(FEATURE_KEY, true)(target); DiscoverableMetaHostCollection.addClassMetaHostLink( target, FEATURE_KEY, ); }; } @FeatureHandler() class ReportService {} const collection = new DiscoverableMetaHostCollection(); // `providerWrapper` is normally supplied by Nest's module/container discovery flow. const providerWrapper = {} as InstanceWrapper; collection.inspectProvider(providerWrapper); const handlers = collection.getProvidersByMetaKey(FEATURE_KEY); for (const wrapper of handlers) { console.log(wrapper.metatype?.name); } ``` ## AI Coding Instructions - Register class metadata through `addClassMetaHostLink()` when creating discoverable class decorators; setting reflection metadata alone is not sufficient for this index. - Use `inspectProvider()` for provider wrappers and `inspectController()` for controller wrappers so each type is stored in the correct lookup map. - Treat `InstanceWrapper` objects as Nest container internals; obtain them from framework discovery/container flows rather than constructing them manually in application code. - Use stable string or `Symbol` metadata keys consistently for registration and lookup. - Expect lookup methods to return a `Set` and handle an empty set when no matching hosts were discovered. ## Relationships - IMPORTS → `Type` # MiddlewareModule **Kind:** Class **Source:** [`packages/core/middleware/middleware-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/middleware-module.ts#L35) **Part of:** [Core](subsystem-packages-core) `MiddlewareModule` coordinates middleware discovery, configuration loading, and route-level registration for the application. It resolves middleware implementations, normalizes their configuration, and attaches them to the appropriate routes during application initialization. ## Methods | Method | Signature | Returns | |---|---|---| | `register` | `register(middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, options: TAppOptions)` | `void` | | `resolveMiddleware` | `resolveMiddleware(middlewareContainer: MiddlewareContainer, modules: Map)` | `void` | | `loadConfiguration` | `loadConfiguration(middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string)` | `void` | | `registerMiddleware` | `registerMiddleware(middlewareContainer: MiddlewareContainer, applicationRef: any)` | `void` | | `registerMiddlewareConfig` | `registerMiddlewareConfig(middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any)` | `void` | | `registerRouteMiddleware` | `registerRouteMiddleware(middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any)` | `void` | ## Where it refuses work - `MiddlewareModule` stops the work with `RuntimeException` when `isUndefined(instanceWrapper)`. - `MiddlewareModule` stops the work with `InvalidMiddlewareException` when `isUndefined(instance?.use)`. - `MiddlewareModule` stops the work with an early return when `!instance.configure`. - `MiddlewareModule` stops the work with an early return when `!this.appOptions.preview`. - `MiddlewareModule` stops the work with an early return when `!(middlewareBuilder instanceof MiddlewareBuilder)`. - `MiddlewareModule` stops the work with an early return when `isModuleAGlobal && isModuleBGlobal`. ## When something fails - `MiddlewareModule` handles failure in 2 places: it logs it and continues in 1, and lets it reach the caller in 1. ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[MiddlewareModule.register] B --> C[loadConfiguration] C --> D[registerMiddlewareConfig] D --> E[resolveMiddleware] E --> F[registerMiddleware] F --> G[registerRouteMiddleware] G --> H[Application Routes] ``` ## Usage ```ts import { MiddlewareModule } from '@your-package/core'; // Resolve the module from the application's dependency container. const middlewareModule = app.get(MiddlewareModule); // During bootstrap, load middleware configuration and bind middleware to routes. await middlewareModule.register(); ``` ## AI Coding Instructions - Call `register()` during application bootstrap; it orchestrates configuration loading and middleware-to-route binding. - Add new middleware through the supported configuration flow rather than registering route handlers directly. - Ensure configured middleware can be resolved by the application container before it is referenced in route configuration. - Keep route middleware configuration explicit, including the target route, HTTP method, and middleware ordering where applicable. - When changing registration behavior, preserve the sequence of configuration loading, middleware resolution, and route registration. # NestFactoryStatic **Kind:** Class **Source:** [`packages/core/nest-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts#L48) **Part of:** [Core](subsystem-packages-core) `NestFactoryStatic` is the core factory responsible for bootstrapping Nest applications from a root module. It creates HTTP applications, standalone application contexts, and microservices while coordinating dependency scanning, container initialization, and adapter setup. In typical applications, it is accessed through the exported `NestFactory` instance. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(module: IEntryNestModule, options: NestApplicationOptions)` | `Promise` | | `create` | `create(module: IEntryNestModule, httpAdapter: AbstractHttpAdapter, options: NestApplicationOptions)` | `Promise` | | `create` | `create(moduleCls: IEntryNestModule, serverOrOptions: AbstractHttpAdapter | NestApplicationOptions, options: NestApplicationOptions)` | `Promise` | | `createMicroservice` | `createMicroservice(moduleCls: IEntryNestModule, options: NestMicroserviceOptions & T)` | `Promise` | | `createApplicationContext` | `createApplicationContext(moduleCls: IEntryNestModule, options: NestApplicationContextOptions)` | `Promise` | ## Where it refuses work - `NestFactoryStatic` stops the work with an early return when `isFunction(receiver[prop])`, in 2 places. - `NestFactoryStatic` stops the work with an early return when `!(prop in receiver)`. - `NestFactoryStatic` stops the work with an early return when `!options`. - `NestFactoryStatic` stops the work with an early return when `!(prop in receiver) && prop in adapter`. ## When something fails - `NestFactoryStatic` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR RootModule[Root Module] --> Factory[NestFactoryStatic] Factory --> HTTP[create()] Factory --> Microservice[createMicroservice()] Factory --> Context[createApplicationContext()] HTTP --> App[INestApplication] Microservice --> Micro[INestMicroservice] Context --> Standalone[INestApplicationContext] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; @Module({}) class AppModule {} async function bootstrap() { // Create an HTTP application. const app = await NestFactory.create(AppModule); await app.listen(3000); // Create a standalone dependency-injection context. const context = await NestFactory.createApplicationContext(AppModule); // Create a microservice when a transport configuration is available. // const microservice = await NestFactory.createMicroservice(AppModule, { // transport: Transport.TCP, // }); // await microservice.listen(); } bootstrap(); ``` ## AI Coding Instructions - Use `create()` for HTTP-based Nest applications, `createMicroservice()` for transport-driven services, and `createApplicationContext()` for CLI jobs, workers, or scripts without an HTTP server. - Pass the root module as the first argument; ensure its imports, providers, and controllers are configured before application bootstrap. - Await factory calls before accessing application APIs such as `listen()`, `get()`, `connectMicroservice()`, or `close()`. - Prefer the public `NestFactory` export rather than instantiating or depending directly on `NestFactoryStatic`. - Ensure standalone contexts and microservices are explicitly closed during tests, scripts, and graceful shutdown flows. # RoutesResolver **Kind:** Class **Source:** [`packages/core/router/routes-resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/routes-resolver.ts#L35) **Part of:** [Core](subsystem-packages-core) `RoutesResolver` connects discovered controllers and route metadata to the underlying HTTP adapter during application initialization. It registers controller routes, configures not-found and exception handlers, and maps framework exceptions to adapter-compatible responses. **Implements:** `Resolver` ## Methods | Method | Signature | Returns | |---|---|---| | `resolve` | `resolve(applicationRef: T, globalPrefix: string)` | `void` | | `registerRouters` | `registerRouters(routes: Map>, moduleName: string, globalPrefix: string, modulePath: string, applicationRef: HttpServer)` | `void` | | `registerNotFoundHandler` | `registerNotFoundHandler()` | `void` | | `registerExceptionHandler` | `registerExceptionHandler()` | `void` | | `mapExternalException` | `mapExternalException(err: any)` | `void` | ## Where it refuses work - `RoutesResolver` stops the work with an early return when `versioningConfig`. ## Diagram ```mermaid graph LR A[Application bootstrap] --> B[RoutesResolver.resolve] B --> C[registerRouters] C --> D[Controller routes] D --> E[HTTP adapter router] B --> F[registerNotFoundHandler] F --> E B --> G[registerExceptionHandler] G --> H[mapExternalException] H --> E ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // RoutesResolver uses this prefix while registering controller routes. app.setGlobalPrefix('api'); // During initialization, Nest internally uses RoutesResolver to: // - discover controller routes // - register them with the HTTP adapter // - configure 404 and exception handlers await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Treat `RoutesResolver` as framework bootstrap infrastructure; application code should usually define controllers and let the framework invoke `resolve()`. - Preserve the registration order: controller routes should be registered before fallback not-found and exception handlers are attached. - When adding route-related behavior, ensure global prefixes, module paths, and controller metadata are consistently applied. - Keep adapter-specific error handling inside `mapExternalException()` so external HTTP adapters receive compatible error objects. - Avoid registering catch-all routes or error middleware too early, as they can prevent resolved controller routes from being reached. ## How it works ## `RoutesResolver` `RoutesResolver` is the HTTP-routing resolver created by `NestApplication`. During application initialization, the application invokes `resolve()` after middleware registration, then invokes its not-found and error-hook registration methods after initialization hooks. [`packages/core/nest-application.ts:190-194`](packages/core/nest-application.ts#L190-L194) [`packages/core/nest-application.ts:207-218`](packages/core/nest-application.ts#L207-L218) It implements the `Resolver` contract: route resolution plus registration of not-found and exception handlers. [`packages/core/router/interfaces/resolver.interface.ts:1-5`](packages/core/router/interfaces/resolver.interface.ts#L1-L5) ## Relationships - IMPORTS → `BadRequestException` - IMPORTS → `HttpException` - IMPORTS → `NotFoundException` - IMPORTS → `HOST_METADATA` - IMPORTS → `MODULE_PATH` - IMPORTS → `VERSION_METADATA` - IMPORTS → `Controller` - IMPORTS → `HttpServer` - IMPORTS → `Type` - IMPORTS → `VersionValue` - IMPORTS → `Logger` # ReplContext **Kind:** Class **Source:** [`packages/core/repl/repl-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-context.ts#L29) **Part of:** [Core](subsystem-packages-core) `ReplContext` encapsulates the runtime context used by the REPL subsystem. It provides output handling through `writeToStdout()`, allowing REPL execution code to send its current output to the standard output stream. ## Methods | Method | Signature | Returns | |---|---|---| | `writeToStdout` | `writeToStdout(text: string)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `debugRegistry` | `Record` | | `globalScope` | `ReplScope` | | `nativeFunctions` | `any` | ## Where it refuses work - `ReplContext` stops the work with an early return when `moduleName === InternalCoreModule.name`. - `ReplContext` stops the work with an early return when `stringifiedToken === ApplicationConfig.name || stringifiedToken === moduleRef.metatype.na…`. - `ReplContext` stops the work with an early return when `stringifiedToken === ModuleRef.name`. ## Diagram ```mermaid graph LR REPL[REPL Command / Evaluator] --> Context[ReplContext] Context --> Output[writeToStdout()] Output --> Stdout[Process Standard Output] ``` ## Usage ```ts import { ReplContext } from "./repl-context"; // Typically created and managed by the REPL runtime. declare const context: ReplContext; // Write the context's current output to standard output. context.writeToStdout(); ``` ## AI Coding Instructions - Keep terminal-output behavior centralized in `ReplContext` rather than writing directly to `process.stdout` from REPL command handlers. - Call `writeToStdout()` only after the context has been populated with the output intended for the user. - Preserve the existing REPL context lifecycle when adding commands or evaluators; prefer receiving a `ReplContext` instance over creating unrelated output state. - Avoid coupling REPL evaluation logic to a specific terminal implementation; use the context as the integration boundary for output. ## How it works `ReplContext` is the state holder used to populate and operate the Nest REPL. It retains the application context, a `Logger` named `ReplContext`, a module-debug registry, a null-prototype global scope, and a map of native REPL-function instances. [packages/core/repl/repl-context.ts:29-40] Its constructor accepts an `INestApplicationContext` and an optional array of `ReplFunction` classes. At runtime, it reads `app.container` through an `any` cast, then immediately builds the module scope and registers built-in plus supplied native functions. Therefore, the supplied application object must expose a container with `getModules()` when constructed. [packages/core/repl/repl-context.ts:39-47] [packages/core/repl/repl-context.ts:53-56] - `globalScope` starts as `Object.create(null)`, so it has no inherited object properties. [packages/core/repl/repl-context.ts:27,32] - For every container module except `InternalCoreModule`, the context adds the module metatype to `globalScope` under its class name. If that name is already truthy in the scope, it appends ` (${moduleRef.token})` to distinguish the module key. These module properties are enumerable and non-configurable. [packages/core/repl/repl-context.ts:56-74] - For each module’s `providers` and `controllers`, it records token names in `debugRegistry[moduleKey]`. It excludes entries whose stringified token matches `ApplicationConfig`, the module metatype name, or `ModuleRef`; only the first two exclusions also prevent adding the token to `globalScope`. [packages/core/repl/repl-context.ts:77-112] - Tokens are named as follows: string tokens become quoted strings such as `"token"`; function tokens use `token.name`; other values use `token?.toString()`. [packages/core/repl/repl-context.ts:114-120] - A token is added to `globalScope` only when no truthy value already exists under that stringified name. The resulting property is enumerable and non-configurable. [packages/core/repl/repl-context.ts:92-99] The standard `repl()` bootstrap creates this context after initializing the application, then copies `globalScope` property descriptors into Node’s `replServer.context`. [packages/core/repl/repl.ts:16-22,25-32] This makes the collected module and injection-token references available in that REPL context. [packages/core/repl/repl-context.ts:65-74,92-99] [packages/core/repl/assign-to-object.util.ts:5-16] `debugRegistry` has one entry per included module key, with separate `controllers` and `providers` records mapping stringified names to their original injection tokens. [packages/core/repl/repl-context.ts:21-25,77-112] The built-in `debug()` function reads this registry to print either all modules or one selected module; if a requested module key is absent, it logs an error. [packages/core/repl/native-functions/debug-repl-fn.ts:15-36] The context always registers these built-in function classes: `HelpReplFn`, `GetReplFn`, `ResolveReplFn`, `SelectReplFn`, `DebugReplFn`, and `MethodsReplFn`; optional function classes are appended after them. [packages/core/repl/repl-context.ts:165-184] Each class is constructed with this context and stored in `nativeFunctions` under its declared name. [packages/core/repl/repl-context.ts:122-129] Declared aliases create objects inheriting from the primary function instance, with alias-specific name metadata, and are also added to the map. [packages/core/repl/repl-context.ts:130-142] Every registered function name, including aliases, is assigned to `globalScope` as an `action` method bound to its function instance. [packages/core/repl/repl-context.ts:145-151] The bound function gets a non-enumerable, non-configurable `help` getter; reading it writes that function’s formatted help message to standard output. [packages/core/repl/repl-context.ts:152-162] Function metadata requires a name, description, and signature, with optional aliases; a function class must accept a `ReplContext` and create a `ReplFunction`. [packages/core/repl/repl.interfaces.ts:4-21] The built-ins use the retained application context for `get`, `resolve`, and `select`, while `methods` resolves string tokens through `app.get()` before scanning prototype method names. [packages/core/repl/native-functions/get-repl-fn.ts:14-16] [packages/core/repl/native-functions/resolve-repl-fn.ts:13-18] [packages/core/repl/native-functions/select-relp-fn.ts:17-19] [packages/core/repl/native-functions/methods-repl-fn.ts:17-30] The built-in `help()` function reads and sorts `nativeFunctions`, then writes each function’s name and description. [packages/core/repl/native-functions/help-repl-fn.ts:17-30] `writeToStdout(text)` directly calls `process.stdout.write(text)`, creating output as its visible side effect. [packages/core/repl/repl-context.ts:49-51] # RoutePathFactory **Kind:** Class **Source:** [`packages/core/router/route-path-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/route-path-factory.ts#L18) **Part of:** [Core](subsystem-packages-core) `RoutePathFactory` builds normalized route path strings from module, controller, and handler metadata. It applies URI version prefixes, global prefixes, excluded-route rules, and trailing/leading slash normalization before routes are registered by the router. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(metadata: RoutePathMetadata, requestMethod: RequestMethod)` | `string[]` | | `getVersion` | `getVersion(metadata: RoutePathMetadata)` | `void` | | `getVersionPrefix` | `getVersionPrefix(versioningOptions: VersioningOptions)` | `string` | | `appendToAllIfDefined` | `appendToAllIfDefined(paths: string[], fragmentToAppend: string | string[] | undefined)` | `string[]` | | `isExcludedFromGlobalPrefix` | `isExcludedFromGlobalPrefix(path: string, requestMethod: RequestMethod, versionOrVersions: VersionValue, versioningOptions: VersioningOptions)` | `void` | ## Where it refuses work - `RoutePathFactory` stops the work with an early return when `this.isExcludedFromGlobalPrefix( path, requestMethod, versionOrVersions, metadata.version…`. - `RoutePathFactory` stops the work with an early return when `versioningOptions.prefix !== undefined`. - `RoutePathFactory` stops the work with an early return when `!fragmentToAppend`. - `RoutePathFactory` stops the work with an early return when `isUndefined(requestMethod)`. ## Diagram ```mermaid graph LR A[Route metadata] --> B[Resolve controller/method version] B --> C[Apply URI version prefix] C --> D[Append module path] D --> E[Append controller path] E --> F[Append method path] F --> G{Excluded from global prefix?} G -->|No| H[Apply global prefix] G -->|Yes| I[Keep route path] H --> J[Normalize slashes] I --> J J --> K[string[] route paths] ``` ## Usage ```ts import { ApplicationConfig } from '@nestjs/core/application-config'; import { RoutePathFactory } from '@nestjs/core/router/route-path-factory'; import { RequestMethod, VersioningType } from '@nestjs/common'; const applicationConfig = new ApplicationConfig(); const routePathFactory = new RoutePathFactory(applicationConfig); const paths = routePathFactory.create( { modulePath: 'admin', ctrlPath: 'users', methodPath: ':id', globalPrefix: 'api', controllerVersion: '1', versioningOptions: { type: VersioningType.URI, prefix: 'v', }, }, RequestMethod.GET, ); console.log(paths); // ['/api/v1/admin/users/:id'] ``` ## AI Coding Instructions - Keep path segments unnormalized while composing them; let `RoutePathFactory` perform leading/trailing slash normalization at the end. - Preserve the precedence used by `getVersion()`: method version overrides controller version, which overrides the configured default version. - Only prepend versions to paths when URI versioning is enabled; header and media-type versioning should not alter the URL path. - When adding global-prefix behavior, always respect `isExcludedFromGlobalPrefix()` so configured excluded routes remain accessible without the prefix. - Treat this class as router infrastructure: changes should be validated against module paths, controller paths, method paths, versioned routes, and global-prefix exclusions. ## How it works ## `RoutePathFactory` `RoutePathFactory` is a class that builds one or more normalized HTTP route path strings from route metadata and optional request-method information. It receives an `ApplicationConfig` instance in its constructor, which it reads when deciding whether a route is excluded from a global prefix. [`packages/core/router/route-path-factory.ts:18-19`](packages/core/router/route-path-factory.ts#L18-L19) [`packages/core/router/route-path-factory.ts:117-143`](packages/core/router/route-path-factory.ts#L117-L143) `RoutePathMetadata` may contain module, controller, and method path fragments; a global prefix; controller- and method-level version values; and versioning options. [`packages/core/router/interfaces/route-path-metadata.interface.ts:4-39`](packages/core/router/interfaces/route-path-metadata.interface.ts#L4-L39) ## Relationships - IMPORTS → `RequestMethod` - IMPORTS → `VERSION_NEUTRAL` - IMPORTS → `VersioningOptions` - IMPORTS → `VersioningType` - IMPORTS → `flatten` - IMPORTS → `VersionValue` - IMPORTS → `addLeadingSlash` - IMPORTS → `isUndefined` - IMPORTS → `stripEndSlash` # LegacyRouteConverter **Kind:** Class **Source:** [`packages/core/router/legacy-route-converter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/legacy-route-converter.ts#L6) **Part of:** [Core](subsystem-packages-core) `LegacyRouteConverter` converts legacy route definitions into the current router format. It encapsulates conversion validation and diagnostics, returning the converted route string through `tryConvert()` while using `printError()` and `printWarning()` to report unsupported or potentially ambiguous patterns. ## Methods | Method | Signature | Returns | |---|---|---| | `tryConvert` | `tryConvert(route: string, options: { logs?: boolean; })` | `string` | | `printError` | `printError(route: string)` | `void` | | `printWarning` | `printWarning(route: string, convertedRoute: string)` | `void` | ## Diagram ```mermaid graph LR A[Legacy route definition] --> B[LegacyRouteConverter] B --> C[tryConvert()] C --> D{Conversion valid?} D -->|Yes| E[Converted route string] D -->|Warning| F[printWarning()] D -->|Error| G[printError()] ``` ## Usage ```ts import { LegacyRouteConverter } from '@core/router/legacy-route-converter'; const legacyRoute = '/users/:id?'; // Provide the legacy route value using the constructor expected by the router. const converter = new LegacyRouteConverter(legacyRoute); try { const convertedRoute = converter.tryConvert(); console.log(convertedRoute); // Use the converted route when registering routes with the current router. } catch (error) { converter.printError(); throw error; } ``` ## AI Coding Instructions - Keep conversion behavior deterministic: equivalent legacy route inputs should always produce the same current-format route string. - Use `printWarning()` for recoverable compatibility concerns and `printError()` for invalid or unsupported route syntax. - Preserve existing diagnostic wording and output conventions, since router migration tooling may rely on them. - Add conversion cases alongside tests for both successful conversions and unsupported legacy patterns. - Avoid silently changing route semantics; prefer explicit warnings or errors when a legacy feature cannot be represented safely. ## How it works `LegacyRouteConverter` is a static utility class for rewriting selected legacy route wildcard syntaxes into named `path-to-regexp` syntax and emitting migration warnings. It owns a Nest `Logger` named `LegacyRouteConverter`. [packages/core/router/legacy-route-converter.ts:6-7] ## Relationships - IMPORTS → `Logger` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 - `FastifyAdapter` — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 # RouterExplorer **Kind:** Class **Source:** [`packages/core/router/router-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-explorer.ts#L57) **Part of:** [Core](subsystem-packages-core) `RouterExplorer` discovers controller route metadata and binds route handlers to the configured HTTP adapter. It creates proxied handlers with exception handling and request-scoped dependency resolution, making it a core part of the framework’s controller-to-router integration. ## Methods | Method | Signature | Returns | |---|---|---| | `explore` | `explore(instanceWrapper: InstanceWrapper, moduleKey: string, httpAdapterRef: T, host: string | RegExp | Array, routePathMetadata: RoutePathMetadata)` | `void` | | `extractRouterPath` | `extractRouterPath(metatype: Type)` | `string[]` | | `applyPathsToRouterProxy` | `applyPathsToRouterProxy(router: T, routeDefinitions: RouteDefinition[], instanceWrapper: InstanceWrapper, moduleKey: string, routePathMetadata: RoutePathMetadata, host: string | RegExp | Array)` | `void` | | `createRequestScopedHandler` | `createRequestScopedHandler(instanceWrapper: InstanceWrapper, requestMethod: RequestMethod, moduleRef: Module, moduleKey: string, methodName: string)` | `void` | ## Where it refuses work - `RouterExplorer` stops the work with `UnknownRequestMappingException` when `isUndefined(path)`. - `RouterExplorer` stops the work with `InternalServerErrorException` when `!next`. - `RouterExplorer` stops the work with an early return when `Array.isArray(path)`. - `RouterExplorer` stops the work with an early return when `!host`. ## When something fails - `RouterExplorer` handles failure in 2 places: it logs it and continues in 1, and lets it reach the caller in 1. ## Diagram ```mermaid graph LR Controller[Controller instance] --> Metadata[Route metadata] Metadata --> RouterExplorer RouterExplorer --> Extract[extractRouterPath()] Extract --> Apply[applyPathsToRouterProxy()] Apply --> Proxy[Router proxy] Proxy --> Adapter[HTTP adapter router] Adapter --> Handler[Controller handler] Handler --> Scoped[createRequestScopedHandler()] Scoped --> Injector[Request-scoped injector] ``` ## Usage ```ts import { RouterExplorer } from '@nestjs/core/router/router-explorer'; // RouterExplorer is typically created by the framework during application setup. // This demonstrates how the framework registers a discovered controller wrapper. routerExplorer.explore( controllerWrapper, // InstanceWrapper containing a controller instance moduleKey, // Internal module identifier httpAdapter, // HttpServer / platform adapter router undefined, // Optional host restriction { modulePath: '/api', controllerPath: '/users', methodPath: '', }, ); // The explorer reads @Controller(), @Get(), @Post(), and related metadata, // then registers proxied handlers on the HTTP adapter. ``` ## AI Coding Instructions - Preserve the separation between route discovery (`extractRouterPath`) and route registration (`applyPathsToRouterProxy`). - Always register handlers through `RouterProxy` so framework exception filters and async error handling remain active. - Use `createRequestScopedHandler` for request-scoped controllers or dependencies; do not resolve request-scoped providers from the static controller instance. - Keep route metadata compatible with `RoutePathFactory`, including module paths, controller paths, method paths, versioning, and host constraints. - Treat `RouterExplorer` as framework infrastructure; application code should define routes with controller decorators rather than instantiate this class directly. # TreeNode **Kind:** Class **Source:** [`packages/core/injector/topology-tree/tree-node.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/topology-tree/tree-node.ts#L1) **Part of:** [Core](subsystem-packages-core) `TreeNode` models a node in the injector topology tree, linking a value to its parent and child nodes. It provides utilities for maintaining relationships, moving nodes between parents, calculating nesting depth, and preventing circular dependency paths. ## Methods | Method | Signature | Returns | |---|---|---| | `addChild` | `addChild(child: TreeNode)` | `void` | | `removeChild` | `removeChild(child: TreeNode)` | `void` | | `relink` | `relink(parent: TreeNode)` | `void` | | `getDepth` | `getDepth()` | `void` | | `hasCycleWith` | `hasCycleWith(target: T)` | `void` | ## Properties | Property | Type | |---|---| | `value` | `T` | | `children` | `any` | ## Where it refuses work - `TreeNode` stops the work with an early return when `visited.has(current!)`, in 2 places. - `TreeNode` stops the work with an early return when `current.value === target`. ## Diagram ```mermaid graph LR Root[Root TreeNode] --> Feature[Feature TreeNode] Feature --> ServiceA[Service A TreeNode] Feature --> ServiceB[Service B TreeNode] ServiceB -. relink() .-> Root ServiceA -. hasCycleWith() .-> Feature ``` ## Usage ```ts import { TreeNode } from './tree-node'; type Provider = { name: string; }; const app = new TreeNode({ name: 'AppModule' }); const feature = new TreeNode({ name: 'FeatureModule' }); const usersService = new TreeNode({ name: 'UsersService' }); app.addChild(feature); feature.addChild(usersService); console.log(usersService.getDepth()); // 2 // Prevent creating a relationship that would introduce a cycle. if (!app.hasCycleWith(usersService)) { app.addChild(usersService); } // Move the service directly under the application node. usersService.relink(app); // Remove a node when it is no longer part of the topology. app.removeChild(feature); ``` ## AI Coding Instructions - Use `addChild()` and `removeChild()` rather than manually changing `parent` or `children` relationships. - Call `hasCycleWith()` before adding or relinking nodes when constructing dependency graphs dynamically. - Use `relink()` to move an existing node; it removes the node from its previous parent before attaching it to the new parent. - Treat `getDepth()` as topology-derived state and avoid caching its result if the tree can be relinked. - Keep this class focused on tree structure; injector-specific resolution logic belongs in the topology tree integration layer. ## How it works `TreeNode` is a generic, mutable tree-node class. It stores a read-only `value`, a public mutable `Set` of child nodes, and a private parent-node reference that may be `null`. [tree-node.ts:1-8](packages/core/injector/topology-tree/tree-node.ts#L1-L8) - **Construction:** `new TreeNode({ value, parent })` assigns the supplied value and parent reference, and starts with an empty `children` set. Construction does **not** add the new node to the supplied parent’s `children` set. [tree-node.ts:3-9](packages/core/injector/topology-tree/tree-node.ts#L3-L9) - **`addChild(child)`:** adds that exact `TreeNode` object to `children`. Because `children` is a `Set`, the collection is keyed by node identity rather than by `value`. This method does not change `child`’s private parent reference. [tree-node.ts:3,11-13](packages/core/injector/topology-tree/tree-node.ts#L3) - **`removeChild(child)`:** removes that node object from `children`; removing an object that is absent has no additional code path. It does not change the removed child’s parent reference. [tree-node.ts:15-17](packages/core/injector/topology-tree/tree-node.ts#L15-L17) - **`relink(parent)`:** if the node currently has a parent, removes itself from that parent’s child set; it then replaces its parent reference and adds itself to the new parent’s child set. [tree-node.ts:19-24](packages/core/injector/topology-tree/tree-node.ts#L19-L24) It accepts only a non-null `TreeNode` parent in its type signature. [tree-node.ts:19](packages/core/injector/topology-tree/tree-node.ts#L19) - **`getDepth()`:** walks parent references beginning with the node itself and returns the number of nodes encountered through the `null` parent. Thus, a root node has depth `1`. [tree-node.ts:26-43](packages/core/injector/topology-tree/tree-node.ts#L26-L43) It tracks visited node objects; if following parents reaches a previously visited node, it returns `-1` instead of a depth. [tree-node.ts:27-43](packages/core/injector/topology-tree/tree-node.ts#L27-L43) - **`hasCycleWith(target)`:** walks from this node through its parents and returns `true` when a current node’s `value === target`, including this node’s own value. [tree-node.ts:46-56](packages/core/injector/topology-tree/tree-node.ts#L46-L56) If the parent chain ends without a match, or a repeated node is reached before a match, it returns `false`. [tree-node.ts:57-64](packages/core/injector/topology-tree/tree-node.ts#L57-L64) There is no runtime validation of constructor inputs, child-parent consistency, relinking to a descendant, or value uniqueness, and the class contains no explicit error throwing. [tree-node.ts:6-24](packages/core/injector/topology-tree/tree-node.ts#L6-L24) Within `TopologyTree`, nodes wrap `Module` instances: the root is created with `parent: null`, newly discovered module nodes are explicitly added to their parent after construction, and an existing node may be relinked after depth and ancestor-value checks. [topology-tree.ts:8-15,33-54](packages/core/injector/topology-tree/topology-tree.ts#L8-L15) # ContextCreator **Kind:** Class **Source:** [`packages/core/helpers/context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-creator.ts#L5) **Part of:** [Core](subsystem-packages-core) `ContextCreator` is a shared base class for building execution-context components from metadata attached to classes and methods. It collects global, class-level, and method-level metadata, then delegates to a concrete implementation to create the final context objects. It also provides consistent request-to-`ContextId` handling for request-scoped dependency resolution. ## Methods | Method | Signature | Returns | |---|---|---| | `createConcreteContext` | `createConcreteContext(metadata: T, contextId: ContextId, inquirerId: string)` | `R` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: ContextId, inquirerId: string)` | `T` | | `createContext` | `createContext(instance: Controller, callback: (...args: any[]) => void, metadataKey: string, contextId: undefined, inquirerId: string)` | `R` | | `reflectClassMetadata` | `reflectClassMetadata(instance: Controller, metadataKey: string)` | `T` | | `reflectMethodMetadata` | `reflectMethodMetadata(callback: (...args: unknown[]) => unknown, metadataKey: string)` | `T` | | `getContextId` | `getContextId(contextId: ContextId, instanceWrapper: InstanceWrapper)` | `ContextId` | ## Diagram ```mermaid graph LR Request[Incoming request] --> ContextId[getContextId()] ContextId --> ContextFactory[ContextIdFactory] Controller[Controller / provider instance] --> CreateContext[createContext()] Handler[Handler callback] --> CreateContext MetadataKey[Metadata key] --> CreateContext Global[getGlobalMetadata()] --> CreateContext ClassMetadata[reflectClassMetadata()] --> CreateContext MethodMetadata[reflectMethodMetadata()] --> CreateContext CreateContext --> Concrete[createConcreteContext()] Concrete --> Result[Concrete context objects] ``` ## Usage ```ts import { ContextCreator } from '@nestjs/core/helpers/context-creator'; import { ContextIdFactory } from '@nestjs/core/helpers/context-id-factory'; const FEATURE_METADATA = 'feature:contexts'; class ExampleController { handleRequest() { return 'ok'; } } // Obtain a concrete ContextCreator implementation from the framework or adapter. declare const contextCreator: ContextCreator; const controller = new ExampleController(); const request = { headers: { 'x-request-id': 'req-123' } }; // Reuse the same ContextId when resolving request-scoped dependencies. const contextId = contextCreator.getContextId(request, false); const contexts = contextCreator.createContext( controller, controller.handleRequest, FEATURE_METADATA, contextId, ); console.log(contexts); ``` ## AI Coding Instructions - Treat `ContextCreator` as infrastructure: use a concrete context creator implementation rather than duplicating metadata collection logic. - Preserve metadata precedence when extending behavior: global metadata is combined with class metadata and then method metadata. - Pass the same `ContextId` through the execution flow so request-scoped providers resolve consistently. - Use stable metadata keys for decorators and ensure metadata is applied to the intended class or handler function. - Keep `createConcreteContext()` focused on converting merged metadata into runtime context objects; avoid performing reflection there. ## Relationships - IMPORTS → `Controller` # AbstractInstanceResolver **Kind:** Class **Source:** [`packages/core/injector/abstract-instance-resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/abstract-instance-resolver.ts#L12) **Part of:** [Core](subsystem-packages-core) `AbstractInstanceResolver` is the internal base class responsible for locating and resolving provider instances from Nest's dependency injection container. It supports synchronous lookup through `get()` and `find()`, plus context-aware asynchronous resolution through `resolvePerContext()` for request-scoped or transient providers. It is extended by container-facing APIs such as `ModuleRef` rather than instantiated directly. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(typeOrToken: Type | Function | string | symbol, options: GetOrResolveOptions)` | `TResult | Array` | | `find` | `find(typeOrToken: Type | Abstract | string | symbol, options: { moduleId?: string; each?: boolean })` | `TResult | Array` | | `resolvePerContext` | `resolvePerContext(typeOrToken: Type | Abstract | string | symbol, contextModule: Module, contextId: ContextId, options: GetOrResolveOptions)` | `Promise>` | ## Properties | Property | Type | |---|---| | `instanceLinksHost` | `InstanceLinksHost` | | `injector` | `Injector` | ## Where it refuses work - `AbstractInstanceResolver` stops the work with `InvalidClassScopeException` when `wrapperRef.scope === Scope.REQUEST || wrapperRef.scope === Scope.TRANSIENT || !wrapperRef…`. - `AbstractInstanceResolver` stops the work with `UnknownElementException` when `!instance`. - `AbstractInstanceResolver` stops the work with an early return when `Array.isArray(instanceLinkOrArray)`, in 2 places. - `AbstractInstanceResolver` stops the work with an early return when `wrapperRef.isDependencyTreeStatic() && !wrapperRef.isTransient`. ## Diagram ```mermaid graph LR A[Application Code] --> B[ModuleRef] B --> C[AbstractInstanceResolver] C --> D[InstanceLinksHost] D --> E[Provider Wrapper] E --> F[Singleton Instance] E --> G[Request-scoped Instance] E --> H[Transient Instance] C -->|get / find| F C -->|resolvePerContext| G C -->|resolvePerContext| H ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ContextIdFactory, ModuleRef } from '@nestjs/core'; @Injectable() export class ReportService { constructor(private readonly moduleRef: ModuleRef) {} getSharedLogger() { // Uses the resolver's synchronous lookup flow for singleton providers. return this.moduleRef.get(AppLogger, { strict: false }); } async createRequestHandler(request: Request) { const contextId = ContextIdFactory.getByRequest(request); // Uses context-aware resolution for request-scoped providers. return this.moduleRef.resolve(RequestHandler, contextId, { strict: false, }); } } ``` ## AI Coding Instructions - Do not instantiate `AbstractInstanceResolver` directly; use or extend container APIs such as `ModuleRef`. - Use synchronous `get()`-style resolution only for providers that are already available in the current static context, typically singleton providers. - Use context-aware resolution for request-scoped or transient providers so each request receives the correct instance. - Pass `{ strict: false }` only when a provider may be declared in another module; prefer strict lookup when module boundaries should be enforced. - Avoid resolving dependencies manually when constructor injection is sufficient; use runtime resolution primarily for dynamic or context-specific dependencies. ## Relationships - IMPORTS → `Abstract` - IMPORTS → `Scope` - IMPORTS → `Type` - IMPORTS → `GetOrResolveOptions` # BaseExceptionFilter **Kind:** Class **Source:** [`packages/core/exceptions/base-exception-filter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/base-exception-filter.ts#L17) **Part of:** [Core](subsystem-packages-core) `BaseExceptionFilter` is NestJS’s default HTTP exception handling foundation. It converts `HttpException` instances and compatible HTTP error objects into framework responses, while safely returning a generic 500 response and logging unexpected errors. **Implements:** `ExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: T, host: ArgumentsHost)` | `void` | | `handleUnknownError` | `handleUnknownError(exception: T, host: ArgumentsHost, applicationRef: AbstractHttpAdapter | HttpServer)` | `void` | | `isExceptionObject` | `isExceptionObject(err: any)` | `err is Error` | | `isHttpError` | `isHttpError(err: any)` | `err is { statusCode: number; message: string }` | ## Properties | Property | Type | |---|---| | `httpAdapterHost` | `HttpAdapterHost` | ## Where it refuses work - `BaseExceptionFilter` stops the work with an early return when `!(exception instanceof HttpException)`. ## Diagram ```mermaid graph LR A[Thrown exception] --> B[BaseExceptionFilter.catch] B --> C{HttpException?} C -->|Yes| D[Extract status and response body] D --> E[Send response through HTTP adapter] C -->|No| F[handleUnknownError] F --> G{HTTP-style error object?} G -->|Yes| H[Use statusCode and message] G -->|No| I[Return generic 500 response] H --> E I --> E ``` ## Usage ```ts import { ArgumentsHost, Catch } from '@nestjs/common'; import { BaseExceptionFilter } from '@nestjs/core'; @Catch() export class AllExceptionsFilter extends BaseExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { // Add custom logging, metrics, or tracing here. console.error('Unhandled exception:', exception); // Preserve Nest's standard HTTP exception behavior. super.catch(exception, host); } } // Register the filter globally: // app.useGlobalFilters(new AllExceptionsFilter()); ``` ## AI Coding Instructions - Extend `BaseExceptionFilter` when adding cross-cutting exception behavior while retaining NestJS’s default HTTP response handling. - Always call `super.catch(exception, host)` unless the custom filter intentionally replaces the complete response flow. - Use `handleUnknownError()` for non-`HttpException` errors; it handles safe 500 responses and error logging. - Avoid exposing raw unknown error messages or stack traces in HTTP responses; rely on the base filter’s generic internal-error behavior. - Ensure custom filters are registered through `app.useGlobalFilters()` or the `APP_FILTER` provider token. ## Relationships - IMPORTS → `ArgumentsHost` - IMPORTS → `ExceptionFilter` - IMPORTS → `HttpException` - IMPORTS → `HttpServer` - IMPORTS → `HttpStatus` - IMPORTS → `Inject` - IMPORTS → `IntrinsicException` - IMPORTS → `Logger` - IMPORTS → `Optional` - IMPORTS → `isObject` # DeepHashedModuleOpaqueKeyFactory **Kind:** Class **Source:** [`packages/core/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.ts#L13) **Part of:** [Core](subsystem-packages-core) `DeepHashedModuleOpaqueKeyFactory` creates stable opaque keys used by the NestJS container to identify module instances. Static modules receive a key based on a cached module ID and name, while dynamic modules include deeply serialized metadata and a hash so differently configured instances remain distinct. **Implements:** `ModuleOpaqueKeyFactory` ## Methods | Method | Signature | Returns | |---|---|---| | `createForStatic` | `createForStatic(moduleCls: Type)` | `string` | | `createForDynamic` | `createForDynamic(moduleCls: Type, dynamicMetadata: Omit)` | `string` | | `getStringifiedOpaqueToken` | `getStringifiedOpaqueToken(opaqueToken: object | undefined)` | `string` | | `getModuleId` | `getModuleId(metatype: Type)` | `string` | | `getModuleName` | `getModuleName(metatype: Type)` | `string` | ## Where it refuses work - `DeepHashedModuleOpaqueKeyFactory` stops the work with an early return when `this.moduleTokenCache.has(key)`. - `DeepHashedModuleOpaqueKeyFactory` stops the work with an early return when `moduleId`. - `DeepHashedModuleOpaqueKeyFactory` stops the work with an early return when `isClass`. - `DeepHashedModuleOpaqueKeyFactory` stops the work with an early return when `isSymbol(value)`. ## Diagram ```mermaid graph LR A[Module class] --> B[getModuleId] A --> C[getModuleName] B --> D[Static module key] C --> D E[Dynamic module metadata] --> F[getStringifiedOpaqueToken] B --> G[Opaque token] C --> G E --> G G --> F F --> H[Hash] H --> I[Dynamic module key] ``` ## Usage ```ts import { DeepHashedModuleOpaqueKeyFactory } from '@nestjs/core/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory'; class FeatureModule {} const keyFactory = new DeepHashedModuleOpaqueKeyFactory(); // Produces a stable key for this module class during the factory lifetime. const staticKey = keyFactory.createForStatic(FeatureModule); // Produces a hash that includes dynamic module configuration. const dynamicKey = keyFactory.createForDynamic(FeatureModule, { providers: [{ provide: 'FEATURE_OPTIONS', useValue: { enabled: true } }], exports: ['FEATURE_OPTIONS'], }); console.log({ staticKey, dynamicKey }); ``` ## AI Coding Instructions - Use `createForStatic()` for regular module classes and `createForDynamic()` whenever module metadata affects container identity. - Preserve the cached module ID behavior; generating a new ID per call would prevent equivalent module references from resolving consistently. - Ensure dynamic metadata is serializable through the factory’s opaque-token stringification logic; functions and symbols require consistent representations. - Do not rely on generated opaque keys as public application identifiers; they are internal container keys and may change between process runs. - When extending module metadata, include identity-relevant configuration so distinct dynamic module registrations produce distinct keys. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Type` - IMPORTS → `Logger` - IMPORTS → `randomStringGenerator` - IMPORTS → `isFunction` - IMPORTS → `isSymbol` # PipesConsumer **Kind:** Class **Source:** [`packages/core/pipes/pipes-consumer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/pipes/pipes-consumer.ts#L5) **Part of:** [Core](subsystem-packages-core) `PipesConsumer` is NestJS core infrastructure that executes a sequence of `PipeTransform` instances against an argument value. It applies pipes in declaration order, passing each transformed result to the next pipe along with normalized argument metadata. ## Methods | Method | Signature | Returns | |---|---|---| | `apply` | `apply(value: TInput, { metatype, type, data }: ArgumentMetadata, pipes: PipeTransform[])` | `void` | | `applyPipes` | `applyPipes(value: TInput, { metatype, type, data }: { metatype: any; type?: any; data?: any }, transforms: PipeTransform[])` | `void` | ## Diagram ```mermaid graph LR A[Route argument value] --> B[PipesConsumer.apply] B --> C[Normalize ArgumentMetadata] C --> D[applyPipes] D --> E[Pipe 1 transform] E --> F[Pipe 2 transform] F --> G[Additional pipes] G --> H[Transformed value] ``` ## Usage ```ts import { PipeTransform, ArgumentMetadata } from '@nestjs/common'; import { PipesConsumer } from '@nestjs/core/pipes/pipes-consumer'; class TrimPipe implements PipeTransform { transform(value: string, metadata: ArgumentMetadata): string { if (metadata.type === 'body' && typeof value === 'string') { return value.trim(); } return value; } } async function transformInput() { const pipesConsumer = new PipesConsumer(); const result = await pipesConsumer.apply( ' NestJS ', { type: 'body', data: undefined, metatype: String, }, [new TrimPipe()], ); console.log(result); // "NestJS" } ``` ## AI Coding Instructions - Preserve sequential pipe execution: every pipe must receive the resolved output of the previous pipe. - Use `apply()` when working with Nest route argument metadata; it normalizes route parameter types before calling `applyPipes()`. - Ensure custom pipes implement `PipeTransform` and return either a transformed value or a `Promise` resolving to one. - Do not bypass pipe errors; validation and transformation exceptions should propagate to Nest’s exception handling flow. - Treat `PipesConsumer` as core framework infrastructure; application code should usually configure pipes with decorators or global pipe registration instead of invoking it directly. ## How it works ## `PipesConsumer` `PipesConsumer` is a core class that runs an input value through an ordered array of `PipeTransform` instances, passing argument metadata to every transform. Its `apply()` method accepts framework route-parameter metadata, while `applyPipes()` accepts metadata with a direct `type` value. [packages/core/pipes/pipes-consumer.ts:5-28] ## Relationships - IMPORTS → `RouteParamtypes` - IMPORTS → `ArgumentMetadata` - IMPORTS → `PipeTransform` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `MicroservicesModule` — `packages/microservices/microservices-module.ts`:23 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `SocketModule` — `packages/websockets/socket-module.ts`:27 # SseStream **Kind:** Class **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L75) **Part of:** [Core](subsystem-packages-core) Adapted from https://raw.githubusercontent.com/EventSource/node-ssestream Transforms "messages" to W3C event stream content. See https://html.spec.whatwg.org/multipage/server-sent-events.html A message is an object with one or more of the following properties: - data (String or object, which gets turned into JSON) - type - id - retry - comment If constructed with a HTTP Request, it will optimise the socket for streaming. If this stream is piped to an HTTP Response, it will set appropriate headers. `SseStream` is a transform stream that converts message objects into W3C Server-Sent Events (SSE) wire-format payloads. It can optimize an incoming HTTP request for streaming and configures appropriate response headers when piped to an HTTP response. **Extends:** `Transform` ## Methods | Method | Signature | Returns | |---|---|---| | `pipe` | `pipe(destination: T, options: { additionalHeaders?: AdditionalHeaders; statusCode?: number; end?: boolean; })` | `T` | | `commitHeaders` | `commitHeaders()` | `void` | | `_transform` | `_transform(message: MessageEvent, encoding: string, callback: (error?: Error | null, data?: any) => void)` | `void` | | `writeMessage` | `writeMessage(message: MessageEvent, cb: (error: Error | null | undefined) => void)` | `void` | ## Where it refuses work - `SseStream` stops the work with an early return when `this._headersCommitted || !this._destination`. - `SseStream` stops the work with an early return when `this._destination.writableEnded`. ## Diagram ```mermaid graph LR A[HTTP Request] --> B[SseStream] C[Message objects
data, type, id, retry, comment] --> B B -->|Formats as SSE frames| D[HTTP Response] D --> E[EventSource client] ``` ## AI Coding Instructions - Write message objects to the stream using standard stream APIs such as `stream.write({ data, type, id })`. - Use `data` for strings or JSON-serializable objects; objects are serialized to JSON before being sent to clients. - Pipe the stream directly to the HTTP response so `SseStream` can apply the required SSE response headers. - Construct the stream with the request when available to enable request socket optimizations for long-lived connections. - Handle request or response closure and call `end()` to avoid retaining SSE streams after clients disconnect. # SettlementSignal **Kind:** Class **Source:** [`packages/core/injector/settlement-signal.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/settlement-signal.ts#L6) **Part of:** [Core](subsystem-packages-core) SettlementSignal is used to signal the resolution of a provider/instance. Calling `complete` or `error` will resolve the promise returned by `asPromise`. Can be used to detect circular dependencies. `SettlementSignal` coordinates the lifecycle of a provider or instance while it is being resolved by the injector. Calling `complete()` or `error()` settles the promise returned by `asPromise()`, while reference tracking through `insertRef()` and `isCycle()` helps identify circular dependencies. ## Methods | Method | Signature | Returns | |---|---|---| | `complete` | `complete()` | `void` | | `error` | `error(err: unknown)` | `void` | | `asPromise` | `asPromise()` | `void` | | `insertRef` | `insertRef(wrapperId: string)` | `void` | | `isCycle` | `isCycle(wrapperId: string)` | `void` | ## Diagram ```mermaid graph LR Injector[Injector resolving provider] --> Signal[SettlementSignal] Signal --> Promise[asPromise()] Signal -->|complete()| Resolved[Provider resolved] Signal -->|error()| Failed[Provider resolution failed] Signal -->|insertRef()| References[Resolution references] References -->|isCycle()| Cycle[Circular dependency detected] ``` ## Usage ```ts import { SettlementSignal } from "./settlement-signal"; async function resolveProvider() { const signal = new SettlementSignal(); const resolution = signal.asPromise(); try { // Create and initialize the provider instance. const instance = { connected: true }; signal.complete(); await resolution; return instance; } catch (error) { signal.error(); throw error; } } ``` ## AI Coding Instructions - Create a `SettlementSignal` for each in-progress provider or instance resolution that must be observed asynchronously. - Call `complete()` only after the provider has been fully constructed and initialized. - Call `error()` when resolution fails so consumers awaiting `asPromise()` are unblocked. - Use `insertRef()` while traversing dependency references, then check `isCycle()` before continuing resolution. - Avoid awaiting `asPromise()` from a dependency path that has already been identified as circular. # ContextIdFactory **Kind:** Class **Source:** [`packages/core/helpers/context-id-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-id-factory.ts#L43) **Part of:** [Core](subsystem-packages-core) `ContextIdFactory` creates and resolves context identifiers used to scope dependency injection instances to a specific request or custom execution context. It supports generating standalone IDs, reusing IDs attached to requests, and applying a custom context ID strategy for advanced transports or multi-tenant workflows. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create()` | `ContextId` | | `getByRequest` | `getByRequest(request: T, propsToInspect: string[])` | `ContextId` | | `apply` | `apply(strategy: ContextIdStrategy)` | `void` | ## Where it refuses work - `ContextIdFactory` stops the work with an early return when `!request`. - `ContextIdFactory` stops the work with an early return when `request[REQUEST_CONTEXT_ID as any]`. - `ContextIdFactory` stops the work with an early return when `request[key]?.[REQUEST_CONTEXT_ID]`. - `ContextIdFactory` stops the work with an early return when `!this.strategy`. ## Diagram ```mermaid graph LR A[Incoming request or custom context] --> B[ContextIdFactory.getByRequest] B --> C{Context ID already attached?} C -->|Yes| D[Reuse existing ContextId] C -->|No| E[ContextIdFactory.create] E --> F[New ContextId] F --> G[Request-scoped provider resolution] D --> G H[ContextIdFactory.apply] --> I[Custom ContextIdStrategy] I --> B ``` ## Usage ```ts import { ContextIdFactory, ModuleRef } from '@nestjs/core'; import { UsersService } from './users.service'; async function resolveRequestScopedService( request: Request, moduleRef: ModuleRef, ) { // Reuses the request context ID when one exists, or creates a new one. const contextId = ContextIdFactory.getByRequest(request); const usersService = await moduleRef.resolve(UsersService, contextId); return usersService; } // Create an isolated context for background jobs or tests. const jobContextId = ContextIdFactory.create(); ``` ## AI Coding Instructions - Use `getByRequest(request)` when resolving request-scoped providers so providers share the same lifecycle within one request. - Use `create()` for non-HTTP execution paths such as queue jobs, scheduled tasks, tests, or manually managed scopes. - Resolve scoped dependencies through `ModuleRef.resolve(provider, contextId)` with the same context ID throughout the operation. - Apply a custom strategy with `ContextIdFactory.apply()` only when integrating custom transports or parent-child context behavior; ensure the strategy is initialized during application bootstrap. - Avoid creating a new context ID repeatedly during a single request, as this produces separate instances of request-scoped providers. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 # MiddlewareBuilder **Kind:** Class **Source:** [`packages/core/middleware/builder.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/builder.ts#L17) **Part of:** [Core](subsystem-packages-core) `MiddlewareBuilder` collects middleware registrations and converts them into normalized `MiddlewareConfiguration` entries for the framework’s middleware pipeline. It exposes a fluent `apply()` API through `MiddlewareConfigProxy`, while `build()` returns the accumulated configurations and `getHttpAdapter()` provides access to the underlying HTTP server adapter. **Implements:** `MiddlewareConsumer` ## Methods | Method | Signature | Returns | |---|---|---| | `apply` | `apply(middleware: Array | Function | Array | Function>>)` | `MiddlewareConfigProxy` | | `build` | `build()` | `MiddlewareConfiguration[]` | | `getHttpAdapter` | `getHttpAdapter()` | `HttpServer` | ## Where it refuses work - `MiddlewareBuilder` stops the work with an early return when `route.method !== item.method`. ## Diagram ```mermaid graph LR A[Application Module] --> B[MiddlewareBuilder] B -->|apply(...middleware)| C[MiddlewareConfigProxy] C -->|forRoutes / exclude| D[MiddlewareConfiguration] B -->|build()| E[MiddlewareConfiguration[]] B -->|getHttpAdapter()| F[HttpServer] E --> G[Middleware Pipeline] F --> G ``` ## Usage ```ts import { MiddlewareBuilder } from '@nestjs/core/middleware/builder'; import { RoutesMapper } from '@nestjs/core/middleware/routes-mapper'; // Typically created and used internally by the framework. const builder = new MiddlewareBuilder( new RoutesMapper(container, applicationConfig), httpAdapter, ); builder .apply(LoggerMiddleware, AuthenticationMiddleware) .exclude('health') .forRoutes('users'); const middlewareConfigurations = builder.build(); // The HTTP adapter used to register middleware with the server. const adapter = builder.getHttpAdapter(); ``` ## AI Coding Instructions - Use `apply()` as the entry point for registering one or more middleware classes/functions; route selection is configured through the returned `MiddlewareConfigProxy`. - Call `build()` only after all middleware registrations are complete, since it returns the builder’s accumulated configuration list. - Preserve middleware ordering: configurations are processed in registration order, so avoid rearranging stored entries without considering execution order. - Use `getHttpAdapter()` when integration code needs server-specific middleware behavior; avoid coupling configuration-building logic directly to a specific HTTP platform. - Keep route mapping and exclusion logic delegated to `MiddlewareConfigProxy` and route-mapping utilities rather than duplicating route normalization in the builder. ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `MiddlewareConsumer` - IMPORTS → `Type` - IMPORTS → `MiddlewareConfigProxy` - IMPORTS → `MiddlewareConfiguration` - IMPORTS → `RouteInfo` - IMPORTS → `stripEndSlash` # InstanceLoader **Kind:** Class **Source:** [`packages/core/injector/instance-loader.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-loader.ts#L11) **Part of:** [Core](subsystem-packages-core) `InstanceLoader` coordinates the creation of provider, controller, and injectable instances for modules registered in the dependency injection container. During application bootstrap, it delegates dependency resolution to the injector and can report initialization progress through a configured logger. ## Methods | Method | Signature | Returns | |---|---|---| | `setLogger` | `setLogger(logger: Logger)` | `void` | | `createInstancesOfDependencies` | `createInstancesOfDependencies(modules: Map)` | `void` | ## When something fails - `InstanceLoader` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[InstanceLoader] B --> C[Container Modules] B --> D[Injector] B --> E[Logger] C --> F[Providers] C --> G[Injectables] C --> H[Controllers] D --> F D --> G D --> H ``` ## Usage ```ts import { InstanceLoader } from '@nestjs/core/injector/instance-loader'; import { Injector } from '@nestjs/core/injector/injector'; // Typically created internally by the Nest application bootstrap process. const instanceLoader = new InstanceLoader( container, new Injector(), graphInspector, ); instanceLoader.setLogger(logger); // Resolves and creates providers, injectables, and controllers // for all modules in the container. await instanceLoader.createInstancesOfDependencies(); ``` ## AI Coding Instructions - Treat `InstanceLoader` as a bootstrap-level internal service; application code should normally rely on Nest's standard application factory instead of constructing it directly. - Ensure modules are registered in the container before calling `createInstancesOfDependencies()`. - Preserve the dependency creation order: providers and injectables must be available before controllers are instantiated. - Use `setLogger()` to integrate bootstrap progress reporting without coupling instance creation logic to a specific logger implementation. - Keep dependency resolution delegated to `Injector`; avoid adding direct constructor-resolution logic to `InstanceLoader`. ## Relationships - IMPORTS → `Logger` - IMPORTS → `LoggerService` - IMPORTS → `Controller` - IMPORTS → `Injectable` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingInstanceLoader` — `packages/testing/testing-instance-loader.ts`:6 # LazyModuleLoader **Kind:** Class **Source:** [`packages/core/injector/lazy-module-loader/lazy-module-loader.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/lazy-module-loader/lazy-module-loader.ts#L12) **Part of:** [Core](subsystem-packages-core) `LazyModuleLoader` loads Nest modules on demand instead of during application bootstrap. It creates and registers a module dynamically, returning a `ModuleRef` that can be used to resolve providers from the loaded module. ## Methods | Method | Signature | Returns | |---|---|---| | `load` | `load(loaderFn: () => | Promise | DynamicModule> | Type | DynamicModule, loadOpts: LazyModuleLoaderLoadOptions)` | `Promise` | ## Diagram ```mermaid graph LR A[Application Service] --> B[LazyModuleLoader] B --> C[load module factory] C --> D[Dynamic Module Import] D --> E[ModuleRef] E --> F[Resolve Module Providers] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { LazyModuleLoader } from '@nestjs/core'; import { ReportsService } from './reports.service'; @Injectable() export class DashboardService { constructor(private readonly lazyModuleLoader: LazyModuleLoader) {} async loadReports() { const moduleRef = await this.lazyModuleLoader.load(() => import('./reports/reports.module').then(({ ReportsModule }) => ReportsModule), ); const reportsService = moduleRef.get(ReportsService); return reportsService.getSummary(); } } ``` ## AI Coding Instructions - Inject `LazyModuleLoader` from `@nestjs/core` into a provider; do not instantiate it manually. - Pass a loader callback to `load()` so the module is imported only when it is needed. - Return the module class or dynamic module definition from the loader callback, typically using `import(...).then(...)`. - Use the returned `ModuleRef` to retrieve providers registered by the lazy-loaded module. - Ensure providers needed from the loaded module are declared or exported correctly within that module. ## How it works `LazyModuleLoader` is a class that asynchronously loads a module class or dynamic-module definition into the Nest module container and returns that module’s `ModuleRef`. Its constructor receives a `DependenciesScanner`, `InstanceLoader`, `ModuleCompiler`, `ModulesContainer`, and optional module overrides. [`lazy-module-loader.ts:12-19`](packages/core/injector/lazy-module-loader/lazy-module-loader.ts#L12-L19) ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Type` ## Used by 3 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Injected or called by (1) - `LazyController` — `integration/lazy-modules/src/lazy.controller.ts`:4 ### Imported by (2) - `AppModule` — `integration/lazy-modules/src/app.module.ts`:7 - `LazyController` — `integration/lazy-modules/src/lazy.controller.ts`:4 # InstanceLinksHost **Kind:** Class **Source:** [`packages/core/injector/instance-links-host.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-links-host.ts#L17) **Part of:** [Core](subsystem-packages-core) `InstanceLinksHost` is Nest’s internal registry for locating provider instance links across the application’s modules. It indexes providers by injection token and returns the corresponding `InstanceLink`, which contains the resolved instance, wrapper metadata, and owning module context. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(token: InjectionToken)` | `InstanceLink` | | `get` | `get(token: InjectionToken, options: { moduleId?: string; each?: boolean })` | `InstanceLink | Array>` | | `get` | `get(token: InjectionToken, options: { moduleId?: string; each?: boolean })` | `InstanceLink | Array>` | ## Where it refuses work - `InstanceLinksHost` stops the work with `UnknownElementException` when `!instanceLinksForGivenToken`. - `InstanceLinksHost` stops the work with `UnknownElementException` when `!instanceLink`. - `InstanceLinksHost` stops the work with an early return when `options.each`. ## Diagram ```mermaid graph LR Container[NestContainer] --> Modules[Registered Modules] Modules --> Providers[Provider Wrappers] Providers --> Links[InstanceLink entries] Links --> Host[InstanceLinksHost] Token[Injection Token] --> Host Host --> Result[InstanceLink / InstanceLink[]] ``` ## Usage ```ts import { InstanceLinksHost } from '@nestjs/core/injector/instance-links-host'; import { NestContainer } from '@nestjs/core/injector/container'; import { CatsService } from './cats.service'; // Nest normally creates and manages these internal objects. const container = new NestContainer(); const instanceLinksHost = new InstanceLinksHost(container); // Look up the provider link registered for a token. const link = instanceLinksHost.get(CatsService); // The link exposes the resolved provider instance and wrapper metadata. const catsService = link.instance as CatsService; catsService.findAll(); ``` ## AI Coding Instructions - Treat `InstanceLinksHost` as internal Nest injector infrastructure; prefer public APIs such as `ModuleRef` or `app.get()` in application code. - Use the same injection token used during provider registration when calling `get()`, including class constructors, strings, symbols, or custom tokens. - Handle missing tokens carefully: lookups for unregistered providers can throw an unknown-element error. - Remember that a token may exist in multiple modules; use the appropriate lookup mode when integration code needs every matching `InstanceLink`. - Do not mutate returned link metadata or provider wrappers, because they are shared by Nest’s dependency-injection container. # UNKNOWN_DEPENDENCIES_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L63) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function UNKNOWN_DEPENDENCIES_MESSAGE(type: string | symbol, unknownDependencyContext: InjectorDependencyContext, moduleRef: Module | undefined) ``` ## Parameters | Name | Type | |---|---| | `type` | `string | symbol` | | `unknownDependencyContext` | `InjectorDependencyContext` | | `moduleRef` | `Module | undefined` | ## Relationships - IMPORTS → `isNil` - IMPORTS → `isSymbol` # Barrier **Kind:** Class **Source:** [`packages/core/helpers/barrier.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/barrier.ts#L4) **Part of:** [Core](subsystem-packages-core) A simple barrier to synchronize flow of multiple async operations. `Barrier` synchronizes multiple asynchronous operations at a shared checkpoint. Call `signal()` when an operation reaches the barrier, and use `wait()` to pause until the required signals have been received; `signalAndWait()` performs both steps atomically for participating operations. ## Methods | Method | Signature | Returns | |---|---|---| | `signal` | `signal()` | `void` | | `wait` | `wait()` | `Promise` | | `signalAndWait` | `signalAndWait()` | `Promise` | ## Diagram ```mermaid graph LR A[Async operation A] -->|signal / signalAndWait| B[Barrier] C[Async operation B] -->|signal / signalAndWait| B D[Async operation C] -->|signal / signalAndWait| B B -->|all participants signaled| E[Release waiting operations] ``` ## Usage ```ts import { Barrier } from '@your-package/core/helpers/barrier'; const barrier = new Barrier(2); async function worker(name: string) { console.log(`${name} reached the checkpoint`); await barrier.signalAndWait(); console.log(`${name} continues after the checkpoint`); } await Promise.all([ worker('worker-a'), worker('worker-b'), ]); ``` ## AI Coding Instructions - Create a `Barrier` with the number of async participants expected to reach the synchronization point. - Prefer `signalAndWait()` when a participant should both register its arrival and wait for all other participants. - Use `signal()` only for operations that should notify the barrier without blocking themselves. - Ensure every expected participant signals the barrier; otherwise, calls to `wait()` can remain pending indefinitely. - Use barriers for deterministic coordination between concurrent tasks, not as a replacement for error handling or cancellation logic. # MiddlewareContainer **Kind:** Class **Source:** [`packages/core/middleware/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/container.ts#L8) **Part of:** [Core](subsystem-packages-core) `MiddlewareContainer` stores middleware providers and their route-level configurations for the application. It maintains collections keyed by injection token and module key, allowing the middleware runtime to resolve middleware instances and apply configurations during request pipeline setup. ## Methods | Method | Signature | Returns | |---|---|---| | `getMiddlewareCollection` | `getMiddlewareCollection(moduleKey: string)` | `Map` | | `getConfigurations` | `getConfigurations()` | `Map>` | | `insertConfig` | `insertConfig(configList: MiddlewareConfiguration[], moduleKey: string)` | `void` | ## Diagram ```mermaid graph LR Module[Module registration] --> Config[MiddlewareConfiguration] Config --> Insert[MiddlewareContainer.insertConfig] Insert --> ConfigMap["configurations: Map>"] Providers[Middleware providers] --> MiddlewareMap["middleware: Map"] MiddlewareMap --> Resolver[Middleware resolver] ConfigMap --> Resolver Resolver --> Pipeline[HTTP middleware pipeline] ``` ## Usage ```ts import { MiddlewareContainer } from '@nestjs/core/middleware/container'; import { RequestMethod } from '@nestjs/common'; import type { MiddlewareConfiguration } from '@nestjs/common/interfaces/middleware'; const middlewareContainer = new MiddlewareContainer(applicationConfig); const configuration: MiddlewareConfiguration = { middleware: [LoggerMiddleware], forRoutes: [ { path: 'users', method: RequestMethod.ALL, }, ], }; const moduleKey = 'UsersModule'; middlewareContainer.insertConfig([configuration], moduleKey); const configurations = middlewareContainer.getConfigurations(); const userMiddlewareConfigs = configurations.get(moduleKey); console.log(userMiddlewareConfigs); ``` ## AI Coding Instructions - Use `insertConfig()` to add middleware configurations so multiple configuration entries for the same module are preserved in a `Set`. - Treat module keys as stable, unique identifiers; inconsistent keys will create separate configuration groups. - Do not replace the maps returned by `getMiddlewareCollection()` or `getConfigurations()`; consumers depend on the container’s shared collections. - Keep middleware provider registration and route configuration synchronized so each configured middleware can be resolved from its injection token. - When adding configuration behavior, preserve insertion order because middleware execution order can affect request handling. # ModuleCompiler **Kind:** Class **Source:** [`packages/core/injector/compiler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/compiler.ts#L14) **Part of:** [Core](subsystem-packages-core) `ModuleCompiler` normalizes static module classes and `DynamicModule` objects into a compiled `ModuleFactory`. It extracts the module type and dynamic metadata, then creates a stable token used by the injector and module container to register and resolve modules. ## Methods | Method | Signature | Returns | |---|---|---| | `compile` | `compile(moduleClsOrDynamic: | Type | DynamicModule | ForwardReference | Promise)` | `Promise` | | `extractMetadata` | `extractMetadata(moduleClsOrDynamic: Type | ForwardReference | DynamicModule)` | `{ type: Type; dynamicMetadata: Omit | undefined; }` | | `isDynamicModule` | `isDynamicModule(moduleClsOrDynamic: Type | DynamicModule | ForwardReference)` | `moduleClsOrDynamic is DynamicModule` | ## Where it refuses work - `ModuleCompiler` stops the work with an early return when `!this.isDynamicModule(moduleClsOrDynamic)`. ## Diagram ```mermaid graph LR A[Module class or DynamicModule] --> B[ModuleCompiler.compile] B --> C[extractMetadata] C --> D[Module type] C --> E[Dynamic metadata] D --> F[Module token creation] E --> F F --> G[ModuleFactory] ``` ## Usage ```ts import { ModuleCompiler } from '@nestjs/core/injector/compiler'; class AppModule {} const compiler = new ModuleCompiler(); // Compile a standard module class. const staticFactory = await compiler.compile(AppModule); // Compile a dynamic module definition. const dynamicFactory = await compiler.compile({ module: AppModule, providers: [ { provide: 'APP_CONFIG', useValue: { environment: 'production' }, }, ], exports: ['APP_CONFIG'], }); console.log(dynamicFactory.type); // AppModule console.log(dynamicFactory.token); // Generated module token ``` ## AI Coding Instructions - Pass either a module class or a valid `DynamicModule` object containing a `module` property to `compile()`. - Keep dynamic module metadata separate from the `module` class; `extractMetadata()` intentionally removes `module` from `dynamicMetadata`. - Use the generated `ModuleFactory.token` as the module identity when integrating with the container or injector. - Preserve the dynamic-module type guard when extending this class so static and dynamic module inputs remain distinguishable. - Avoid manually generating module tokens; delegate token creation to the compiler and its token factory. ## How it works `ModuleCompiler` converts a module definition into a `ModuleFactory`: the resolved module class (`type`), optional dynamic-module metadata (`dynamicMetadata`), and a string key (`token`). `ModuleFactory` declares those three fields, with `dynamicMetadata` optional. [packages/core/injector/compiler.ts:8-12] # ReplFunction **Kind:** Class **Source:** [`packages/core/repl/repl-function.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-function.ts#L6) **Part of:** [Core](subsystem-packages-core) `ReplFunction` represents an executable function exposed through the core REPL system. It provides the action implementation through `action()` and generates user-facing command documentation through `makeHelpMessage()`. ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action(args: ActionParams)` | `ActionReturn` | | `makeHelpMessage` | `makeHelpMessage()` | `string` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | | `logger` | `Logger` | ## Diagram ```mermaid graph LR User[REPL User] --> Parser[REPL Command Parser] Parser --> Function[ReplFunction] Function --> Help[makeHelpMessage()] Function --> Action[action()] Action --> Result[ActionReturn] Result --> User ``` ## Usage ```ts import { ReplFunction } from "@core/repl/repl-function"; function runReplFunction(replFunction: ReplFunction) { // Display help when the function is requested without valid input. console.log(replFunction.makeHelpMessage()); // Execute the function through the REPL runtime. const result = replFunction.action(); return result; } ``` ## AI Coding Instructions - Keep command execution logic inside `action()` and return the expected `ActionReturn` value for the REPL runtime. - Use `makeHelpMessage()` to provide concise, user-facing guidance for the function's syntax and behavior. - Avoid writing directly to the console from `action()` unless the surrounding REPL conventions require it; prefer returning structured output. - Ensure new REPL functions are registered through the relevant REPL command/function integration point. - Keep help text aligned with the arguments and behavior implemented by `action()`. ## How it works ## `ReplFunction` `ReplFunction` is an abstract base class for a REPL-native function. It is generic over the argument tuple accepted by `action` and its return type; both default to `Array` and `any`, respectively. [repl-function.ts:6-9] A subclass must define: - `fnDefinition`, containing a function `name`, `description`, and `signature`; it may also declare aliases. The interface documents `name` as a valid JavaScript function name and describes `signature` as TypeScript function-type-expression syntax. [repl-function.ts:10-11] [repl.interfaces.ts:4-19] - `action(...args)`, the abstract method called for function invocation from the REPL. [repl-function.ts:19-22] The constructor receives a `ReplContext`, stores it as a protected read-only `ctx`, and assigns `ctx.logger` to a protected read-only `logger`. [repl-function.ts:13-17] Built-in subclasses access `ctx` for application operations and output; for example, `GetReplFn.action` calls `ctx.app.get`, while `DebugReplFn` writes through `ctx.writeToStdout` and reports a missing module through `logger.error`. [native-functions/get-repl-fn.ts:14-16] [native-functions/debug-repl-fn.ts:15-36] ## Relationships - IMPORTS → `Logger` # RouteInfoPathExtractor **Kind:** Class **Source:** [`packages/core/middleware/route-info-path-extractor.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/route-info-path-extractor.ts#L16) **Part of:** [Core](subsystem-packages-core) `RouteInfoPathExtractor` converts middleware `RouteInfo` definitions into concrete path arrays. It normalizes single and multiple route paths and resolves framework-level routing configuration such as global prefixes and versioning before middleware routes are registered. ## Methods | Method | Signature | Returns | |---|---|---| | `extractPathsFrom` | `extractPathsFrom({ path, method, version }: RouteInfo)` | `string[]` | | `extractPathFrom` | `extractPathFrom(route: RouteInfo)` | `string[]` | ## Where it refuses work - `RouteInfoPathExtractor` stops the work with an early return when `!versionPaths.length`, in 2 places. - `RouteInfoPathExtractor` stops the work with an early return when `this.isAWildcard(route.path) && !route.version`. - `RouteInfoPathExtractor` stops the work with an early return when `isSimpleWildcard.includes(path)`. - `RouteInfoPathExtractor` stops the work with an early return when `!versionValue || this.versioningConfig?.type !== VersioningType.URI`. - `RouteInfoPathExtractor` stops the work with an early return when `Array.isArray(versionValue)`. ## Diagram ```mermaid graph LR A[RouteInfo
path, method, version] --> B[RouteInfoPathExtractor] B --> C[extractPathFrom] C --> D[Normalized raw path array] B --> E[extractPathsFrom] E --> F[Configured route paths
prefix/version applied] F --> G[Middleware registration] ``` ## Usage ```ts import { RequestMethod } from '@nestjs/common'; import { ApplicationConfig } from '../application-config'; import { RouteInfoPathExtractor } from './route-info-path-extractor'; const applicationConfig = new ApplicationConfig(); applicationConfig.setGlobalPrefix('api'); const pathExtractor = new RouteInfoPathExtractor(applicationConfig); const route = { path: ['health', 'status'], method: RequestMethod.GET, }; // Normalize the route's declared path value into an array. const declaredPaths = pathExtractor.extractPathFrom(route); // ['health', 'status'] // Resolve paths using application routing configuration. const resolvedPaths = pathExtractor.extractPathsFrom(route); // ['/api/health', '/api/status'] ``` ## AI Coding Instructions - Use `extractPathFrom()` when only normalizing the `RouteInfo.path` value into a string array. - Use `extractPathsFrom()` before registering middleware routes so global prefixes and versioning configuration are consistently applied. - Pass complete `RouteInfo` metadata, including the HTTP method and version when applicable; path resolution may depend on both. - Do not manually prepend global prefixes or version segments before calling `extractPathsFrom()`, as this can produce duplicated route segments. - Keep this class aligned with `ApplicationConfig` and route-path generation behavior when changing middleware routing logic. ## Relationships - IMPORTS → `VersioningType` - IMPORTS → `RouteInfo` - IMPORTS → `VersioningOptions` - IMPORTS → `VersionValue` - IMPORTS → `addLeadingSlash` - IMPORTS → `stripEndSlash` # SilentLogger **Kind:** Class **Source:** [`packages/core/injector/helpers/silent-logger.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/helpers/silent-logger.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `Logger` ## Properties | Property | Type | |---|---| | `log` | `any` | | `error` | `any` | | `warn` | `any` | | `debug` | `any` | | `verbose` | `any` | | `fatal` | `any` | | `setLogLevels` | `any` | ## Relationships - IMPORTS → `Logger` # HandlerMetadataStorage **Kind:** Class **Source:** [`packages/core/helpers/handler-metadata-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/handler-metadata-storage.ts#L44) **Part of:** [Core](subsystem-packages-core) `HandlerMetadataStorage` associates metadata values with handler functions and provides lookup access later in the execution flow. It is useful for preserving handler-specific configuration discovered during registration, decoration, or route setup. ## Methods | Method | Signature | Returns | |---|---|---| | `set` | `set(controller: TKey, methodName: string, metadata: TValue)` | `void` | | `get` | `get(controller: TKey, methodName: string)` | `TValue | undefined` | ## Diagram ```mermaid graph LR A[Handler function] -->|set(handler, metadata)| B[HandlerMetadataStorage] B -->|stores association| C[Metadata value] A -->|get(handler)| B B -->|returns TValue or undefined| D[Consumer / runtime logic] ``` ## Usage ```ts import { HandlerMetadataStorage } from './helpers/handler-metadata-storage'; type HandlerOptions = { requiresAuth: boolean; rateLimit?: number; }; const handlerMetadata = new HandlerMetadataStorage(); function getProfile() { return { id: 'user-123' }; } handlerMetadata.set(getProfile, { requiresAuth: true, rateLimit: 100, }); const options = handlerMetadata.get(getProfile); if (options?.requiresAuth) { // Apply authentication middleware or authorization checks. } console.log(options); // { requiresAuth: true, rateLimit: 100 } ``` ## AI Coding Instructions - Use the same handler reference for both `set()` and `get()`; a different function instance will not resolve the stored metadata. - Treat `get()` results as optional, since it returns `undefined` when no metadata has been registered. - Store small, immutable configuration objects where possible so handler metadata remains predictable across the application lifecycle. - Register metadata during handler setup or discovery, then read it from routing, middleware, or invocation logic. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 # INVALID_MODULE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L156) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function INVALID_MODULE_MESSAGE(parentModule: any, index: number, scope: any[], receivedValue: unknown) ``` ## Parameters | Name | Type | |---|---| | `parentModule` | `any` | | `index` | `number` | | `scope` | `any[]` | | `receivedValue` | `unknown` | # mapToClass **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L57) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function mapToClass(middleware: T, excludedRoutes: ExcludeRouteMetadata[], httpAdapter: HttpServer) ``` ## Parameters | Name | Type | |---|---| | `middleware` | `T` | | `excludedRoutes` | `ExcludeRouteMetadata[]` | | `httpAdapter` | `HttpServer` | # ModulesContainer **Kind:** Class **Source:** [`packages/core/injector/modules-container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/modules-container.ts#L5) **Part of:** [Core](subsystem-packages-core) `ModulesContainer` is the core registry for application modules, storing `Module` instances and providing lookup by module ID. It also publishes RPC-capable instance wrappers through an observable registry so transport-related infrastructure can discover newly registered targets. **Extends:** `Map` ## Methods | Method | Signature | Returns | |---|---|---| | `getById` | `getById(id: string)` | `Module | undefined` | | `getRpcTargetRegistry` | `getRpcTargetRegistry()` | `Observable` | | `addRpcTarget` | `addRpcTarget(target: T)` | `void` | ## Diagram ```mermaid graph LR A[Module registration] --> B[ModulesContainer] B --> C[Map of module tokens to Module instances] C --> D[getById(moduleId)] B --> E[RPC target ReplaySubject] F[addRpcTarget(wrapper)] --> E E --> G[getRpcTargetRegistry()] G --> H[RPC/transport consumers] ``` ## Usage ```ts import { ModulesContainer } from '@nestjs/core/injector/modules-container'; import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; class PaymentsRpcHandler { processPayment() { return { status: 'accepted' }; } } const modules = new ModulesContainer(); // Subscribe before or after targets are registered. // The underlying replay-based registry can expose previously added targets. const subscription = modules.getRpcTargetRegistry().subscribe((target) => { console.log(`Discovered RPC target: ${String(target.token)}`); }); const paymentsTarget = new InstanceWrapper({ token: PaymentsRpcHandler, name: PaymentsRpcHandler.name, metatype: PaymentsRpcHandler, }); modules.addRpcTarget(paymentsTarget); // Module IDs are distinct from the container's map keys. const module = modules.getById('module-id'); console.log(module?.metatype?.name); subscription.unsubscribe(); ``` ## AI Coding Instructions - Treat `ModulesContainer` as framework infrastructure; prefer interacting with it through Nest's injector and application lifecycle rather than manually constructing module entries in application code. - Use `getById()` when matching Nest module IDs; do not assume the `Map` key is the same as `Module.id`. - Register only valid `InstanceWrapper` objects through `addRpcTarget()` so RPC consumers receive the metadata they expect. - Subscribe to `getRpcTargetRegistry()` when integrating transport or RPC discovery logic, and dispose subscriptions when the consumer is destroyed. - Preserve the observable-based registration flow instead of replacing it with direct polling of module collections. # ByReferenceModuleOpaqueKeyFactory **Kind:** Class **Source:** [`packages/core/injector/opaque-key-factory/by-reference-module-opaque-key-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/opaque-key-factory/by-reference-module-opaque-key-factory.ts#L10) **Part of:** [Core](subsystem-packages-core) `ByReferenceModuleOpaqueKeyFactory` creates opaque string keys for module definitions using their object reference identity. It provides separate key generation paths for static modules and dynamic modules, allowing the injector to distinguish module registrations without relying on module names alone. **Implements:** `ModuleOpaqueKeyFactory` ## Methods | Method | Signature | Returns | |---|---|---| | `createForStatic` | `createForStatic(moduleCls: Type, originalRef: Type | ForwardReference)` | `string` | | `createForDynamic` | `createForDynamic(moduleCls: Type, dynamicMetadata: Omit, originalRef: DynamicModule | ForwardReference)` | `string` | ## Where it refuses work - `ByReferenceModuleOpaqueKeyFactory` stops the work with an early return when `originalRef[K_MODULE_ID]`. ## Diagram ```mermaid graph LR A[Module Definition] --> B[ByReferenceModuleOpaqueKeyFactory] B --> C{Module Type} C -->|Static| D[createForStatic] C -->|Dynamic| E[createForDynamic] D --> F[Static Opaque Key] E --> G[Dynamic Opaque Key] F --> H[Injector Module Registry] G --> H ``` ## Usage ```ts import { ByReferenceModuleOpaqueKeyFactory } from './by-reference-module-opaque-key-factory'; const opaqueKeyFactory = new ByReferenceModuleOpaqueKeyFactory(); const staticModuleKey = opaqueKeyFactory.createForStatic(); const dynamicModuleKey = opaqueKeyFactory.createForDynamic(); console.log(staticModuleKey); console.log(dynamicModuleKey); // Store the generated keys when registering modules in an injector registry. const moduleRegistry = new Map(); moduleRegistry.set(staticModuleKey, StaticModule); moduleRegistry.set(dynamicModuleKey, dynamicModuleDefinition); ``` ## AI Coding Instructions - Use `createForStatic()` when registering a standard module definition and `createForDynamic()` for dynamically configured module instances. - Treat returned keys as opaque identifiers; do not parse, manually construct, or depend on their string format. - Preserve reference-based identity semantics when changing this factory or its callers, since injector module deduplication depends on unique keys. - Ensure static and dynamic module registration paths continue to use their respective factory methods to avoid key collisions. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `Type` - IMPORTS → `randomStringGenerator` # DebugReplFn **Kind:** Class **Source:** [`packages/core/repl/native-functions/debug-repl-fn.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/native-functions/debug-repl-fn.ts#L7) **Part of:** [Core](subsystem-packages-core) `DebugReplFn` is a native REPL function that provides a debug-oriented command within the core REPL environment. Its `action()` method performs the command's behavior when the function is invoked by the REPL command dispatcher. **Extends:** `ReplFunction` ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action(moduleCls: Type | string)` | `void` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | ## Where it refuses work - `DebugReplFn` stops the work with an early return when `!moduleEntry`. - `DebugReplFn` stops the work with an early return when `collectionEntries.length <= 0`. ## Diagram ```mermaid graph LR User[REPL user] --> Parser[REPL command parser] Parser --> Dispatcher[Native function dispatcher] Dispatcher --> DebugReplFn[DebugReplFn] DebugReplFn --> Action[action(): void] Action --> DebugOutput[Debug behavior/output] ``` ## Usage ```ts import { DebugReplFn } from './native-functions/debug-repl-fn'; // Typically invoked by the REPL's native-function dispatcher. const debugCommand = new DebugReplFn(); debugCommand.action(); ``` ## AI Coding Instructions - Keep `action()` focused on the behavior of the debug REPL command; avoid placing command parsing logic in this class. - Integrate `DebugReplFn` through the existing native-function registration and dispatch flow rather than calling it directly from unrelated application code. - Preserve the `void` return contract of `action()` and route observable results through the REPL's established output or logging mechanisms. - Treat this function as a developer-facing REPL capability; avoid exposing sensitive runtime state unless the surrounding debug conventions explicitly allow it. # ExceptionsHandler **Kind:** Class **Source:** [`packages/core/exceptions/exceptions-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/exceptions-handler.ts#L9) **Part of:** [Core](subsystem-packages-core) `ExceptionsHandler` coordinates exception processing for a request or execution context. It first attempts to match and invoke registered custom exception filters, then falls back to the base exception filter when no custom filter handles the error. **Extends:** `BaseExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `next` | `next(exception: Error | HttpException, ctx: ArgumentsHost)` | `void` | | `setCustomFilters` | `setCustomFilters(filters: ExceptionFilterMetadata[])` | `void` | | `invokeCustomFilters` | `invokeCustomFilters(exception: T, ctx: ArgumentsHost)` | `boolean` | ## Where it refuses work - `ExceptionsHandler` stops the work with `InvalidExceptionFilterException` when `!Array.isArray(filters)`. - `ExceptionsHandler` stops the work with an early return when `this.invokeCustomFilters(exception, ctx)`. - `ExceptionsHandler` stops the work with an early return when `isEmpty(this.filters)`. ## Diagram ```mermaid graph LR A[Exception thrown] --> B[ExceptionsHandler.next] B --> C{Custom filter matches?} C -->|Yes| D[invokeCustomFilters] D --> E[Custom filter response] C -->|No| F[BaseExceptionFilter.catch] F --> G[Default error response] ``` ## Usage ```ts import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common'; import { HttpAdapterHost } from '@nestjs/core'; import { ExceptionsHandler } from '@nestjs/core/exceptions/exceptions-handler'; class DomainError extends Error {} @Catch(DomainError) class DomainErrorFilter implements ExceptionFilter { catch(exception: DomainError, host: ArgumentsHost) { const response = host.switchToHttp().getResponse(); response.status(400).json({ statusCode: 400, message: exception.message, }); } } const { httpAdapter } = app.get(HttpAdapterHost); const exceptionsHandler = new ExceptionsHandler(httpAdapter); const filter = new DomainErrorFilter(); exceptionsHandler.setCustomFilters([ { exceptionMetatypes: [DomainError], func: filter.catch.bind(filter), }, ]); // Typically called internally by Nest when an exception occurs. exceptionsHandler.next(new DomainError('Invalid domain input'), argumentsHost); ``` ## AI Coding Instructions - Register custom filters through `setCustomFilters()` using `exceptionMetatypes` and a correctly bound `func` callback. - Call `next()` to preserve the normal handling flow; it invokes matching custom filters before using the default exception response behavior. - Ensure custom filter callbacks preserve their `this` context, such as with `filter.catch.bind(filter)`. - Return control from a custom filter only after writing an appropriate response for the active transport context. - Treat `ExceptionsHandler` as framework infrastructure; prefer Nest’s `@UseFilters()` and `@Catch()` APIs for most application-level exception handling. ## How it works - `ExceptionsHandler` is an exported HTTP exception handler that extends `BaseExceptionFilter`. It keeps a private array of custom `ExceptionFilterMetadata`, initially empty. [packages/core/exceptions/exceptions-handler.ts:9-10] - `next(exception, ctx)` first attempts custom-filter handling. If a matching custom filter is found, it returns without invoking the inherited fallback; otherwise, it calls `BaseExceptionFilter.catch(exception, ctx)`. [packages/core/exceptions/exceptions-handler.ts:12-17] - The fallback treats `HttpException` instances differently from other values: it obtains the exception response, sends it through the HTTP adapter when headers have not already been sent, or ends the response otherwise. [packages/core/exceptions/base-exception-filter.ts:26-47] For non-`HttpException` values, it sends either an error object’s `statusCode` and `message`, or a 500 response with the unknown-exception message; it logs non-`IntrinsicException` values. [packages/core/exceptions/base-exception-filter.ts:50-75] - `setCustomFilters(filters)` requires `filters` to be an array. A non-array value throws `InvalidExceptionFilterException`; an array replaces the handler’s current filter array. [packages/core/exceptions/exceptions-handler.ts:19-24] That exception extends `RuntimeException` and has the message `Invalid exception filters (@UseFilters()).`. [packages/core/errors/exceptions/invalid-exception-filter.exception.ts:4-7] [packages/core/errors/messages.ts:262] - `invokeCustomFilters(exception, ctx)` returns `false` when its filter array has no elements. [packages/core/exceptions/exceptions-handler.ts:26-32] Otherwise, it selects the first metadata entry whose `exceptionMetatypes` array is empty or contains a type for which `exception instanceof ExceptionMetaType` is true. [packages/common/utils/select-exception-filter-metadata.util.ts:3-13] When selected, it calls that entry’s `func(exception, ctx)` and returns `true`; when none match, it returns `false`. [packages/core/exceptions/exceptions-handler.ts:34-36] - Each filter metadata entry contains a `func` callback typed as an exception filter’s `catch` method and an `exceptionMetatypes` array. [packages/common/interfaces/exceptions/exception-filter-metadata.interface.ts:4-7] Filter contexts create these entries by binding an instantiated filter’s `catch` method and reading its reflected caught-exception metadata. [packages/core/exceptions/base-exception-filter-context.ts:26-36] [packages/core/exceptions/base-exception-filter-context.ts:73-77] - In HTTP route setup, `RouterExceptionFilters.create` constructs `ExceptionsHandler` with the HTTP server adapter. If filters exist, it reverses their order before passing them to `setCustomFilters`. [packages/core/router/router-exception-filters.ts:23-44] `RouterProxy` calls `next` after a route callback or exception-layer callback throws, passing an `ExecutionContextHost` containing request, response, and `next`. [packages/core/router/router-proxy.ts:20-26] [packages/core/router/router-proxy.ts:45-51] ## Relationships - IMPORTS → `HttpException` - IMPORTS → `ExceptionFilterMetadata` - IMPORTS → `ArgumentsHost` - IMPORTS → `selectExceptionFilterMetadata` - IMPORTS → `isEmpty` # ExternalExceptionFilterContext **Kind:** Class **Source:** [`packages/core/exceptions/external-exception-filter-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/external-exception-filter-context.ts#L14) **Part of:** [Core](subsystem-packages-core) `ExternalExceptionFilterContext` builds exception handling contexts for externally invoked handlers, such as controllers or gateway endpoints. It resolves local and global exception filters, then creates an `ExternalExceptionsHandler` configured to apply them in the correct order. **Extends:** `BaseExceptionFilterContext` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: RouterProxyCallback, module: string, contextId: undefined, inquirerId: string)` | `ExternalExceptionsHandler` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: undefined, inquirerId: string)` | `T` | ## Where it refuses work - `ExternalExceptionFilterContext` stops the work with an early return when `isEmpty(filters)`. - `ExternalExceptionFilterContext` stops the work with an early return when `!this.config`. - `ExternalExceptionFilterContext` stops the work with an early return when `contextId === STATIC_CONTEXT && !inquirerId`. ## Diagram ```mermaid graph LR A[External Handler Callback] --> B[ExternalExceptionFilterContext] B --> C[Resolve Method and Class Filters] B --> D[Read Global Filter Metadata] C --> E[ExternalExceptionsHandler] D --> E E --> F[Handle Thrown Exceptions] ``` ## Usage ```ts import { ExternalExceptionFilterContext } from '@nestjs/core/exceptions/external-exception-filter-context'; // Typically created and used internally by the Nest runtime. const exceptionFilterContext = new ExternalExceptionFilterContext( container, applicationConfig, ); // Create an exception handler for a controller method. const exceptionHandler = exceptionFilterContext.create( usersController, usersController.findOne, moduleRef, ); // Inspect globally configured exception filters when needed. const globalFilters = exceptionFilterContext.getGlobalMetadata(); // Use the generated handler when invoking the external callback. try { await usersController.findOne('123'); } catch (error) { await exceptionHandler.next(error, host); } ``` ## AI Coding Instructions - Use `create()` to generate a dedicated `ExternalExceptionsHandler` for each external callback context rather than reusing handlers across unrelated routes or handlers. - Preserve filter ordering: the context resolves and reverses applicable filters so method-, class-, and global-level filters execute as expected. - Use `getGlobalMetadata()` when extending filter resolution behavior; account for both static global filters and request-scoped global filters. - Treat this class as framework infrastructure: application code should generally configure filters through Nest APIs such as `useGlobalFilters()` or `@UseFilters()`. ## How it works `ExternalExceptionFilterContext` is an exception-filter context builder for externally created handlers. It extends `BaseExceptionFilterContext`, accepts a `NestContainer` and optional `ApplicationConfig`, and passes the container to its base class. [packages/core/exceptions/external-exception-filter-context.ts:14-20](packages/core/exceptions/external-exception-filter-context.ts#L14-L20) ## `create()` `create(instance, callback, module, contextId?, inquirerId?)` stores `module` as the inherited `moduleContext`, creates an `ExternalExceptionsHandler`, resolves exception-filter metadata for the supplied controller instance and callback, and returns that handler. [packages/core/exceptions/external-exception-filter-context.ts:22-43](packages/core/exceptions/external-exception-filter-context.ts#L22-L43) The resolved metadata combines global filters, controller-class filters, and callback-method filters in that order through `ContextCreator.createContext()`. [packages/core/helpers/context-creator.ts:16-40](packages/core/helpers/context-creator.ts#L16-L40) It reads class metadata from the instance prototype’s constructor and method metadata from the callback, using the `EXCEPTION_FILTERS_METADATA` key passed by `create()`. [packages/core/exceptions/external-exception-filter-context.ts:32-38](packages/core/exceptions/external-exception-filter-context.ts#L32-L38) [packages/core/helpers/context-creator.ts:43-52](packages/core/helpers/context-creator.ts#L43-L52) Before assigning resolved filters to the handler, `create()` reverses their array. If the resolved array is empty, it returns the new handler without assigning custom filters. [packages/core/exceptions/external-exception-filter-context.ts:31-43](packages/core/exceptions/external-exception-filter-context.ts#L31-L43) Inherited filter resolution accepts an object with a `catch` function or a class/function with a name; it discards other entries. For objects, it uses the object directly. For classes, it looks up an injectable in the stored module and gets its instance for the supplied context and inquirer IDs; missing module context, module, injectable, or instance causes that filter to be omitted. [packages/core/exceptions/base-exception-filter-context.ts:18-36](packages/core/exceptions/base-exception-filter-context.ts#L18-L36) [packages/core/exceptions/base-exception-filter-context.ts:39-71](packages/core/exceptions/base-exception-filter-context.ts#L39-L71) Each retained filter becomes metadata containing its `catch` method bound to the filter instance and exception metatypes read from `FILTER_CATCH_EXCEPTIONS` metadata on its constructor; absent catch metadata becomes an empty metatype array. [packages/core/exceptions/base-exception-filter-context.ts:32-36](packages/core/exceptions/base-exception-filter-context.ts#L32-L36) [packages/core/exceptions/base-exception-filter-context.ts:73-77](packages/core/exceptions/base-exception-filter-context.ts#L73-L77) ## Global-filter lookup `getGlobalMetadata(contextId?, inquirerId?)` returns an empty array when the context was constructed without an `ApplicationConfig`. [packages/core/exceptions/external-exception-filter-context.ts:46-52](packages/core/exceptions/external-exception-filter-context.ts#L46-L52) With configuration, a static context with no inquirer ID returns `ApplicationConfig.getGlobalFilters()` directly. [packages/core/exceptions/external-exception-filter-context.ts:53-56](packages/core/exceptions/external-exception-filter-context.ts#L53-L56) For another context or any inquirer ID, it gets global request-filter wrappers, resolves each wrapper for that context and inquirer, drops falsy instance hosts, extracts their instances, and concatenates them after the static global filters. [packages/core/exceptions/external-exception-filter-context.ts:57-65](packages/core/exceptions/external-exception-filter-context.ts#L57-L65) `ApplicationConfig` stores static global filters separately from global request-filter wrappers; its related add methods append entries to those arrays. [packages/core/application-config.ts:17-23](packages/core/application-config.ts#L17-L23) [packages/core/application-config.ts:64-74](packages/core/application-config.ts#L64-L74) [packages/core/application-config.ts:122-128](packages/core/application-config.ts#L122-L128) ## Resulting handler and externally created callbacks The returned `ExternalExceptionsHandler` selects the first assigned filter whose metatype list is empty or contains a constructor matched by `exception instanceof`; it invokes that filter’s bound `catch` function. If no custom filter matches, it calls its inherited `catch`, which logs non-intrinsic `Error` instances and rethrows the exception. [packages/core/exceptions/external-exceptions-handler.ts:11-17](packages/core/exceptions/external-exceptions-handler.ts#L11-L17) [packages/core/exceptions/external-exceptions-handler.ts:26-36](packages/core/exceptions/external-exceptions-handler.ts#L26-L36) [packages/common/utils/select-exception-filter-metadata.util.ts:3-13](packages/common/utils/select-exception-filter-metadata.util.ts#L3-L13) [packages/core/exceptions/external-exception-filter.ts:6-15](packages/core/exceptions/external-exception-filter.ts#L6-L15) `ExternalContextCreator` constructs this context from a container and its application configuration, calls `create()` while building an external callback, and—when filters are enabled—wraps the callback in `ExternalErrorProxy`. [packages/core/helpers/external-context-creator.ts:56-88](packages/core/helpers/external-context-creator.ts#L56-L88) [packages/core/helpers/external-context-creator.ts:128-134](packages/core/helpers/external-context-creator.ts#L128-L134) [packages/core/helpers/external-context-creator.ts:178-184](packages/core/helpers/external-context-creator.ts#L178-L184) That proxy catches errors from the target callback, creates an `ExecutionContextHost` from callback arguments, sets its context type, and passes the error and host to the handler’s `next()` method. [packages/core/helpers/external-proxy.ts:6-18](packages/core/helpers/external-proxy.ts#L6-L18) ## Validation, errors, and side effects This class has no explicit argument validation and no explicit `throw` statement. Its visible state mutation is assigning `this.moduleContext` during `create()`. [packages/core/exceptions/external-exception-filter-context.ts:22-31](packages/core/exceptions/external-exception-filter-context.ts#L22-L31) It also allocates a new `ExternalExceptionsHandler` per `create()` call. [packages/core/exceptions/external-exception-filter-context.ts:29-32](packages/core/exceptions/external-exception-filter-context.ts#L29-L32) The handler’s `setCustomFilters()` throws `InvalidExceptionFilterException` if called with a non-array value, although this context passes the array returned by `createContext()`. [packages/core/exceptions/external-exceptions-handler.ts:19-24](packages/core/exceptions/external-exceptions-handler.ts#L19-L24) [packages/core/helpers/context-creator.ts:28-40](packages/core/helpers/context-creator.ts#L28-L40) ## Relationships - IMPORTS → `EXCEPTION_FILTERS_METADATA` - IMPORTS → `Controller` - IMPORTS → `ExceptionFilterMetadata` - IMPORTS → `isEmpty` # ExternalExceptionsHandler **Kind:** Class **Source:** [`packages/core/exceptions/external-exceptions-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/external-exceptions-handler.ts#L8) **Part of:** [Core](subsystem-packages-core) `ExternalExceptionsHandler` routes exceptions raised outside the standard request pipeline, such as errors from external contexts or adapters. It first attempts to handle an exception with registered custom filters, then falls back to Nest’s default external exception handling behavior when no matching filter is available. **Extends:** `ExternalExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `next` | `next(exception: Error, host: ArgumentsHost)` | `Promise` | | `setCustomFilters` | `setCustomFilters(filters: ExceptionFilterMetadata[])` | `void` | | `invokeCustomFilters` | `invokeCustomFilters(exception: T, host: ArgumentsHost)` | `Promise | null` | ## Where it refuses work - `ExternalExceptionsHandler` stops the work with `InvalidExceptionFilterException` when `!Array.isArray(filters)`. - `ExternalExceptionsHandler` stops the work with an early return when `result`. - `ExternalExceptionsHandler` stops the work with an early return when `isEmpty(this.filters)`. ## Diagram ```mermaid graph LR A[Exception raised] --> B[ExternalExceptionsHandler.next] B --> C[invokeCustomFilters] C --> D{Matching custom filter?} D -->|Yes| E[Execute filter function] D -->|No| F[Delegate to default handler] F --> G[ExternalExceptionFilter.catch] ``` ## Usage ```ts import { ExternalExceptionsHandler } from '@nestjs/core/exceptions/external-exceptions-handler'; const exceptionsHandler = new ExternalExceptionsHandler(); exceptionsHandler.setCustomFilters([ { exceptionMetatypes: [Error], func: async (exception, host) => { console.error('External operation failed:', exception.message); // Handle the error for the current execution context. const response = host.switchToHttp().getResponse(); response.status(500).json({ message: 'An external operation failed', }); }, }, ]); // Typically invoked internally by Nest when an external-context callback fails. await exceptionsHandler.next(new Error('Service unavailable'), host); ``` ## AI Coding Instructions - Register custom filters through `setCustomFilters()` before calling `next()`; an empty filter list preserves default behavior. - Ensure each custom filter declares the exception types it handles and provides a `func(exception, host)` callback. - Let `next()` remain the primary entry point so unmatched exceptions correctly fall back to `ExternalExceptionFilter`. - Return or await asynchronous filter work from `func`; `invokeCustomFilters()` supports promise-based handlers. - Avoid bypassing this handler in external-context integrations, since doing so skips custom filter selection and fallback handling. ## How it works ## `ExternalExceptionsHandler` `ExternalExceptionsHandler` is an exception handler class that extends `ExternalExceptionFilter` and keeps an initially empty private list of `ExceptionFilterMetadata` entries. [packages/core/exceptions/external-exceptions-handler.ts:8-9](packages/core/exceptions/external-exceptions-handler.ts#L8-L9) ## Relationships - IMPORTS → `ExceptionFilterMetadata` - IMPORTS → `ArgumentsHost` - IMPORTS → `selectExceptionFilterMetadata` - IMPORTS → `isEmpty` # HelpReplFn **Kind:** Class **Source:** [`packages/core/repl/native-functions/help-repl-fn.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/native-functions/help-repl-fn.ts#L6) **Part of:** [Core](subsystem-packages-core) `HelpReplFn` implements the native `help` command for the core REPL. Its `action()` method displays available REPL commands or usage guidance, helping users discover supported interactive functionality. **Extends:** `ReplFunction` ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action()` | `void` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | | `buildHelpMessage` | `any` | ## Diagram ```mermaid graph LR U[REPL User] --> C[help command] C --> H[HelpReplFn] H --> A[action()] A --> O[Help text written to REPL output] ``` ## Usage ```ts import { HelpReplFn } from "@core/repl/native-functions/help-repl-fn"; // Construct the command with the same REPL dependencies used by the command registry. const helpCommand = new HelpReplFn(/* REPL context or output dependencies */); // Execute the native help command. helpCommand.action(); ``` ## AI Coding Instructions - Keep `action()` focused on presenting help content; avoid adding command-execution logic to this class. - Register `HelpReplFn` through the REPL native-function or command registry so users can invoke it interactively. - Keep displayed command names and descriptions synchronized with the commands actually available in the REPL. - Preserve the REPL’s existing output mechanism and formatting conventions when changing help text. # loadAdapter **Kind:** Function **Source:** [`packages/core/helpers/load-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/load-adapter.ts#L11) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function loadAdapter(defaultPlatform: string, transport: string, loaderFn: Function) ``` ## Parameters | Name | Type | |---|---| | `defaultPlatform` | `string` | | `transport` | `string` | | `loaderFn` | `Function` | ## Relationships - IMPORTS → `Logger` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `SocketModule` — `packages/websockets/socket-module.ts`:27 # PathsExplorer **Kind:** Class **Source:** [`packages/core/router/paths-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/paths-explorer.ts#L25) **Part of:** [Core](subsystem-packages-core) `PathsExplorer` discovers route handler methods on a controller instance and converts their decorator metadata into `RouteDefinition` objects. It is used by the router setup flow to scan controller prototypes, read path and HTTP method metadata, and provide callbacks that can be registered with the underlying HTTP adapter. ## Methods | Method | Signature | Returns | |---|---|---| | `scanForPaths` | `scanForPaths(instance: Controller, prototype: object)` | `RouteDefinition[]` | | `exploreMethodMetadata` | `exploreMethodMetadata(instance: Controller, prototype: object, methodName: string)` | `RouteDefinition | null` | ## Where it refuses work - `PathsExplorer` stops the work with an early return when `isUndefined(routePath)`. ## Diagram ```mermaid graph LR Controller[Controller instance] --> Scan[PathsExplorer.scanForPaths] Scan --> Scanner[MetadataScanner scans prototype methods] Scanner --> Explore[PathsExplorer.exploreMethodMetadata] Explore --> Metadata[Reflect route metadata] Metadata --> Definitions[RouteDefinition[]] Definitions --> Router[Router registers handlers] ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { MetadataScanner } from '@nestjs/core/metadata-scanner'; import { PathsExplorer } from '@nestjs/core/router/paths-explorer'; @Controller('users') class UsersController { @Get() findAll() { return ['Ada', 'Grace']; } } const controller = new UsersController(); const metadataScanner = new MetadataScanner(); const pathsExplorer = new PathsExplorer(metadataScanner); const routes = pathsExplorer.scanForPaths(controller); console.log(routes); // [ // { // path: [''], // requestMethod: 0, // targetCallback: [Function: findAll], // methodName: 'findAll' // } // ] ``` ## AI Coding Instructions - Use `scanForPaths()` with a controller instance so discovered callbacks reference the instantiated controller and retain access to its dependencies. - Ensure route methods have path metadata, such as `@Get()`, `@Post()`, or another HTTP method decorator; methods without route metadata are ignored. - Preserve the prototype-scanning pattern when extending this code: metadata is stored on prototype methods, while route callbacks come from the instance. - Treat `exploreMethodMetadata()` returning `null` as an expected result for non-route methods rather than an error. - Keep `RouteDefinition` fields aligned with the router registration layer, especially the normalized path array, request method, handler callback, and method name. ## How it works ## `PathsExplorer` `PathsExplorer` is a router helper that converts method-level route metadata on a controller prototype into `RouteDefinition` objects. It receives a `MetadataScanner` in its constructor. [packages/core/router/paths-explorer.ts:17-26] A `RouteDefinition` contains: - `path`: an array of route-path strings; - `requestMethod`: the metadata-derived `RequestMethod`; - `targetCallback`: the method currently found on the controller instance; - `methodName`: the scanned method name; and - optional `version`: the method’s version metadata. [packages/core/router/paths-explorer.ts:17-23] # RouterExceptionFilters **Kind:** Class **Source:** [`packages/core/router/router-exception-filters.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-exception-filters.ts#L14) **Part of:** [Core](subsystem-packages-core) `RouterExceptionFilters` builds an `ExceptionsHandler` for a routed controller method. It resolves method-, controller-, and application-level exception filters, including scoped global filters, and attaches them in the correct execution order. **Extends:** `BaseExceptionFilterContext` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: RouterProxyCallback, moduleKey: string | undefined, contextId: undefined, inquirerId: string)` | `ExceptionsHandler` | | `getGlobalMetadata` | `getGlobalMetadata(contextId: undefined, inquirerId: string)` | `T` | ## Where it refuses work - `RouterExceptionFilters` stops the work with an early return when `isEmpty(filters)`. - `RouterExceptionFilters` stops the work with an early return when `contextId === STATIC_CONTEXT && !inquirerId`. ## Diagram ```mermaid graph LR A[Incoming route handler] --> B[RouterExceptionFilters.create] B --> C[Resolve method/controller filter metadata] B --> D[Resolve global filters] C --> E[ExceptionsHandler] D --> E E --> F[Execute matching exception filter] F --> G[Send HTTP error response] ``` ## Usage ```ts import { RouterExceptionFilters } from '@nestjs/core/router/router-exception-filters'; // Typically created internally by Nest during application bootstrap. const exceptionFilters = new RouterExceptionFilters( container, applicationConfig, httpAdapter, ); // Create the handler used to process exceptions thrown by a route callback. const handler = exceptionFilters.create( usersController, usersController.findOne, moduleKey, ); // The returned ExceptionsHandler is used by the router proxy. try { await usersController.findOne('123'); } catch (error) { handler.next(error, requestContext); } ``` ## AI Coding Instructions - Treat `RouterExceptionFilters` as router infrastructure; application code should normally register filters with `@UseFilters()` or `app.useGlobalFilters()` instead of instantiating it directly. - Preserve filter resolution order when changing this class: method and controller metadata must be combined with global filter metadata predictably. - Ensure request-scoped and transient global filters are resolved using the active context ID and inquirer ID when applicable. - Return an `ExceptionsHandler` even when no custom filters are registered so default HTTP exception handling remains available. - Keep integrations aligned with `ApplicationConfig`, `NestContainer`, and the active HTTP adapter, since they provide global filters, dependency resolution, and response handling. ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `EXCEPTION_FILTERS_METADATA` - IMPORTS → `Controller` - IMPORTS → `isEmpty` # RoutesMapper **Kind:** Class **Source:** [`packages/core/middleware/routes-mapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/routes-mapper.ts#L24) **Part of:** [Core](subsystem-packages-core) `RoutesMapper` resolves route declarations into normalized `RouteInfo` objects that middleware can consume consistently. It bridges controller metadata, literal path definitions, and application routing configuration so middleware registration can target the correct HTTP paths and methods. ## Methods | Method | Signature | Returns | |---|---|---| | `mapRouteToRouteInfo` | `mapRouteToRouteInfo(controllerOrRoute: Type | RouteInfo | string)` | `RouteInfo[]` | ## Where it refuses work - `RoutesMapper` stops the work with an early return when `!metatype`, in 2 places. - `RoutesMapper` stops the work with an early return when `isString(controllerOrRoute)`. - `RoutesMapper` stops the work with an early return when `this.isRouteInfo(routePathOrPaths, controllerOrRoute)`. - `RoutesMapper` stops the work with an early return when `typeof version !== 'string' && Array.isArray(version)`. - `RoutesMapper` stops the work with an early return when `!moduleRefsSet`. - `RoutesMapper` stops the work with an early return when `versioningConfig`. ## Diagram ```mermaid graph LR A[Route declaration] --> B[RoutesMapper] B --> C[Controller metadata] B --> D[Application route configuration] C --> E[Normalized RouteInfo[]] D --> E E --> F[Middleware registration] ``` ## Usage ```ts import { RoutesMapper } from '@nestjs/core/middleware/routes-mapper'; import { UsersController } from './users.controller'; // RoutesMapper is typically created and used internally by Nest's // middleware subsystem with container and application configuration. const mapper = new RoutesMapper(container, appConfig, routePathFactory); // Resolve a controller's route metadata into middleware-ready route info. const routes = mapper.mapRouteToRouteInfo(UsersController); for (const route of routes) { console.log(route.path, route.method); } ``` ## AI Coding Instructions - Keep route normalization centralized in `RoutesMapper`; middleware code should consume `RouteInfo` rather than reimplementing controller metadata lookup. - Preserve support for controller classes, path strings, and explicit route objects when changing route-resolution behavior. - Return an empty `RouteInfo[]` for route declarations that cannot be resolved instead of throwing during middleware configuration. - Ensure changes remain compatible with application global prefixes, versioning, and controller path metadata. - Treat this class as middleware infrastructure; instantiate it through framework wiring where possible rather than constructing it ad hoc in application code. # USING_INVALID_CLASS_AS_A_MODULE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L184) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function USING_INVALID_CLASS_AS_A_MODULE_MESSAGE(metatypeUsedAsAModule: Type | ForwardReference, scope: any[], classKind: 'provider' | 'controller' | 'filter') ``` ## Parameters | Name | Type | |---|---| | `metatypeUsedAsAModule` | `Type | ForwardReference` | | `scope` | `any[]` | | `classKind` | `'provider' | 'controller' | 'filter'` | # isMiddlewareRouteExcluded **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L118) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isMiddlewareRouteExcluded(req: Record, excludedRoutes: ExcludeRouteMetadata[], httpAdapter: HttpServer): boolean ``` ## Parameters | Name | Type | |---|---| | `req` | `Record` | | `excludedRoutes` | `ExcludeRouteMetadata[]` | | `httpAdapter` | `HttpServer` | **Returns:** `boolean` # RouterProxy **Kind:** Class **Source:** [`packages/core/router/router-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-proxy.ts#L10) **Part of:** [Core](subsystem-packages-core) `RouterProxy` wraps HTTP route and error-layer callbacks with centralized exception handling. It creates async proxy functions that preserve the Express-style middleware signature while forwarding thrown errors to Nest's `ExceptionsHandler` with an HTTP execution context. ## Methods | Method | Signature | Returns | |---|---|---| | `createProxy` | `createProxy(targetCallback: RouterProxyCallback, exceptionsHandler: ExceptionsHandler)` | `void` | | `createExceptionLayerProxy` | `createExceptionLayerProxy(targetCallback: ( err: TError, req: TRequest, res: TResponse, next: () => void, ) => void | Promise, exceptionsHandler: ExceptionsHandler)` | `void` | ## When something fails - `RouterProxy` handles failure in 2 places: it turns it into a return value in all 2. ## Diagram ```mermaid graph LR A[Incoming HTTP request] --> B[RouterProxy.createProxy] B --> C[Route callback] C -->|Success| D[Response / next()] C -->|Throws error| E[ExecutionContextHost] E --> F[ExceptionsHandler.next] F --> G[Exception filters / HTTP response] H[Express error middleware] --> I[createExceptionLayerProxy] I --> J[Error callback] J -->|Throws error| E ``` ## Usage ```ts import { RouterProxy } from '@nestjs/core/router/router-proxy'; // In Nest internals, ExceptionsHandler is configured with exception filters. const routerProxy = new RouterProxy(); const routeHandler = async (req: any, res: any) => { const user = await usersService.findById(req.params.id); if (!user) { throw new Error('User not found'); } res.json(user); }; // `exceptionsHandler` is typically created by Nest's router explorer. const proxiedHandler = routerProxy.createProxy( routeHandler, exceptionsHandler, ); // Register the wrapped handler with the underlying HTTP adapter/router. expressRouter.get('/users/:id', proxiedHandler); ``` ## AI Coding Instructions - Wrap route callbacks with `createProxy()` so synchronous and asynchronous errors reach Nest exception filters consistently. - Use `createExceptionLayerProxy()` only for error middleware that follows the `(err, req, res, next)` signature. - Preserve the original callback arguments and avoid handling exceptions directly inside the proxy; delegate them through `ExceptionsHandler`. - Ensure the supplied exception handler is configured for the current route context before registering the proxied callback. - Treat this class as framework routing infrastructure; application code should normally use controllers, guards, and filters instead of calling it directly. ## How it works `RouterProxy` is a class that creates asynchronous HTTP-style callback wrappers around route, middleware, and error-layer callbacks. Its normal callback type accepts `(req, res, next)` and may return `void` or `Promise`. [packages/core/router/router-proxy.ts:4-10] - `createProxy(targetCallback, exceptionsHandler)` returns an async `(req, res, next)` function. It invokes and awaits `targetCallback(req, res, next)`. On normal completion, it does not explicitly return a value. [packages/core/router/router-proxy.ts:11-21] - If that invocation throws synchronously or its returned promise rejects, the wrapper constructs an `ExecutionContextHost` containing `[req, res, next]`, passes the caught value and host to `exceptionsHandler.next`, then returns `res`. [packages/core/router/router-proxy.ts:20-26] - `createExceptionLayerProxy(targetCallback, exceptionsHandler)` has the same behavior for callbacks with the error-layer signature `(err, req, res, next)`: it awaits the target callback, catches failures, creates a context from `[req, res, next]`—not including `err`—dispatches the newly caught failure to `exceptionsHandler.next`, and returns `res` from the catch path. [packages/core/router/router-proxy.ts:30-52] - Neither factory performs runtime validation of either argument before returning its wrapper. [packages/core/router/router-proxy.ts:11-28] [packages/core/router/router-proxy.ts:30-53] The context created after a failure defaults to the `http` context type. Its HTTP accessors expose the captured values as request at index `0`, response at index `1`, and next callback at index `2`. [packages/core/helpers/execution-context-host.ts:10-17] [packages/core/helpers/execution-context-host.ts:50-55] `ExceptionsHandler.next` first attempts to invoke a selected custom exception filter; when no matching custom filter handles the exception, it delegates to `BaseExceptionFilter.catch`. [packages/core/exceptions/exceptions-handler.ts:12-17] Custom filters are selected from configured metadata and called with the exception and context. [packages/core/exceptions/exceptions-handler.ts:26-37] The base filter writes HTTP exception responses through its adapter when headers have not been sent, otherwise ends the response; unknown errors are converted to an HTTP-error-shaped response or a 500 response and may be logged. [packages/core/exceptions/base-exception-filter.ts:26-47] [packages/core/exceptions/base-exception-filter.ts:50-74] Current router integration includes: - Controller execution contexts are wrapped with `createProxy` together with an exception filter created for the controller callback. [packages/core/router/router-explorer.ts:350-375] - Bound middleware `use` methods are wrapped with `createProxy` and a middleware exception handler. [packages/core/middleware/middleware-module.ts:303-315] - The not-found callback throws a `NotFoundException`; it is wrapped with `createProxy` before registration as the adapter’s not-found handler. [packages/core/router/routes-resolver.ts:146-159] - The external error handler maps certain external errors, throws the mapped error, and is wrapped with `createExceptionLayerProxy` before registration through `setErrorHandler`. [packages/core/router/routes-resolver.ts:162-182] # callAppShutdownHook **Kind:** Function **Source:** [`packages/core/hooks/on-app-shutdown.hook.ts`](https://github.com/nestjs/nest/blob/master/packages/core/hooks/on-app-shutdown.hook.ts#L45) **Part of:** [Core](subsystem-packages-core) Calls the `onApplicationShutdown` function on the module and its children (providers / controllers). `callAppShutdownHook` orchestrates application shutdown lifecycle handling for a module. It invokes `onApplicationShutdown` on the module itself and on eligible providers, controllers, injectables, and middleware instances, forwarding an optional shutdown signal such as `SIGTERM`. ## Signature ```ts async function callAppShutdownHook(module: Module, signal: string): Promise ``` ## Parameters | Name | Type | |---|---| | `module` | `Module` | | `signal` | `string` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Application shutdown signal] --> B[callAppShutdownHook] B --> C[Resolve module providers and children] C --> D[Invoke non-transient instances] D --> E[Invoke transient instances] E --> F[onApplicationShutdown(signal)] ``` ## Usage ```ts import { callAppShutdownHook } from '@nestjs/core/hooks/on-app-shutdown.hook'; // Typically called by the Nest application shutdown lifecycle internally. async function shutdownModule(moduleRef: any) { await callAppShutdownHook(moduleRef, 'SIGTERM'); console.log('Module shutdown hooks completed.'); } ``` ## AI Coding Instructions - Treat this as framework lifecycle infrastructure; application code should normally implement `onApplicationShutdown` rather than call this function directly. - Pass the operating-system shutdown signal when available so lifecycle hooks can distinguish graceful termination causes. - Preserve the shutdown ordering between non-transient and transient instances when modifying hook execution behavior. - Ensure providers, controllers, middleware, and module instances with `onApplicationShutdown` remain discoverable through the module container. ## Relationships - IMPORTS → `OnApplicationShutdown` - IMPORTS → `isFunction` - IMPORTS → `isNil` # ExceptionsZone **Kind:** Class **Source:** [`packages/core/errors/exceptions-zone.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions-zone.ts#L6) **Part of:** [Core](subsystem-packages-core) `ExceptionsZone` executes synchronous or asynchronous bootstrap work within a centralized exception boundary. It delegates caught errors to Nest's exception handling and logging infrastructure, then runs a teardown callback—by default terminating the process. ## Methods | Method | Signature | Returns | |---|---|---| | `run` | `run(callback: () => void, teardown: (err: any) => void, autoFlushLogs: boolean)` | `void` | | `asyncRun` | `asyncRun(callback: () => Promise, teardown: (err: any) => void, autoFlushLogs: boolean)` | `void` | ## When something fails - `ExceptionsZone` handles failure in 2 places: it logs it and continues in all 2. ## Diagram ```mermaid graph LR A[Application bootstrap callback] --> B{ExceptionsZone.run / asyncRun} B -->|Success| C[Continue execution] B -->|Throws or rejects| D[ExceptionHandler] D --> E[Flush logs] E --> F[Teardown callback] F --> G[Exit process by default] ``` ## Usage ```ts import { ExceptionsZone } from '@nestjs/core/errors/exceptions-zone'; async function bootstrap() { // Create and start the application here. console.log('Application started'); } ExceptionsZone.asyncRun( bootstrap, error => { console.error('Bootstrap failed:', error); process.exitCode = 1; }, ); ``` ## AI Coding Instructions - Use `run()` for synchronous callbacks and `asyncRun()` for callbacks that return a `Promise`. - Provide a custom teardown callback when callers need cleanup, test-friendly behavior, or custom process-exit handling. - Do not catch and silently ignore errors inside the callback; allow unrecoverable bootstrap errors to reach `ExceptionsZone`. - Preserve the exception handler and log-flushing flow when modifying this class, as it ensures startup failures are reported consistently. - Treat this as core bootstrap infrastructure; application-level request exceptions should use Nest exception filters instead. ## Relationships - IMPORTS → `Logger` # isRouteExcluded **Kind:** Function **Source:** [`packages/core/router/utils/exclude-route.util.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/utils/exclude-route.util.ts#L9) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isRouteExcluded(excludedRoutes: ExcludeRouteMetadata[], path: string, requestMethod: RequestMethod) ``` ## Parameters | Name | Type | |---|---| | `excludedRoutes` | `ExcludeRouteMetadata[]` | | `path` | `string` | | `requestMethod` | `RequestMethod` | # PartialGraphHost **Kind:** Class **Source:** [`packages/core/inspector/partial-graph.host.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/partial-graph.host.ts#L3) **Part of:** [Core](subsystem-packages-core) `PartialGraphHost` is a static host for storing and exposing the most recently generated partial dependency graph. It delegates serialization to a `SerializedGraph`, allowing inspector and error-reporting flows to retrieve the graph as JSON or a formatted string after it has been registered. ## Methods | Method | Signature | Returns | |---|---|---| | `toJSON` | `toJSON()` | `void` | | `toString` | `toString()` | `void` | | `register` | `register(partialGraph: SerializedGraph)` | `void` | ## Diagram ```mermaid graph LR A[Graph inspection or bootstrap failure] --> B[SerializedGraph] B -->|register(graph)| C[PartialGraphHost] C -->|toJSON()| D[Structured graph data] C -->|toString()| E[Human-readable graph output] ``` ## Usage ```ts import { PartialGraphHost } from '@nestjs/core/inspector/partial-graph.host'; import { SerializedGraph } from '@nestjs/core/inspector/serialized-graph'; // Typically produced by the inspector while scanning application modules. const partialGraph = new SerializedGraph(); // Store the graph for later diagnostics or reporting. PartialGraphHost.register(partialGraph); // Retrieve serialized output. const graphJson = PartialGraphHost.toJSON(); const graphText = PartialGraphHost.toString(); console.log(graphJson); console.log(graphText); ``` ## AI Coding Instructions - Treat `PartialGraphHost` as a static global holder; do not instantiate it or rely on per-instance state. - Register a complete `SerializedGraph` before calling `toJSON()` or `toString()` to avoid reporting stale graph data. - Keep serialization logic in `SerializedGraph`; `PartialGraphHost` should only store and delegate to the registered graph. - Use this host for inspector, diagnostics, and bootstrap-error integration points where a partial dependency graph must remain accessible. - Be aware that calling `register()` replaces the previously stored graph for the entire process. ## How it works - `PartialGraphHost` is an exported class with one private, class-level `SerializedGraph` reference named `partialGraph`. [packages/core/inspector/partial-graph.host.ts:3-4] - `register(partialGraph)` assigns its `SerializedGraph` argument to that shared reference. A later call replaces the previously stored graph; the method contains no visible validation or error handling. [packages/core/inspector/partial-graph.host.ts:14-16] - `toJSON()` optionally calls `toJSON()` on the stored graph. If no graph has been registered, optional chaining causes it to return `undefined`; it does not throw from this method. [packages/core/inspector/partial-graph.host.ts:6-8] When a graph exists, the delegated serialization contains object forms of its nodes, edges, and entrypoints, plus extras and, when set, status and metadata. [packages/core/inspector/serialized-graph.ts:125-140] - `toString()` likewise optionally delegates to the stored graph. A registered `SerializedGraph` formats its JSON with two-space indentation, converts symbols to strings, and serializes functions as their name or `"Function"`. [packages/core/inspector/partial-graph.host.ts:10-12] [packages/core/inspector/serialized-graph.ts:142-150] - The in-repository registration path is `GraphInspector.registerPartial(error)`: it marks its graph’s status as `'partial'`, records metadata for either an `UnknownDependenciesException` or an unknown error, then registers that graph with this host. [packages/core/inspector/graph-inspector.ts:38-59] # repl **Kind:** Function **Source:** [`packages/core/repl/repl.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl.ts#L12) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts async function repl(module: Type | DynamicModule, replOptions: ReplOptions) ``` ## Parameters | Name | Type | |---|---| | `module` | `Type | DynamicModule` | | `replOptions` | `ReplOptions` | ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Logger` - IMPORTS → `Type` # UNDEFINED_MODULE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L210) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function UNDEFINED_MODULE_MESSAGE(parentModule: any, index: number, scope: any[]) ``` ## Parameters | Name | Type | |---|---| | `parentModule` | `any` | | `index` | `number` | | `scope` | `any[]` | # callBeforeAppShutdownHook **Kind:** Function **Source:** [`packages/core/hooks/before-app-shutdown.hook.ts`](https://github.com/nestjs/nest/blob/master/packages/core/hooks/before-app-shutdown.hook.ts#L49) **Part of:** [Core](subsystem-packages-core) Calls the `beforeApplicationShutdown` function on the module and its children (providers / controllers). `callBeforeAppShutdownHook` invokes the `beforeApplicationShutdown` lifecycle hook for a module’s providers, controllers, and module class. It coordinates shutdown hook execution for static dependency trees and forwards the optional operating-system shutdown signal to each eligible instance. ## Signature ```ts async function callBeforeAppShutdownHook(module: Module, signal: string): Promise ``` ## Parameters | Name | Type | |---|---| | `module` | `Module` | | `signal` | `string` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Application shutdown signal] --> B[callBeforeAppShutdownHook] B --> C[Module providers] B --> D[Module controllers] B --> E[Module class instance] C --> F[beforeApplicationShutdown(signal)] D --> F E --> F ``` ## Usage ```ts import { callBeforeAppShutdownHook } from '@nestjs/core/hooks/before-app-shutdown.hook'; import { ModulesContainer } from '@nestjs/core'; async function runShutdownHooks( modulesContainer: ModulesContainer, signal = 'SIGTERM', ) { for (const moduleRef of modulesContainer.values()) { await callBeforeAppShutdownHook(moduleRef, signal); } } ``` ## AI Coding Instructions - Preserve the lifecycle execution order: providers and controllers should run before the module class hook. - Always forward the optional shutdown signal, such as `SIGTERM` or `SIGINT`, to `beforeApplicationShutdown`. - Await hook execution so asynchronous cleanup tasks, such as closing database connections, finish before shutdown continues. - Only invoke hooks for eligible static dependency trees; transient or request-scoped instances require the existing instance-selection logic. - Treat this as framework lifecycle infrastructure—prefer enabling application shutdown hooks rather than calling it directly in application code. ## Relationships - IMPORTS → `BeforeApplicationShutdown` - IMPORTS → `isFunction` - IMPORTS → `isNil` # DeterministicUuidRegistry **Kind:** Class **Source:** [`packages/core/inspector/deterministic-uuid-registry.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/deterministic-uuid-registry.ts#L1) **Part of:** [Core](subsystem-packages-core) `DeterministicUuidRegistry` maintains stable UUID values for identifiers encountered during inspection. It returns the same UUID for a given registry key throughout a registry lifecycle and can reset its stored mappings with `clear()`. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(str: string, inc: undefined)` | `void` | | `clear` | `clear()` | `void` | ## Where it refuses work - `DeterministicUuidRegistry` stops the work with an early return when `this.registry.has(id)`. ## Diagram ```mermaid graph LR A[Inspector / Caller] -->|get(stable key)| B[DeterministicUuidRegistry] B -->|existing mapping| C[Previously assigned UUID] B -->|new mapping| D[Deterministically generated UUID] D --> E[Registry storage] E --> C A -->|clear()| B B -->|remove mappings| E ``` ## Usage ```ts import { DeterministicUuidRegistry } from "./deterministic-uuid-registry"; const uuidRegistry = new DeterministicUuidRegistry(); // Repeated lookups for the same stable key return the same UUID. const firstId = uuidRegistry.get("workflow-step:validate-input"); const secondId = uuidRegistry.get("workflow-step:validate-input"); console.log(firstId === secondId); // true // Reset mappings when starting a new inspection lifecycle. uuidRegistry.clear(); ``` ## AI Coding Instructions - Use stable, meaningful keys when calling `get()` so generated UUIDs remain consistent across related inspection operations. - Reuse a single registry instance for the full inspection or serialization lifecycle that requires stable identifiers. - Call `clear()` only when beginning a new independent lifecycle; clearing during processing invalidates existing mappings. - Do not treat returned UUIDs as permanent persisted IDs unless the registry lifecycle and input keys are also persisted. ## How it works ## `DeterministicUuidRegistry` `DeterministicUuidRegistry` is a static registry that generates string IDs from an input string and tracks IDs already returned during the registry’s current lifetime. Its state is a private static `Map`, shared by every call to the class. [packages/core/inspector/deterministic-uuid-registry.ts:1-2] # filterMiddleware **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L44) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function filterMiddleware(middleware: T[], routes: RouteInfo[], httpAdapter: HttpServer) ``` ## Parameters | Name | Type | |---|---| | `middleware` | `T[]` | | `routes` | `RouteInfo[]` | | `httpAdapter` | `HttpServer` | # MethodsReplFn **Kind:** Class **Source:** [`packages/core/repl/native-functions/methods-repl-fn.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/native-functions/methods-repl-fn.ts#L7) **Part of:** [Core](subsystem-packages-core) `MethodsReplFn` is a native REPL function responsible for handling the `methods` command/action within the core REPL environment. Its `action()` method performs the command’s behavior, allowing the REPL to expose method-related information through the native-function system. **Extends:** `ReplFunction` ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action(token: Type | string)` | `void` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | ## Diagram ```mermaid graph LR User[REPL User] --> Command[methods command] Command --> MethodsReplFn[MethodsReplFn] MethodsReplFn --> Action[action()] Action --> Output[REPL Output] ``` ## Usage ```ts import { MethodsReplFn } from './packages/core/repl/native-functions/methods-repl-fn'; const methodsCommand = new MethodsReplFn(); // Execute the native REPL command behavior. methodsCommand.action(); ``` ## AI Coding Instructions - Keep command-specific behavior inside `action()` so it remains compatible with the REPL native-function dispatch flow. - Follow the conventions used by other classes in `packages/core/repl/native-functions/` when adding output, validation, or context access. - Avoid placing interactive input parsing in this class unless other native functions use the same pattern; parsing is typically handled by the REPL command layer. - When changing displayed method information, ensure the output remains useful for interactive REPL users and consistent with related help or introspection commands. # RouterModule **Kind:** Class **Source:** [`packages/core/router/router-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-module.ts#L19) **Part of:** [Core](subsystem-packages-core) `RouterModule` configures route mappings between URL path segments and application modules. Its `register()` method creates a dynamic module that NestJS uses to apply route prefixes and nested route structures during application bootstrap. ## Methods | Method | Signature | Returns | |---|---|---| | `register` | `register(routes: Routes)` | `DynamicModule` | ## Where it refuses work - `RouterModule` stops the work with an early return when `typeof routeOrType === 'function'`. - `RouterModule` stops the work with an early return when `routeOrType.children`. - `RouterModule` stops the work with an early return when `!moduleRef`. ## Diagram ```mermaid graph LR A[AppModule imports] --> B[RouterModule.register routes] B --> C[Route configuration] C --> D[Feature Module] D --> E[Controllers] E --> F[HTTP endpoints with configured prefix] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { RouterModule } from '@nestjs/core'; import { UsersModule } from './users/users.module'; import { AdminModule } from './admin/admin.module'; @Module({ imports: [ UsersModule, AdminModule, RouterModule.register([ { path: 'api', children: [ { path: 'users', module: UsersModule }, { path: 'admin', module: AdminModule }, ], }, ]), ], }) export class AppModule {} ``` The controllers in `UsersModule` are available under `/api/users`, while controllers in `AdminModule` are available under `/api/admin`. ## AI Coding Instructions - Register routed feature modules in the same application module that imports those feature modules. - Use `children` to build nested route prefixes instead of repeating shared path segments across modules. - Ensure every `module` referenced in `RouterModule.register()` is also included in the parent module's `imports` array. - Keep route paths focused on module-level prefixes; define endpoint-specific paths in controller decorators. - Avoid conflicting route prefixes between sibling modules, as route resolution can become ambiguous. ## How it works ## `RouterModule` `RouterModule` is a public Nest module decorated with an empty `@Module({})` declaration. It registers module-level route prefixes from a `Routes` tree. [`packages/core/router/router-module.ts:16-20`](packages/core/router/router-module.ts#L16-L20) A route tree entry has a `path`, may name a module constructor, and may contain child route entries or module constructors. [`packages/core/router/interfaces/routes.interface.ts:3-9`](packages/core/router/interfaces/routes.interface.ts#L3-L9) # VERSIONED_CONTROLLER_MAPPING_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L31) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function VERSIONED_CONTROLLER_MAPPING_MESSAGE(name: string, path: string, version: VersionValue) ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `path` | `string` | | `version` | `VersionValue` | # VERSIONED_ROUTE_MAPPED_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L15) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function VERSIONED_ROUTE_MAPPED_MESSAGE(path: string, method: string | number, version: VersionValue) ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | | `method` | `string | number` | | `version` | `VersionValue` | # InternalCoreModuleFactory **Kind:** Class **Source:** [`packages/core/injector/internal-core-module/internal-core-module-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/internal-core-module/internal-core-module-factory.ts#L17) **Part of:** [Core](subsystem-packages-core) `InternalCoreModuleFactory` builds the framework’s internal core module definition used by the dependency injection container. Its `create()` method registers foundational providers such as reflection utilities, request context tokens, module storage, HTTP adapter access, lazy module loading, and graph inspection services. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(container: NestContainer, scanner: DependenciesScanner, moduleCompiler: ModuleCompiler, httpAdapterHost: HttpAdapterHost, graphInspector: GraphInspector, moduleOverrides: ModuleOverride[])` | `void` | ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[InternalCoreModuleFactory.create] B --> C[InternalCoreModule Definition] C --> D[Core DI Providers] D --> E[Reflector] D --> F[ModulesContainer] D --> G[HttpAdapterHost] D --> H[ExternalContextCreator] D --> I[LazyModuleLoader] D --> J[SerializedGraph] C --> K[NestContainer] ``` ## Usage ```ts import { InternalCoreModuleFactory } from './internal-core-module-factory'; // Typically called internally during application initialization. const internalCoreModule = InternalCoreModuleFactory.create( container, scanner, moduleCompiler, httpAdapterHost, graphInspector, ); // Register the generated module definition with the application container. await container.addModule(internalCoreModule, []); ``` ## AI Coding Instructions - Treat `create()` as framework bootstrap infrastructure; application code should generally not call it directly. - Keep provider tokens and exports aligned so internal services remain resolvable throughout the container. - Pass the active `NestContainer`, scanner, compiler, HTTP adapter host, and graph inspector from the bootstrap pipeline. - Preserve request-scoped provider behavior when adding providers that depend on request context or inquirer resolution. - Update this factory when introducing new globally available internal runtime services. ## Relationships - IMPORTS → `Logger` # REQUEST **Kind:** Constant **Source:** [`packages/core/router/request/request-constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/request/request-constants.ts#L1) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'REQUEST' ``` ## Value ```ts 'REQUEST' ``` ## Used by 8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (8) - `ScopedService` — `integration/injector/src/scoped/scoped.service.ts`:4 - `DurableService` — `integration/inspector/src/durable/durable.service.ts`:4 - `HelperService` — `integration/inspector/src/request-chain/helper/helper.service.ts`:4 - `DurableService` — `integration/scopes/src/durable/durable.service.ts`:10 - `NonDurableService` — `integration/scopes/src/durable/non-durable.service.ts`:5 - `RequestLogger` — `integration/scopes/src/inject-inquirer/hello-request/request-logger.service.ts`:4 - `HelperService` — `integration/scopes/src/request-chain/helper/helper.service.ts`:4 - `CONTEXT` — `packages/microservices/tokens.ts`:3 # TopologyTree **Kind:** Class **Source:** [`packages/core/injector/topology-tree/topology-tree.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/topology-tree/topology-tree.ts#L4) **Part of:** [Core](subsystem-packages-core) `TopologyTree` represents the hierarchical import topology of modules during dependency-injection container setup. Its `walk()` method traverses the tree from the root module, allowing internal tooling to inspect each module and its depth in the topology. ## Methods | Method | Signature | Returns | |---|---|---| | `walk` | `walk(callback: (value: Module, depth: number) => void)` | `void` | ## Where it refuses work - `TopologyTree` stops the work with an early return when `!node.value.imports`. - `TopologyTree` stops the work with an early return when `!child`. - `TopologyTree` stops the work with an early return when `node.hasCycleWith(child)`. ## Diagram ```mermaid graph LR Root[Root Module] --> FeatureA[Feature Module A] Root --> FeatureB[Feature Module B] FeatureA --> Shared[Shared Module] Walk[TopologyTree.walk()] --> Root Walk --> Callback["callback(module, depth)"] ``` ## Usage ```ts import { TopologyTree } from '@nestjs/core/injector/topology-tree/topology-tree'; // `rootModule` is the root Module instance created by the container. const topologyTree = new TopologyTree(rootModule); // Traverse modules in the topology and use their nesting depth. topologyTree.walk((moduleRef, depth) => { if (!moduleRef.isGlobal) { moduleRef.distance = depth; } console.log(`${' '.repeat(depth)}${moduleRef.metatype?.name}`); }); ``` ## AI Coding Instructions - Use `walk()` for read-only traversal tasks such as calculating module distance, collecting metadata, or inspecting module relationships. - Treat `TopologyTree` as an internal injector/container utility; avoid depending on it from application-level modules. - Preserve the callback’s depth value when adding traversal-based logic, since it represents the module’s position relative to the root. - Do not mutate the module import graph while walking it; build the topology first, then traverse it. ## How it works ## `TopologyTree` `TopologyTree` is a private-structure builder for a graph of `Module` instances connected through each module’s `imports` set. It stores one `TreeNode` per encountered module in a `Map`, rooted at the `Module` passed to its constructor. [topology-tree.ts:4-6](packages/core/injector/topology-tree/topology-tree.ts#L4-L6) # optionalRequire **Kind:** Function **Source:** [`packages/core/helpers/optional-require.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/optional-require.ts#L1) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function optionalRequire(packageName: string, loaderFn: Function) ``` ## Parameters | Name | Type | |---|---| | `packageName` | `string` | | `loaderFn` | `Function` | ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 # ResolveReplFn **Kind:** Class **Source:** [`packages/core/repl/native-functions/resolve-repl-fn.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/native-functions/resolve-repl-fn.ts#L5) **Part of:** [Core](subsystem-packages-core) `ResolveReplFn` is a native REPL function that performs the resolve operation exposed by the interactive REPL environment. Its `action()` method executes the resolution workflow asynchronously and returns the resulting value to the REPL runtime. **Extends:** `ReplFunction` ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action(token: string | symbol | Function | Type, contextId: any)` | `Promise` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | ## Diagram ```mermaid graph LR User[REPL user input] --> Repl[REPL runtime] Repl --> ResolveReplFn[ResolveReplFn] ResolveReplFn --> Action[action()] Action --> Resolver[Resolution workflow] Resolver --> Result[Promise result] Result --> Repl ``` ## Usage ```ts import { ResolveReplFn } from "./native-functions/resolve-repl-fn"; // ResolveReplFn is typically constructed and registered by the REPL runtime. declare const resolveFn: ResolveReplFn; async function runResolve(): Promise { const result = await resolveFn.action(); console.log("Resolve result:", result); } void runResolve(); ``` ## AI Coding Instructions - Keep `action()` asynchronous and return the resolution result through its `Promise`. - Treat this class as a REPL integration point; ensure it is registered or instantiated through the same native-function flow as other REPL commands. - Preserve the result shape expected by the REPL renderer or caller when changing resolution behavior. - Handle resolution failures consistently with other native REPL functions so errors are surfaced clearly to interactive users. ## How it works ## `ResolveReplFn` `ResolveReplFn` is a built-in REPL function class that extends `ReplFunction`. Its metadata registers the function under the name `resolve`, with the displayed signature `(token: InjectionToken, contextId: any) => Promise`. [packages/core/repl/native-functions/resolve-repl-fn.ts:5-11] `ReplContext` includes `ResolveReplFn` in its built-in function classes. During initialization, it constructs the class, stores it in `nativeFunctions` under its metadata name, and binds its `action` method into the REPL global scope as `resolve`. [packages/core/repl/repl-context.ts:168-184] [packages/core/repl/repl-context.ts:122-150] Thus a REPL user can invoke it as `resolve(...)`. The bound function also has a non-enumerable `help` getter that writes a generated help message to standard output. [packages/core/repl/repl-context.ts:152-162] The help text is generated from this class’s description, name, and signature. [packages/core/repl/repl-function.ts:27-35] # RouteParamsFactory **Kind:** Class **Source:** [`packages/core/router/route-params-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/route-params-factory.ts#L4) **Part of:** [Core](subsystem-packages-core) `RouteParamsFactory` resolves a configured route-parameter key into its corresponding typed value. It centralizes route parameter exchange logic so router consumers can safely retrieve values while handling missing parameters through a `null` result. **Implements:** `IRouteParamsFactory` ## Methods | Method | Signature | Returns | |---|---|---| | `exchangeKeyForValue` | `exchangeKeyForValue(key: RouteParamtypes | string, data: string, { req, res, next }: { req: TRequest; res: TResponse; next: Function })` | `TResult | null` | ## Diagram ```mermaid graph LR A[Route definition / parameter mapping] --> B[RouteParamsFactory] C[Current route parameters] --> B B --> D[exchangeKeyForValue()] D --> E[Typed parameter value] D --> F[null when no matching value exists] ``` ## Usage ```ts import { RouteParamsFactory } from "@your-package/core/router"; function loadUser(routeParamsFactory: RouteParamsFactory) { const userId = routeParamsFactory.exchangeKeyForValue(); if (userId === null) { throw new Error("A user route parameter is required."); } return fetch(`/api/users/${encodeURIComponent(userId)}`); } ``` ## AI Coding Instructions - Treat `exchangeKeyForValue()` as a nullable lookup; always handle the `null` case before using the returned value. - Provide the expected result type through the generic parameter when the route value needs to be treated as a specific type. - Keep route-key mapping and parameter exchange logic inside `RouteParamsFactory` rather than duplicating lookup behavior in route handlers. - Ensure the route definition and the factory’s configured parameter mapping stay aligned when renaming route parameters. ## How it works ## `RouteParamsFactory` `RouteParamsFactory` is a class implementing `IRouteParamsFactory`; its `exchangeKeyForValue` method maps a route-parameter type and optional `data` key to a value from `{ req, res, next }`. [route-params-factory.ts:4-13](packages/core/router/route-params-factory.ts#L4-L13) The router constructs one instance and passes it to `RouterExecutionContext`; that context creates extraction functions which call this method with the request, response, and next callback. [router-explorer.ts:78-98](packages/core/router/router-explorer.ts#L78-L98) [router-execution-context.ts:315-326](packages/core/router/router-execution-context.ts#L315-L326) ## Relationships - IMPORTS → `RouteParamtypes` # UNKNOWN_EXPORT_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L227) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function UNKNOWN_EXPORT_MESSAGE(token: string | symbol, module: string) ``` ## Parameters | Name | Type | |---|---| | `token` | `string | symbol` | | `module` | `string` | # assignToObject **Kind:** Function **Source:** [`packages/core/repl/assign-to-object.util.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/assign-to-object.util.ts#L5) **Part of:** [Core](subsystem-packages-core) Similar to `Object.assign` but copying properties descriptors from `source` as well. `assignToObject` copies all own properties from a source object to a target object while preserving each property's descriptor, including getters, setters, enumerability, writability, and configurability. Unlike `Object.assign`, it does not read property values during copying, making it suitable for REPL and runtime utilities that need to retain object behavior accurately. ## Signature ```ts function assignToObject(target: T, source: U): T & U ``` ## Parameters | Name | Type | |---|---| | `target` | `T` | | `source` | `U` | **Returns:** `T & U` ## Diagram ```mermaid graph LR Source[Source object] --> Keys[Own property keys] Keys --> Descriptors[Get property descriptors] Descriptors --> Define[Define properties on target] Define --> Target[Target object] ``` ## Usage ```ts import { assignToObject } from './assign-to-object.util'; const source = {}; Object.defineProperty(source, 'computed', { enumerable: true, get() { return 'generated value'; }, }); const target = { existing: true }; assignToObject(target, source); console.log(target.existing); // true console.log(target.computed); // "generated value" const descriptor = Object.getOwnPropertyDescriptor(target, 'computed'); console.log(typeof descriptor?.get); // "function" ``` ## AI Coding Instructions - Use `assignToObject` when copied properties must retain getters, setters, and descriptor flags; use `Object.assign` only for plain value copying. - Preserve own-property descriptor semantics, including symbol keys if the implementation supports them. - Do not access source property values while copying, as doing so can invoke getters and change behavior. - Ensure the target object can accept the copied descriptors; non-configurable target properties may cause `Object.defineProperty` to throw. - Keep this utility focused on descriptor-preserving assignment for REPL object composition and runtime inspection flows. # defineDefaultCommandsOnRepl **Kind:** Function **Source:** [`packages/core/repl/repl-native-commands.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-native-commands.ts#L20) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function defineDefaultCommandsOnRepl(replServer: REPLServer): void ``` ## Parameters | Name | Type | |---|---| | `replServer` | `REPLServer` | **Returns:** `void` # GetReplFn **Kind:** Class **Source:** [`packages/core/repl/native-functions/get-repl-fn.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/native-functions/get-repl-fn.ts#L5) **Part of:** [Core](subsystem-packages-core) `GetReplFn` is a native REPL function implementation responsible for resolving and returning a function through its `action()` method. It participates in the core REPL native-function layer, allowing REPL expressions or commands to access callable behavior at runtime. **Extends:** `ReplFunction` ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action(token: string | symbol | Function | Type)` | `any` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | ## Diagram ```mermaid graph LR REPL[REPL Input] --> Resolver[Native Function Resolution] Resolver --> GetReplFn[GetReplFn] GetReplFn --> Action[action()] Action --> Function[Resolved Function] ``` ## Usage ```ts import { GetReplFn } from "./packages/core/repl/native-functions/get-repl-fn"; const getReplFn = new GetReplFn(); const resolvedFunction = getReplFn.action(); if (typeof resolvedFunction === "function") { const result = resolvedFunction(); console.log(result); } ``` ## AI Coding Instructions - Keep function-resolution logic inside `action()` so it remains consistent with other native REPL function implementations. - Treat the `action()` return value as potentially dynamic; validate it before invoking it as a callable function. - Follow the established native-function registration and naming conventions when integrating `GetReplFn` into the REPL runtime. - Avoid adding REPL parsing concerns to this class; parsing and command dispatch should remain in the surrounding REPL infrastructure. # InitializeOnPreviewAllowlist **Kind:** Class **Source:** [`packages/core/inspector/initialize-on-preview.allowlist.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/initialize-on-preview.allowlist.ts#L3) **Part of:** [Core](subsystem-packages-core) `InitializeOnPreviewAllowlist` tracks which component or entity types are permitted to run initialization logic while the inspector is in preview mode. It provides a small allowlist API: use `add()` to register allowed entries and `has()` to check whether preview initialization should be enabled for a given entry. ## Methods | Method | Signature | Returns | |---|---|---| | `add` | `add(type: Type)` | `void` | | `has` | `has(type: Type)` | `void` | ## Diagram ```mermaid graph LR A[Inspector Preview Flow] --> B[InitializeOnPreviewAllowlist] B -->|add(type)| C[Allowed initialization entries] A -->|has(type)| B B -->|true| D[Run initialization in preview] B -->|false| E[Skip initialization] ``` ## Usage ```ts import { InitializeOnPreviewAllowlist } from './initialize-on-preview.allowlist'; const previewAllowlist = new InitializeOnPreviewAllowlist(); // Allow a component type to initialize during inspector preview. previewAllowlist.add('my-component'); function shouldInitializeInPreview(componentType: string): boolean { return previewAllowlist.has(componentType); } if (shouldInitializeInPreview('my-component')) { // Run preview-safe initialization. } ``` ## AI Coding Instructions - Use `add()` during inspector or component registration to explicitly opt entries into preview initialization. - Always guard preview-only initialization with `has()` rather than assuming normal runtime initialization is safe in preview. - Keep allowlisted initialization side-effect-safe; preview code should avoid unexpected persistence, network calls, or global mutations. - Reuse the same allowlist instance across the relevant inspector preview flow so registrations are visible to checks. ## Relationships - IMPORTS → `Type` # SelectReplFn **Kind:** Class **Source:** [`packages/core/repl/native-functions/select-relp-fn.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/native-functions/select-relp-fn.ts#L9) **Part of:** [Core](subsystem-packages-core) `SelectReplFn` is a native REPL function responsible for selecting and returning a NestJS `INestApplicationContext`. It provides the REPL layer with access to the active application context so commands can resolve and interact with registered providers. **Extends:** `ReplFunction` ## Methods | Method | Signature | Returns | |---|---|---| | `action` | `action(token: DynamicModule | Type)` | `INestApplicationContext` | ## Properties | Property | Type | |---|---| | `fnDefinition` | `ReplFnDefinition` | ## Diagram ```mermaid graph LR User[REPL User] --> Command[REPL Command] Command --> SelectReplFn[SelectReplFn] SelectReplFn --> Context[INestApplicationContext] Context --> Providers[Nest Providers] ``` ## Usage ```ts import { SelectReplFn } from './native-functions/select-relp-fn'; // Create the native REPL function using the dependencies required by your setup. const selectRepl = new SelectReplFn(/* REPL/application dependencies */); // Retrieve the selected Nest application context. const appContext = selectRepl.action(); // Resolve a provider from the active application context. const myService = appContext.get(MyService); await myService.run(); ``` ## AI Coding Instructions - Keep `action()` focused on returning a valid `INestApplicationContext`; avoid placing command-specific business logic in this class. - Preserve NestJS context typing so callers can safely use `context.get()` to resolve providers. - Ensure the REPL has initialized or selected an application context before invoking `action()`. - When adding REPL-native functions, follow the same small, single-purpose `action()` pattern for predictable command integration. ## How it works ## `SelectReplFn` `SelectReplFn` is a built-in REPL function class that extends `ReplFunction`. Its function metadata registers it under the name `select`, with a signature of `(token: DynamicModule | ClassRef) => INestApplicationContext`. [packages/core/repl/native-functions/select-relp-fn.ts:9-15] When a `ReplContext` initializes, it includes `SelectReplFn` among its built-in function classes. The context stores the resulting instance under its metadata name and places a bound `action` method in the REPL global scope, so users invoke it as `select(...)`. [packages/core/repl/repl-context.ts:128-129] [packages/core/repl/repl-context.ts:148-161] [packages/core/repl/repl-context.ts:168-184] # callModuleBootstrapHook **Kind:** Function **Source:** [`packages/core/hooks/on-app-bootstrap.hook.ts`](https://github.com/nestjs/nest/blob/master/packages/core/hooks/on-app-bootstrap.hook.ts#L43) **Part of:** [Core](subsystem-packages-core) Calls the `onApplicationBootstrap` function on the module and its children (providers / controllers). `callModuleBootstrapHook` invokes `onApplicationBootstrap()` lifecycle hooks for a module’s providers, controllers, injectables, middleware, and module class. It is used during application initialization to ensure eligible static dependency trees complete bootstrap work after dependency injection has been resolved. ## Signature ```ts async function callModuleBootstrapHook(module: Module): Promise ``` ## Parameters | Name | Type | |---|---| | `module` | `Module` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Module] --> B[Collect providers and controllers] B --> C[Invoke non-transient instances] C --> D[Invoke transient instances] D --> E{Module dependency tree is static?} E -- Yes --> F[Call module.onApplicationBootstrap()] E -- No --> G[Skip module hook] ``` ## Usage ```ts import { callModuleBootstrapHook } from '@nestjs/core/hooks/on-app-bootstrap.hook'; import { Module } from '@nestjs/core/injector/module'; // Typically called internally by Nest during application initialization. async function runModuleBootstrapHooks(moduleRef: Module) { await callModuleBootstrapHook(moduleRef); } class CacheService { async onApplicationBootstrap() { console.log('Connecting to cache...'); } } class AppModule { async onApplicationBootstrap() { console.log('Application module bootstrap complete'); } } ``` ## AI Coding Instructions - Treat this as an internal lifecycle orchestration function; application code should normally implement `onApplicationBootstrap()` rather than call this function directly. - Preserve the invocation order: non-transient instances must be processed before transient instances, followed by the module class hook. - Ensure lifecycle hooks are called only for instances with a valid `onApplicationBootstrap` method and an eligible static dependency tree. - Include controllers, providers, injectables, and middleware when collecting instances that may implement bootstrap hooks. - Await all hook calls so asynchronous initialization completes before application bootstrap proceeds. ## Relationships - IMPORTS → `OnApplicationBootstrap` - IMPORTS → `isFunction` - IMPORTS → `isNil` # callModuleDestroyHook **Kind:** Function **Source:** [`packages/core/hooks/on-module-destroy.hook.ts`](https://github.com/nestjs/nest/blob/master/packages/core/hooks/on-module-destroy.hook.ts#L41) **Part of:** [Core](subsystem-packages-core) Calls the `onModuleDestroy` function on the module and its children (providers / controllers). `callModuleDestroyHook` runs the `onModuleDestroy()` lifecycle hook for a module’s providers, controllers, injectables, middleware, and the module class itself. It is used during application shutdown to ensure managed resources—such as database connections, queues, and timers—are released in the correct lifecycle phase. ## Signature ```ts async function callModuleDestroyHook(module: Module): Promise ``` ## Parameters | Name | Type | |---|---| | `module` | `Module` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Application shutdown] --> B[callModuleDestroyHook] B --> C[Module providers] B --> D[Controllers] B --> E[Injectables and middleware] C --> F[onModuleDestroy hooks] D --> F E --> F B --> G[Module class] G --> H[Module onModuleDestroy hook] ``` ## Usage ```ts import { Module, OnModuleDestroy } from '@nestjs/common'; class DatabaseService implements OnModuleDestroy { async onModuleDestroy() { console.log('Closing database connection'); // await this.database.close(); } } @Module({ providers: [DatabaseService], }) export class DatabaseModule implements OnModuleDestroy { onModuleDestroy() { console.log('Destroying DatabaseModule'); } } // Nest calls callModuleDestroyHook internally when the application closes: // await app.close(); ``` ## AI Coding Instructions - Treat this as an internal lifecycle utility; application code should normally trigger it through `app.close()` rather than calling it directly. - Ensure resource-owning providers implement `onModuleDestroy()` and make cleanup operations safe to run once. - Preserve the distinction between non-transient and transient provider instances when changing hook invocation logic. - Keep module-class destruction after child provider, controller, injectable, and middleware hooks have completed. - Await asynchronous cleanup hooks so shutdown does not complete before resources are released. ## Relationships - IMPORTS → `OnModuleDestroy` - IMPORTS → `isFunction` - IMPORTS → `isNil` # callModuleInitHook **Kind:** Function **Source:** [`packages/core/hooks/on-module-init.hook.ts`](https://github.com/nestjs/nest/blob/master/packages/core/hooks/on-module-init.hook.ts#L37) **Part of:** [Core](subsystem-packages-core) Calls the `onModuleInit` function on the module and its children (providers / controllers). `callModuleInitHook` runs the `onModuleInit()` lifecycle hook for a Nest module’s initialized controllers, providers, injectables, and middleware. It processes non-transient and transient instances before invoking the module class’s own hook when its dependency tree is static. ## Signature ```ts async function callModuleInitHook(module: Module): Promise ``` ## Parameters | Name | Type | |---|---| | `module` | `Module` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Module] --> B[Controllers] A --> C[Providers] A --> D[Injectables] A --> E[Middleware] B --> F[Invoke onModuleInit] C --> F D --> F E --> F F --> G[Non-transient instances] G --> H[Transient instances] H --> I[Module class onModuleInit] ``` ## Usage ```ts import { callModuleInitHook } from '@nestjs/core/hooks/on-module-init.hook'; import { Module } from '@nestjs/core/injector/module'; // Typically called internally by Nest during application initialization. async function initializeModule(moduleRef: Module) { await callModuleInitHook(moduleRef); console.log('Module lifecycle hooks have completed.'); } ``` ## AI Coding Instructions - Treat this as an internal lifecycle utility; application code should usually implement `OnModuleInit` rather than call this function directly. - Ensure providers, controllers, injectables, and middleware are fully instantiated before invoking module initialization hooks. - Preserve the ordering: execute child instance hooks before the module class’s own `onModuleInit()` hook. - Keep transient and non-transient instance handling separate so each lifecycle hook is invoked for the correct resolved instances. - Only invoke the module class hook when its dependency tree is static and the class implements `onModuleInit()`. ## Relationships - IMPORTS → `OnModuleInit` - IMPORTS → `isFunction` - IMPORTS → `isNil` # flattenRoutePaths **Kind:** Function **Source:** [`packages/core/router/utils/flatten-route-paths.util.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/utils/flatten-route-paths.util.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function flattenRoutePaths(routes: Routes) ``` ## Parameters | Name | Type | |---|---| | `routes` | `Routes` | ## Relationships - IMPORTS → `Type` - IMPORTS → `isString` - IMPORTS → `normalizePath` # InternalCoreModule **Kind:** Class **Source:** [`packages/core/injector/internal-core-module/internal-core-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/internal-core-module/internal-core-module.ts#L16) **Part of:** [Core](subsystem-packages-core) `InternalCoreModule` is a framework-internal global module that registers core dependency-injection providers used by the application container. Its `register()` method returns a `DynamicModule`, allowing the framework to supply container-specific services during application initialization. ## Methods | Method | Signature | Returns | |---|---|---| | `register` | `register(providers: Array)` | `DynamicModule` | ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[InternalCoreModule.register()] B --> C[DynamicModule] C --> D[Core DI Providers] D --> E[Application Injector / Container] E --> F[Framework Services] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { InternalCoreModule } from './injector/internal-core-module/internal-core-module'; @Module({ imports: [ // Normally registered internally by the framework bootstrap process. InternalCoreModule.register(), ], }) export class AppModule {} ``` ## AI Coding Instructions - Treat `InternalCoreModule` as framework infrastructure; application modules should generally not import it directly. - Keep `register()` focused on returning a valid `DynamicModule` and registering only core container providers. - Ensure providers added during registration are compatible with the injector lifecycle and scope rules. - Preserve the module’s global/core role when changing exports or registered providers. - Prefer integrating new framework-level services through the bootstrap/container setup rather than manually instantiating them. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Global` - IMPORTS → `Module` - IMPORTS → `ExistingProvider` - IMPORTS → `FactoryProvider` - IMPORTS → `ValueProvider` # mapToExcludeRoute **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L15) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function mapToExcludeRoute(routes: (string | RouteInfo)[]): ExcludeRouteMetadata[] ``` ## Parameters | Name | Type | |---|---| | `routes` | `(string | RouteInfo)[]` | **Returns:** `ExcludeRouteMetadata[]` # UuidFactory **Kind:** Class **Source:** [`packages/core/inspector/uuid-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/uuid-factory.ts#L9) **Part of:** [Core](subsystem-packages-core) `UuidFactory` centralizes UUID generation for the inspector subsystem. Its `get()` method provides a new identifier when components need a stable, unique value for tracking or associating inspector entities. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(key: undefined)` | `void` | ## Diagram ```mermaid graph LR A[Inspector component] --> B[UuidFactory] B --> C[get()] C --> D[Generated UUID] ``` ## Usage ```ts import { UuidFactory } from './uuid-factory'; const uuidFactory = new UuidFactory(); const inspectorId = uuidFactory.get(); console.log(inspectorId); // Example: "550e8400-e29b-41d4-a716-446655440000" ``` ## AI Coding Instructions - Use `UuidFactory#get()` whenever the inspector needs a new unique identifier instead of creating ad hoc IDs inline. - Treat returned UUIDs as opaque strings; do not depend on a specific UUID value or formatting beyond uniqueness. - Prefer passing a shared `UuidFactory` instance through the relevant inspector integration path when consistent ID generation needs to be coordinated. - Keep UUID generation concerns inside this factory rather than coupling inspector components directly to a UUID library or platform API. ## How it works - `UuidFactory` is an exported static class that selects between random and deterministic string identifier generation. Its two modes are `Random` (`'random'`) and `Deterministic` (`'deterministic'`). [packages/core/inspector/uuid-factory.ts:4-9] - The class starts in `Random` mode. Assigning `UuidFactory.mode` changes its private static mode for subsequent calls; the setter has no visible validation or error handling. [packages/core/inspector/uuid-factory.ts:10-14] - `UuidFactory.get(key = '')` accepts an optional key, defaulting to the empty string. In deterministic mode, it passes that key to `DeterministicUuidRegistry.get`; in every other mode value, it calls `randomStringGenerator()` and does not use the key. [packages/core/inspector/uuid-factory.ts:16-19] - The random path returns the result of `uid(21)`, because `randomStringGenerator` is defined as `() => uid(21)`. [packages/common/utils/random-string-generator.util.ts:1-4] - The deterministic path hashes the supplied key into a decimal-string identifier. The registry records each emitted identifier; if an identifier has already been recorded, it recursively retries using the key suffixed with `_1`, `_2`, and so on, until it finds an unrecorded hash. [packages/core/inspector/deterministic-uuid-registry.ts:2-10] The hash starts at `0`, updates with `Math.imul(31, h) + characterCode`, coerces each step to a signed 32-bit integer, and returns `h.toString()`. [packages/core/inspector/deterministic-uuid-registry.ts:17-22] - Consequently, deterministic calls mutate the registry’s static map, including calls with the default empty key. The registry can be cleared through `DeterministicUuidRegistry.clear()`, which empties that map. [packages/core/inspector/deterministic-uuid-registry.ts:2, 4-10, 13-15] `GraphInspector.inspectModules()` clears it after inserting module nodes, class nodes, module edges, and cached enhancer edges. [packages/core/inspector/graph-inspector.ts:22-36] - During `NestFactory.initialize`, `options.snapshot` selects the factory’s global mode: truthy selects deterministic mode, otherwise random mode. [packages/core/nest-factory.ts:206-216] - The injector’s `InstanceWrapper` builds a key from its name or token plus its host name and calls `UuidFactory.get(key)` only when that key is truthy; otherwise it bypasses the factory and generates a random string directly. [packages/core/injector/instance-wrapper.ts:569-574] `Module` follows the same pattern, constructing a key with an `M_` prefix and calling the factory only for a truthy key. [packages/core/injector/module.ts:662-671] ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # ExternalErrorProxy **Kind:** Class **Source:** [`packages/core/helpers/external-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/external-proxy.ts#L5) **Part of:** [Core](subsystem-packages-core) `ExternalErrorProxy` creates a proxy around external dependencies so errors thrown by third-party clients can be handled consistently. It centralizes external error interception and translation, allowing the rest of the application to interact with integrations through a safer, uniform interface. ## Methods | Method | Signature | Returns | |---|---|---| | `createProxy` | `createProxy(targetCallback: (...args: any[]) => any, exceptionsHandler: ExternalExceptionsHandler, type: TContext)` | `void` | ## When something fails - `ExternalErrorProxy` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR A[Application Service] --> B[ExternalErrorProxy] B -->|createProxy| C[Proxied External Client] C --> D[External API / SDK] D -->|Success| C C -->|Result| A D -->|Throws external error| B B -->|Normalized application error| A ``` ## Usage ```ts import { ExternalErrorProxy } from '@your-package/core/helpers/external-proxy'; const externalClient = { async getCustomer(customerId: string) { const response = await fetch( `https://api.example.com/customers/${customerId}`, ); if (!response.ok) { throw new Error(`External API request failed: ${response.status}`); } return response.json(); }, }; const errorProxy = new ExternalErrorProxy(); const customerClient = errorProxy.createProxy(externalClient); const customer = await customerClient.getCustomer('customer_123'); console.log(customer); ``` ## AI Coding Instructions - Wrap external SDKs, HTTP clients, and integration adapters with `createProxy()` instead of duplicating error-handling logic in every caller. - Preserve the original external client method signatures when adding new proxied dependencies. - Ensure error normalization retains useful context, such as the failing operation or upstream response details, without exposing sensitive data. - Do not bypass the proxy for production integration calls; doing so can create inconsistent error behavior across the application. - Add tests for both successful method delegation and failures thrown by proxied external methods. ## How it works `ExternalErrorProxy` is a class whose `createProxy` method returns an asynchronous callback wrapper around a target callback. The wrapper accepts any arguments and invokes the target with those same arguments. [packages/core/helpers/external-proxy.ts:5-13] - `createProxy` takes a callable `targetCallback`, an `ExternalExceptionsHandler`, and an optional context-type value constrained to `string` (defaulting generically to `ContextType`). It performs no runtime validation of these inputs. [packages/core/helpers/external-proxy.ts:6-10] - On normal completion, the wrapper resolves to the value produced by `targetCallback`, including when that value is a promise, because it awaits the invocation. [packages/core/helpers/external-proxy.ts:11-13] - It catches both synchronous throws and promise rejections from `targetCallback`. [packages/core/helpers/external-proxy.ts:11-17] The repository test exercises both forms and expects the exception handler’s `next` method to be called. [packages/core/test/helpers/external-proxy.spec.ts:24-41] - On a caught value, it constructs an `ExecutionContextHost` from the wrapper’s received arguments, sets its context type, and returns `exceptionsHandler.next(e, host)`. [packages/core/helpers/external-proxy.ts:14-18] `ExecutionContextHost` retains the supplied argument array; its initial type is `'http'`, and `setType` changes that type only when its argument is truthy. [packages/core/helpers/execution-context-host.ts:10-21,35-40] - Consequently, when `type` is omitted or otherwise falsy at runtime, the host passed to the exception handler retains the default `'http'` type. [packages/core/helpers/external-proxy.ts:15-17] [packages/core/helpers/execution-context-host.ts:11,19-21] - `ExternalExceptionsHandler.next` first invokes a selected custom filter when one matches; otherwise it calls the inherited `catch` method. [packages/core/exceptions/external-exceptions-handler.ts:11-17,26-35] The inherited path logs non-intrinsic `Error` instances and then throws the caught exception. [packages/core/exceptions/external-exception-filter.ts:6-15] - `ExternalContextCreator` wraps its generated external handler with this proxy only when `options.filters` is truthy; otherwise it returns the target handler unwrapped. [packages/core/helpers/external-context-creator.ts:164-185] ## Relationships - IMPORTS → `ContextType` # INVALID_CLASS_SCOPE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L245) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function INVALID_CLASS_SCOPE_MESSAGE(text: TemplateStringsArray, name: string | undefined) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `name` | `string | undefined` | # MiddlewareResolver **Kind:** Class **Source:** [`packages/core/middleware/resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/resolver.ts#L7) **Part of:** [Core](subsystem-packages-core) `MiddlewareResolver` resolves configured middleware definitions into runtime middleware instances. It centralizes middleware instantiation so the application pipeline can execute middleware consistently and with the appropriate dependencies. ## Methods | Method | Signature | Returns | |---|---|---| | `resolveInstances` | `resolveInstances(moduleRef: Module, moduleName: string)` | `void` | ## Diagram ```mermaid graph LR A[Middleware Configuration] --> B[MiddlewareResolver] B --> C[Resolve Middleware Instances] C --> D[Application Middleware Pipeline] D --> E[Request / Response Handling] ``` ## Usage ```ts import { MiddlewareResolver } from "@your-package/core"; // In most applications, the resolver is created or provided by the core runtime. function configureMiddleware(resolver: MiddlewareResolver) { const middlewareInstances = resolver.resolveInstances(); // Register the resolved middleware with the application's request pipeline. middlewareInstances.forEach((middleware) => { app.use(middleware); }); } ``` ## AI Coding Instructions - Use `resolveInstances()` as the single integration point for converting configured middleware into executable runtime instances. - Keep middleware registration order intact; middleware behavior often depends on its position in the request pipeline. - Ensure middleware dependencies are registered in the application's container before resolving instances. - Avoid manually instantiating middleware when the resolver is available, as this can bypass dependency injection or lifecycle handling. # RouterMethodFactory **Kind:** Class **Source:** [`packages/core/helpers/router-method-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/router-method-factory.ts#L23) **Part of:** [Core](subsystem-packages-core) `RouterMethodFactory` resolves an HTTP request method into the corresponding routing function on an HTTP server or router instance. It centralizes method lookup and falls back to the router's `use()` handler when a specific HTTP verb is unavailable. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(target: HttpServer, requestMethod: RequestMethod)` | `Function` | ## Where it refuses work - `RouterMethodFactory` stops the work with an early return when `!method`. ## Diagram ```mermaid graph LR A[RequestMethod] --> B[RouterMethodFactory.get] B --> C[REQUEST_METHOD_MAP] C --> D{Router supports method?} D -->|Yes| E[Return verb handler
get/post/put/etc.] D -->|No| F[Return use() fallback] E --> G[Register route handler] F --> G ``` ## Usage ```ts import { RequestMethod } from '@nestjs/common'; import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory'; const methodFactory = new RouterMethodFactory(); const router = app.getHttpAdapter().getInstance(); const registerGet = methodFactory.get(router, RequestMethod.GET); registerGet.call(router, '/health', (req, res) => { res.status(200).json({ status: 'ok' }); }); ``` ## AI Coding Instructions - Pass a router or HTTP server object that exposes verb methods such as `get`, `post`, `put`, and `delete`. - Use `RequestMethod` enum values rather than hard-coded method-name strings. - Preserve the router receiver when invoking an extracted route method if the underlying adapter depends on `this` (for example, use `.call(router, ...)`). - Account for the `use()` fallback when integrating adapters that do not implement every HTTP verb. - Keep HTTP-method-to-router-method mapping changes aligned with the framework's supported `RequestMethod` values. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ExpressAdapter` — `packages/platform-express/adapters/express-adapter.ts`:51 # ContextId **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L36) **Part of:** [Core](subsystem-packages-core) `ContextId` identifies a scoped dependency-injection context within the injector system. Its numeric `id` distinguishes the context, while `payload` can carry request-specific or execution-specific data associated with that context. ## Properties | Property | Type | |---|---| | `id` | `number` | | `payload` | `unknown` | ## Diagram ```mermaid graph LR A[Request or Execution Scope] --> B[ContextId] B --> C[id: number] B --> D[payload: unknown] B --> E[Injector / Instance Wrapper] E --> F[Scoped Provider Instance] ``` ## Usage ```ts import type { ContextId } from './packages/core/injector/instance-wrapper'; const requestContext: ContextId = { id: 42, payload: { requestId: 'req_123', userId: 'user_456', }, }; // Pass the context when resolving request-scoped dependencies. function resolveForContext(context: ContextId) { console.log(`Resolving providers for context ${context.id}`); return context.payload; } resolveForContext(requestContext); ``` ## AI Coding Instructions - Treat `id` as the stable identifier used to distinguish scoped provider instances. - Keep `payload` context-specific; narrow or validate its `unknown` type before reading properties. - Reuse the same `ContextId` throughout a single request or execution flow to preserve scoped dependency instances. - Avoid generating IDs manually when a context-id factory or injector integration already provides one. - Do not store long-lived global state in `payload`; it should represent data associated with a specific context. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `DurableContextIdStrategy` — `integration/inspector/src/durable/durable-context-id.strategy.ts`:6 - `TenantContext` — `integration/scopes/src/durable/durable-context-id.strategy.ts`:4 - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `TestingInjector` — `packages/testing/testing-injector.ts`:23 # ExternalExceptionFilter **Kind:** Class **Source:** [`packages/core/exceptions/external-exception-filter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/external-exception-filter.ts#L3) **Part of:** [Core](subsystem-packages-core) `ExternalExceptionFilter` defines the exception-handling contract used to process errors raised outside the normal request flow. Implement its `catch()` method to inspect an exception, access the current execution context, and return either a response value or a promise. ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: T, host: ArgumentsHost)` | `R | Promise` | ## Diagram ```mermaid graph LR A[Unhandled exception] --> B[ExternalExceptionFilter.catch] B --> C[ArgumentsHost] C --> D[Access transport context] B --> E[Create error response] E --> F[Return value or Promise] ``` ## Usage ```ts import type { ArgumentsHost } from '@nestjs/common'; import type { ExternalExceptionFilter } from '@nestjs/core'; class LoggingExceptionFilter implements ExternalExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { const response = host.switchToHttp().getResponse(); console.error('Unhandled external exception:', exception); return response.status(500).json({ statusCode: 500, message: 'Internal server error', }); } } // Register the filter with the relevant application integration point. const filter = new LoggingExceptionFilter(); ``` ## AI Coding Instructions - Implement `catch()` with the expected exception and `ArgumentsHost` parameters; it may return a value directly or a `Promise`. - Use `ArgumentsHost` to select the active transport context, such as HTTP, RPC, or WebSocket, before writing a response. - Avoid assuming every exception is an `Error`; safely handle strings, objects, and unknown thrown values. - Preserve framework-specific response conventions, including status codes and response serialization. - Log unexpected exceptions with useful context, but avoid exposing internal error details to clients. ## How it works ## `ExternalExceptionFilter` `ExternalExceptionFilter` is a generic exception-filter base class. Its `catch` method accepts an exception of type `T` and an `ArgumentsHost`, is declared to return `R | Promise`, but always throws the received exception instead of returning normally. [packages/core/exceptions/external-exception-filter.ts:3-6](packages/core/exceptions/external-exception-filter.ts#L3-L6) [packages/core/exceptions/external-exception-filter.ts:14](packages/core/exceptions/external-exception-filter.ts#L14) ## Relationships - IMPORTS → `ArgumentsHost` - IMPORTS → `IntrinsicException` - IMPORTS → `Logger` # INVALID_EXECUTION_CONTEXT **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L44) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function INVALID_EXECUTION_CONTEXT(methodName: string, currentContext: string) ``` ## Parameters | Name | Type | |---|---| | `methodName` | `string` | | `currentContext` | `string` | # MESSAGES **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L3) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { APPLICATION_START: `Starting Nest application...`, APPLICATION_READY: `Nest application successfully started`, MICROSERVICE_READY: `Nest microservice successfully started`, UNKNOWN_EXCEPTION_MESSAGE: 'Internal server error', ERROR_DURING_SHUTDOWN: 'Error happened during shutdown', CALL_LISTEN_FIRST: 'app.listen() needs to be called before calling app.getUrl()', } ``` ## Value ```ts { APPLICATION_START: `Starting Nest application...`, APPLICATION_READY: `Nest application successfully started`, MICROSERVICE_READY: `Nest microservice successfully started`, UNKNOWN_EXCEPTION_MESSAGE: 'Internal server error', ERROR_DURING_SHUTDOWN: 'Error happened during shutdown', CALL_LISTEN_FIRST: 'app.listen() needs to be called before calling app.getUrl()', } ``` ## Relationships - IMPORTS → `EnhancerSubtype` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `BaseRpcExceptionFilter` — `packages/microservices/exceptions/base-rpc-exception-filter.ts`:15 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 - `ErrorPayload` — `packages/websockets/exceptions/base-ws-exception-filter.ts`:11 # ParamsTokenFactory **Kind:** Class **Source:** [`packages/core/pipes/params-token-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/pipes/params-token-factory.ts#L4) **Part of:** [Core](subsystem-packages-core) `ParamsTokenFactory` normalizes route parameter metadata by converting known `RouteParamtypes` enum values into their string token equivalents. It is used by the pipes system to provide consistent parameter identifiers when resolving and applying pipes to controller arguments. ## Methods | Method | Signature | Returns | |---|---|---| | `exchangeEnumForString` | `exchangeEnumForString(type: RouteParamtypes)` | `Paramtype` | ## Diagram ```mermaid graph LR A[Route parameter metadata] --> B[ParamsTokenFactory] B --> C[exchangeEnumForString] C --> D[String parameter token] D --> E[Pipes context / parameter resolution] ``` ## Usage ```ts import { ParamsTokenFactory } from '@nestjs/core/pipes/params-token-factory'; import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; const paramsTokenFactory = new ParamsTokenFactory(); const token = paramsTokenFactory.exchangeEnumForString( RouteParamtypes.BODY, ); console.log(token); // "body" ``` ## AI Coding Instructions - Use `exchangeEnumForString()` when pipe-related code needs a stable string token for a route parameter type. - Preserve existing enum-to-string mappings when adding or modifying supported parameter types. - Return unrecognized parameter values unchanged so custom or already-normalized tokens remain compatible. - Keep this factory focused on token normalization; pipe execution and parameter extraction belong in their respective context creators. ## Relationships - IMPORTS → `Paramtype` - IMPORTS → `RouteParamtypes` # ReplLogger **Kind:** Class **Source:** [`packages/core/repl/repl-logger.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-logger.ts#L6) **Part of:** [Core](subsystem-packages-core) `ReplLogger` provides logging support for the REPL subsystem, centralizing how messages are emitted during interactive sessions. Its `log()` method should be used by REPL commands and runtime flows that need to report status, output, or diagnostic information consistently. **Extends:** `ConsoleLogger` ## Methods | Method | Signature | Returns | |---|---|---| | `log` | `log(_message: any, context: string)` | `void` | ## Where it refuses work - `ReplLogger` stops the work with an early return when `ReplLogger.ignoredContexts.includes(context!)`. ## Diagram ```mermaid graph LR Command[REPL Command] --> Logger[ReplLogger] Runtime[REPL Runtime] --> Logger Logger --> Output[Interactive Console Output] ``` ## Usage ```ts import { ReplLogger } from "./repl-logger"; const logger = new ReplLogger(); logger.log("REPL session started"); // Use the shared logger from command handlers or runtime operations. function runCommand(command: string) { logger.log(`Executing command: ${command}`); } runCommand("help"); ``` ## AI Coding Instructions - Use `ReplLogger.log()` for REPL-facing messages instead of writing directly to the console. - Keep logged messages concise and actionable because they are displayed in an interactive terminal context. - Reuse the logger instance managed by the REPL runtime when one is available; avoid creating unnecessary per-command instances. - Preserve existing output formatting and ordering so command output remains predictable for users and tests. ## How it works ## `ReplLogger` `ReplLogger` is a `ConsoleLogger` subclass used when `repl()` creates a Nest application context. The REPL passes a new instance as the context’s `logger` option before initializing the application. [packages/core/repl/repl-logger.ts:6](packages/core/repl/repl-logger.ts#L6) [packages/core/repl/repl.ts:16-20](packages/core/repl/repl.ts#L16-L20) It overrides only `log`; inherited methods such as `error`, `warn`, `debug`, `verbose`, and `fatal` are not overridden. [packages/core/repl/repl-logger.ts:13-19](packages/core/repl/repl-logger.ts#L13-L19) [packages/common/services/console-logger.service.ts:192-276](packages/common/services/console-logger.service.ts#L192-L276) ## Relationships - IMPORTS → `ConsoleLogger` # UnknownDependenciesException **Kind:** Class **Source:** [`packages/core/errors/exceptions/unknown-dependencies.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/unknown-dependencies.exception.ts#L6) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` ## Properties | Property | Type | |---|---| | `moduleRef` | `{ id: string } | undefined` | # assignToken **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L113) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function assignToken(metatype: Type, token): Type ``` ## Parameters | Name | Type | |---|---| | `metatype` | `Type` | | `token` | `any` | **Returns:** `Type` # getNonTransientInstances **Kind:** Function **Source:** [`packages/core/injector/helpers/transient-instances.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/helpers/transient-instances.ts#L25) **Part of:** [Core](subsystem-packages-core) Returns the instances which are not transient `getNonTransientInstances` filters provider instance entries and returns only those whose scope is not `Scope.TRANSIENT`. It is used by the injector lifecycle to identify reusable or request-scoped providers while excluding providers that must be created for every injection. ## Signature ```ts function getNonTransientInstances(instances: [InjectionToken, InstanceWrapper][]): InstanceWrapper[] ``` ## Parameters | Name | Type | |---|---| | `instances` | `[InjectionToken, InstanceWrapper][]` | **Returns:** `InstanceWrapper[]` ## Diagram ```mermaid graph LR A[Provider instance entries] --> B[getNonTransientInstances] B --> C{scope is TRANSIENT?} C -->|Yes| D[Exclude entry] C -->|No| E[Return entry] E --> F[Default and request-scoped providers] ``` ## Usage ```ts import { Scope } from '@nestjs/common'; import { getNonTransientInstances } from '@nestjs/core/injector/helpers/transient-instances'; import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; const providerEntries: [string, InstanceWrapper][] = [ ['CacheService', { scope: Scope.DEFAULT } as InstanceWrapper], ['RequestContext', { scope: Scope.REQUEST } as InstanceWrapper], ['AuditService', { scope: Scope.TRANSIENT } as InstanceWrapper], ]; const nonTransientProviders = getNonTransientInstances(providerEntries); // Includes CacheService and RequestContext. // Excludes AuditService. console.log(nonTransientProviders.map(([token]) => token)); ``` ## AI Coding Instructions - Pass provider entries as `[token, InstanceWrapper]` tuples, typically from a module provider map via `Array.from(providers.entries())`. - Treat `Scope.TRANSIENT` providers as per-injection instances; do not include them in reuse, preload, or static lifecycle processing. - Preserve the original tuple structure so downstream injector code can access both the provider token and its wrapper. - Use this helper alongside transient-specific filtering helpers instead of duplicating scope checks throughout injector code. # getTransientInstances **Kind:** Function **Source:** [`packages/core/injector/helpers/transient-instances.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/helpers/transient-instances.ts#L9) **Part of:** [Core](subsystem-packages-core) Returns the instances which are transient `getTransientInstances` filters a collection of injector-managed instances and returns only those configured with transient lifetime behavior. It is used by the core injector to identify providers that must be created separately for each resolution rather than reused from a shared instance. ## Signature ```ts function getTransientInstances(instances: [InjectionToken, InstanceWrapper][]): InstanceWrapper[] ``` ## Parameters | Name | Type | |---|---| | `instances` | `[InjectionToken, InstanceWrapper][]` | **Returns:** `InstanceWrapper[]` ## Diagram ```mermaid graph LR A[Registered injector instances] --> B[getTransientInstances] B --> C{Transient scope?} C -->|Yes| D[Transient instances] C -->|No| E[Ignored shared/request-scoped instances] ``` ## Usage ```ts import { getTransientInstances } from './helpers/transient-instances'; // `providers` is the injector's registered provider collection. const transientProviders = getTransientInstances(providers); for (const provider of transientProviders) { // Resolve or initialize providers that require a new instance per use. await injector.loadProvider(provider, moduleRef); } ``` ## AI Coding Instructions - Use this helper when code needs to operate only on transient providers; do not duplicate transient-scope filtering at call sites. - Ensure provider metadata and scope have been assigned before calling the helper. - Preserve the injector's existing instance-wrapper types and collection structure when passing instances to this function. - Do not treat transient instances as cacheable singletons; each resolution may require a fresh instance. ## Relationships - IMPORTS → `InjectionToken` # HttpAdapterHost **Kind:** Class **Source:** [`packages/core/helpers/http-adapter-host.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/http-adapter-host.ts#L16) **Part of:** [Core](subsystem-packages-core) Defines the `HttpAdapterHost` object. `HttpAdapterHost` wraps the underlying platform-specific `HttpAdapter`. The `HttpAdapter` is a wrapper around the underlying native HTTP server library (e.g., Express). The `HttpAdapterHost` object provides methods to `get` and `set` the underlying HttpAdapter. `HttpAdapterHost` provides access to the platform-specific `HttpAdapter` used by the application, such as the Express or Fastify adapter. It acts as a shared integration point for framework features that need to inspect or interact with the underlying HTTP server without depending on a specific platform. ## Diagram ```mermaid graph LR A[Nest Application] --> B[HttpAdapterHost] B --> C[HttpAdapter] C --> D[Express Adapter] C --> E[Fastify Adapter] D --> F[Native Express Server] E --> G[Native Fastify Server] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HttpAdapterHost } from '@nestjs/core'; @Injectable() export class ServerInfoService { constructor( private readonly adapterHost: HttpAdapterHost, ) {} getPlatform(): string { const httpAdapter = this.adapterHost.httpAdapter; return httpAdapter.getType(); // "express" or "fastify" } getHttpServer() { return this.adapterHost.httpAdapter.getHttpServer(); } } ``` ## AI Coding Instructions - Inject `HttpAdapterHost` through Nest's dependency injection container instead of creating it manually in application services. - Access the current platform adapter through the `httpAdapter` property; avoid casting directly to Express or Fastify unless platform-specific behavior is required. - Use adapter abstraction methods such as `getType()` and `getHttpServer()` to keep integrations portable across supported HTTP platforms. - Ensure the HTTP adapter has been initialized before relying on native server behavior, especially in bootstrap, testing, or lifecycle-sensitive code. # INVALID_MIDDLEWARE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L143) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function INVALID_MIDDLEWARE_MESSAGE(text: TemplateStringsArray, name: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `name` | `string` | # isMiddlewareClass **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L100) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isMiddlewareClass(middleware: any): middleware is Type ``` ## Parameters | Name | Type | |---|---| | `middleware` | `any` | **Returns:** `middleware is Type` # MODULE_INIT_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L7) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function MODULE_INIT_MESSAGE(text: TemplateStringsArray, module: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `module` | `string` | ## Relationships - IMPORTS → `RequestMethod` - IMPORTS → `VersionValue` - IMPORTS → `VERSION_NEUTRAL` # ContextIdStrategy **Kind:** Interface **Source:** [`packages/core/helpers/context-id-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-id-factory.ts#L30) **Part of:** [Core](subsystem-packages-core) ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `DurableContextIdStrategy` — `integration/inspector/src/durable/durable-context-id.strategy.ts`:6 - `TenantContext` — `integration/scopes/src/durable/durable-context-id.strategy.ts`:4 # STATIC_CONTEXT **Kind:** Constant **Source:** [`packages/core/injector/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/constants.ts#L6) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts ContextId ``` ## Value ```ts Object.freeze({ id: STATIC_CONTEXT_ID, }) ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `ExceptionFiltersContext` — `packages/microservices/context/exception-filters-context.ts`:16 - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 - `TestingInjector` — `packages/testing/testing-injector.ts`:23 # ExceptionHandler **Kind:** Class **Source:** [`packages/core/errors/exception-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exception-handler.ts#L3) **Part of:** [Core](subsystem-packages-core) `ExceptionHandler` centralizes application error handling within the core error layer. Its `handle()` method receives an exception, applies the project's error-handling policy, and translates it into the appropriate logging, response, or propagation behavior for the calling layer. ## Methods | Method | Signature | Returns | |---|---|---| | `handle` | `handle(exception: Error)` | `void` | ## Diagram ```mermaid graph LR A[Application Code] -->|throws or catches error| B[ExceptionHandler] B -->|handle(error)| C{Classify Exception} C --> D[Log / Report Error] C --> E[Create Standardized Error Result] E --> F[API, Worker, or Caller] ``` ## Usage ```ts import { ExceptionHandler } from "@your-project/core/errors/exception-handler"; const exceptionHandler = new ExceptionHandler(); try { await processOrder(orderId); } catch (error) { return exceptionHandler.handle(error); } ``` ## AI Coding Instructions - Route caught application errors through `ExceptionHandler.handle()` instead of duplicating error-formatting logic in controllers, services, or jobs. - Preserve the original error when passing it to `handle()`; avoid replacing it with a generic message before the handler can classify it. - Keep domain-specific validation and business errors distinguishable from unexpected infrastructure errors so the handler can apply the correct response policy. - Ensure new execution entry points, such as HTTP handlers, queue consumers, and CLI commands, integrate with this centralized error-handling path. ## Relationships - IMPORTS → `Logger` # HostComponentInfo **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L25) **Part of:** [Core](subsystem-packages-core) `HostComponentInfo` describes metadata associated with the component that hosts a provider or dependency instance. It identifies the host through its injection `token` and indicates whether the host belongs to a durable dependency tree via `isTreeDurable`. ## Properties | Property | Type | |---|---| | `token` | `InjectionToken` | | `isTreeDurable` | `boolean` | ## Diagram ```mermaid graph LR Wrapper[Instance Wrapper] --> HostInfo[HostComponentInfo] HostInfo --> Token[token: InjectionToken] HostInfo --> Durable[isTreeDurable: boolean] Token --> HostComponent[Host Component / Provider] Durable --> Tree[Dependency Tree Durability] ``` ## Usage ```ts import type { InjectionToken } from '@nestjs/common'; import type { HostComponentInfo } from '@nestjs/core/injector/instance-wrapper'; class UsersService {} const hostComponentInfo: HostComponentInfo = { token: UsersService as InjectionToken, isTreeDurable: true, }; // Store this metadata when creating or inspecting an instance wrapper. function registerHost(info: HostComponentInfo) { console.log(`Host token: ${String(info.token)}`); console.log(`Tree durable: ${info.isTreeDurable}`); } registerHost(hostComponentInfo); ``` ## AI Coding Instructions - Preserve both fields when cloning, transforming, or forwarding host component metadata. - Use the same injection token that identifies the owning provider or component; do not substitute an instance value. - Set `isTreeDurable` based on dependency-tree durability rules, especially when working with scoped providers. - Treat `token` as an `InjectionToken`, which may be a class, string, symbol, or custom token. - Keep this interface focused on host metadata; lifecycle and instance state belong on the surrounding instance wrapper. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `DurableContextIdStrategy` — `integration/inspector/src/durable/durable-context-id.strategy.ts`:6 - `TenantContext` — `integration/scopes/src/durable/durable-context-id.strategy.ts`:4 # InjectorDependencyContext **Kind:** Interface **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L67) **Part of:** [Core](subsystem-packages-core) Context of a dependency which gets injected by the injector `InjectorDependencyContext` describes a dependency request being resolved by the injector. It captures the dependency token (`key`), the requesting constructor or identifier (`name`), the parameter position (`index`), and any nested dependencies needed to complete resolution. ## Properties | Property | Type | |---|---| | `key` | `string | symbol` | | `name` | `Function | string | symbol` | | `index` | `number` | | `dependencies` | `InjectorDependency[]` | ## Diagram ```mermaid graph LR A[Injectable constructor or factory] --> B[InjectorDependencyContext] B --> C[key: string | symbol] B --> D[name: Function | string | symbol] B --> E[index: number] B --> F[dependencies: InjectorDependency[]] F --> G[Resolved dependency graph] ``` ## Usage ```ts import type { InjectorDependencyContext } from "./injector"; function describeDependency(context: InjectorDependencyContext): string { const owner = typeof context.name === "function" ? context.name.name : String(context.name); return `Resolving "${String(context.key)}" for ${owner} at parameter ${context.index}`; } const context: InjectorDependencyContext = { key: "logger", name: "UserService", index: 0, dependencies: [], }; console.log(describeDependency(context)); // Resolving "logger" for UserService at parameter 0 ``` ## AI Coding Instructions - Use `key` as the dependency token being requested; preserve whether it is a `string` or `symbol`. - Set `name` to the requesting class, factory, or identifier so injector errors can provide useful context. - Treat `index` as the zero-based parameter position in the target constructor or function. - Populate `dependencies` when resolving nested dependency graphs or when reporting chained resolution failures. - Avoid assuming `name` is always a constructor; it may also be a string or symbol. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingInjector` — `packages/testing/testing-injector.ts`:23 # isValueProvider **Kind:** Function **Source:** [`packages/core/injector/helpers/provider-classifier.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/helpers/provider-classifier.ts#L15) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isValueProvider(provider: Provider): provider is ValueProvider ``` ## Parameters | Name | Type | |---|---| | `provider` | `Provider` | **Returns:** `provider is ValueProvider` # RoutePathMetadata **Kind:** Interface **Source:** [`packages/core/router/interfaces/route-path-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/route-path-metadata.interface.ts#L4) **Part of:** [Core](subsystem-packages-core) `RoutePathMetadata` aggregates all path and versioning inputs needed to construct a controller route. The router uses it to combine global, module, controller, and method paths while applying controller- or method-level API versioning configuration. ## Properties | Property | Type | |---|---| | `ctrlPath` | `string` | | `methodPath` | `string` | | `globalPrefix` | `string` | | `modulePath` | `string` | | `controllerVersion` | `VersionValue` | | `methodVersion` | `VersionValue` | | `versioningOptions` | `VersioningOptions` | ## Diagram ```mermaid graph LR GP[globalPrefix] --> RP[RoutePathMetadata] MP[modulePath] --> RP CP[ctrlPath] --> RP MTP[methodPath] --> RP CV[controllerVersion] --> RP MV[methodVersion] --> RP VO[versioningOptions] --> RP RP --> URL[Resolved Route URL] ``` ## Usage ```ts import { VersioningType } from '@nestjs/common'; import { RoutePathMetadata } from '@nestjs/core/router/interfaces/route-path-metadata.interface'; const routeMetadata: RoutePathMetadata = { globalPrefix: 'api', modulePath: 'users', ctrlPath: 'profiles', methodPath: ':id', controllerVersion: '1', methodVersion: '2', versioningOptions: { type: VersioningType.URI, }, }; // Used internally to resolve a route such as: // /api/v2/users/profiles/:id ``` ## AI Coding Instructions - Preserve each path segment separately; route composition should be handled by the router rather than manual string concatenation. - Treat `methodVersion` as the more specific version value when method- and controller-level versions both exist. - Ensure `versioningOptions` matches the application's configured versioning strategy, such as `URI`, `HEADER`, or `MEDIA_TYPE`. - Avoid including leading or trailing slash assumptions in consumers; normalize paths when constructing the final route. ## How it works ## `RoutePathMetadata` `RoutePathMetadata` is an exported TypeScript interface that groups optional path fragments and API-versioning metadata used while constructing and registering HTTP route paths. It declares no methods or runtime logic; all seven properties are optional. [route-path-metadata.interface.ts:4-39] ## Relationships - IMPORTS → `VersioningOptions` - IMPORTS → `VersionValue` # UNDEFINED_FORWARDREF_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L148) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function UNDEFINED_FORWARDREF_MESSAGE(scope: Type[]) ``` ## Parameters | Name | Type | |---|---| | `scope` | `Type[]` | # UNKNOWN_REQUEST_MAPPING **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L253) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function UNKNOWN_REQUEST_MAPPING(metatype: Type) ``` ## Parameters | Name | Type | |---|---| | `metatype` | `Type` | # ClassNode **Kind:** Type **Source:** [`packages/core/inspector/interfaces/node.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/node.interface.ts#L13) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { parent: string; metadata: { type: 'provider' | 'controller' | 'middleware' | 'injectable'; subtype?: EnhancerSubtype; sourceModuleName: string; durable: boolean; static: boolean; transient: boolean; exported: boolean; scope: Scope; token: InjectionToken; initTime: number; enhancers?: Array< | { id: string; subtype: EnhancerSubtype } | { name: string; methodKey?: string; subtype: EnhancerSubtype } >; global?: boolean; internal?: boolean; }; } ``` # CONTROLLER_MAPPING_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L28) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function CONTROLLER_MAPPING_MESSAGE(name: string, path: string) ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `path` | `string` | # INVALID_CLASS_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L242) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function INVALID_CLASS_MESSAGE(text: TemplateStringsArray, value: any) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `value` | `any` | # isClassProvider **Kind:** Function **Source:** [`packages/core/injector/helpers/provider-classifier.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/helpers/provider-classifier.ts#L9) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isClassProvider(provider: Provider): provider is ClassProvider ``` ## Parameters | Name | Type | |---|---| | `provider` | `Provider` | **Returns:** `provider is ClassProvider` ## Relationships - IMPORTS → `ClassProvider` - IMPORTS → `FactoryProvider` - IMPORTS → `Provider` - IMPORTS → `ValueProvider` - IMPORTS → `isUndefined` # isFactoryProvider **Kind:** Function **Source:** [`packages/core/injector/helpers/provider-classifier.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/helpers/provider-classifier.ts#L22) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isFactoryProvider(provider: Provider): provider is FactoryProvider ``` ## Parameters | Name | Type | |---|---| | `provider` | `Provider` | **Returns:** `provider is FactoryProvider` # ROUTE_MAPPED_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L12) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function ROUTE_MAPPED_MESSAGE(path: string, method: string | number) ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | | `method` | `string | number` | # DiscoveryModule **Kind:** Class **Source:** [`packages/core/discovery/discovery-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-module.ts#L8) **Part of:** [Core](subsystem-packages-core) ## Relationships - IMPORTS → `Module` ## Used by 2 references from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AppModule` — `integration/discovery/src/app.module.ts`:6 ### Imported by (1) - `AppModule` — `integration/discovery/src/app.module.ts`:6 # getClassScope **Kind:** Function **Source:** [`packages/core/helpers/get-class-scope.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/get-class-scope.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function getClassScope(provider: Type): Scope ``` ## Parameters | Name | Type | |---|---| | `provider` | `Type` | **Returns:** `Scope` ## Relationships - IMPORTS → `Scope` - IMPORTS → `SCOPE_OPTIONS_METADATA` - IMPORTS → `Type` # InvalidExceptionFilterException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-exception-filter.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-exception-filter.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `RpcExceptionsHandler` — `packages/microservices/exceptions/rpc-exceptions-handler.ts`:13 - `WsExceptionsHandler` — `packages/websockets/exceptions/ws-exceptions-handler.ts`:12 # isDurable **Kind:** Function **Source:** [`packages/core/helpers/is-durable.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/is-durable.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isDurable(provider: Type): boolean | undefined ``` ## Parameters | Name | Type | |---|---| | `provider` | `Type` | **Returns:** `boolean | undefined` ## Relationships - IMPORTS → `SCOPE_OPTIONS_METADATA` - IMPORTS → `Type` # ModuleDefinition **Kind:** Type **Source:** [`packages/core/interfaces/module-definition.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/interfaces/module-definition.interface.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts | ForwardReference | Type | DynamicModule | Promise ``` ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `Type` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `OverrideModule` — `packages/testing/interfaces/override-module.interface.ts`:7 - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # ModuleOpaqueKeyFactory **Kind:** Interface **Source:** [`packages/core/injector/opaque-key-factory/interfaces/module-opaque-key-factory.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/opaque-key-factory/interfaces/module-opaque-key-factory.interface.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `Type` # APP_INTERCEPTOR **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L13) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'APP_INTERCEPTOR' ``` ## Value ```ts 'APP_INTERCEPTOR' ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `CoreModule` — `integration/inspector/src/core/core.module.ts`:8 - `CoreModule` — `sample/01-cats-app/src/core/core.module.ts`:6 - `CoreModule` — `sample/10-fastify/src/core/core.module.ts`:6 - `CoreModule` — `sample/36-hmr-esm/src/core/core.module.ts`:6 # isRequestMethodAll **Kind:** Function **Source:** [`packages/core/router/utils/exclude-route.util.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/utils/exclude-route.util.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function isRequestMethodAll(method: RequestMethod) ``` ## Parameters | Name | Type | |---|---| | `method` | `RequestMethod` | ## Relationships - IMPORTS → `RequestMethod` - IMPORTS → `addLeadingSlash` # REQUEST_METHOD_MAP **Kind:** Constant **Source:** [`packages/core/helpers/router-method-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/router-method-factory.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { [RequestMethod.GET]: 'get', [RequestMethod.POST]: 'post', [RequestMethod.PUT]: 'put', [RequestMethod.DELETE]: 'delete', [RequestMethod.PATCH]: 'patch', [RequestMethod.ALL]: 'all', [RequestMethod.OPTIONS]: 'options', [RequestMethod.HEAD]: 'head', [RequestMethod.SEARCH]: 'search', [RequestMethod.PROPFIND]: 'propfind', [RequestMethod.PROPPATCH]: 'proppatch', [RequestMethod.M… ``` ## Value ```ts { [RequestMethod.GET]: 'get', [RequestMethod.POST]: 'post', [RequestMethod.PUT]: 'put', [RequestMethod.DELETE]: 'delete', [RequestMethod.PATCH]: 'patch', [RequestMethod.ALL]: 'all', [RequestMethod.OPTIONS]: 'options', [RequestMethod.HEAD]: 'head', [RequestMethod.SEARCH]: 'search', [RequestMethod.PROPFIND]: 'propfind', [RequestMethod.PROPPATCH]: 'proppatch', [RequestMethod.M… ``` ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `RequestMethod` # rethrow **Kind:** Function **Source:** [`packages/core/helpers/rethrow.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/rethrow.ts#L1) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function rethrow(err: unknown) ``` ## Parameters | Name | Type | |---|---| | `err` | `unknown` | # CreateDecoratorOptions **Kind:** Interface **Source:** [`packages/core/services/reflector.service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/services/reflector.service.ts#L8) **Part of:** [Core](subsystem-packages-core) `CreateDecoratorOptions` configures how a reflector decorator reads and transforms metadata values. It defines the metadata `key` to access and a `transform` function that converts the raw parameter value into the type consumed by the decorator or reflector service. ## Properties | Property | Type | |---|---| | `key` | `string` | | `transform` | `(value: TParam) => TTransformed` | ## Diagram ```mermaid graph LR A[Decorator Invocation] --> B[CreateDecoratorOptions] B --> C[key: string] B --> D[transform(value)] C --> E[Reflector Metadata Lookup] E --> F[Raw Metadata Value] F --> D D --> G[Transformed Metadata Value] ``` ## Usage ```ts import type { CreateDecoratorOptions } from '@nestjs/core/services/reflector.service'; interface RoleOptions { roles: string[]; } const roleDecoratorOptions: CreateDecoratorOptions< string[], RoleOptions > = { key: 'roles', transform: (roles) => ({ roles: roles.map((role) => role.toLowerCase()), }), }; // The transform function receives the raw metadata value and returns // the normalized value used by the application. const normalizedRoles = roleDecoratorOptions.transform(['ADMIN', 'EDITOR']); // { roles: ['admin', 'editor'] } console.log(normalizedRoles); ``` ## AI Coding Instructions - Use a stable, unique `key` string that matches the metadata key used by the associated decorator. - Keep `transform` pure: it should convert the input value without mutating it or relying on external state. - Type `TParam` to match the raw decorator input and `TTransformed` to match the value consumers should receive. - Validate or normalize optional, array, and nested values inside `transform` when downstream code expects a consistent shape. - Ensure metadata readers use the same key and expect the transformed output type rather than the raw decorator argument. ## Relationships - IMPORTS → `CustomDecorator` - IMPORTS → `SetMetadata` - IMPORTS → `Type` - IMPORTS → `isEmpty` - IMPORTS → `isObject` # ExcludeRouteMetadata **Kind:** Interface **Source:** [`packages/core/router/interfaces/exclude-route-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/exclude-route-metadata.interface.ts#L3) **Part of:** [Core](subsystem-packages-core) `ExcludeRouteMetadata` describes a route that should be excluded from router-level behavior, such as middleware or guard application. It combines the original route `path`, a compiled `pathRegex` used for matching requests, and the associated NestJS `requestMethod`. ## Properties | Property | Type | |---|---| | `path` | `string` | | `pathRegex` | `RegExp` | | `requestMethod` | `RequestMethod` | ## Diagram ```mermaid graph LR A[Incoming Request] --> B{Request Method Matches?} B -->|Yes| C{Path Matches pathRegex?} B -->|No| D[Do Not Exclude] C -->|Yes| E[Exclude Route Behavior] C -->|No| D F[ExcludeRouteMetadata] --> G[path: string] F --> H[pathRegex: RegExp] F --> I[requestMethod: RequestMethod] ``` ## Usage ```ts import { RequestMethod } from '@nestjs/common'; import { ExcludeRouteMetadata } from './interfaces/exclude-route-metadata.interface'; const excludedHealthCheck: ExcludeRouteMetadata = { path: '/health', pathRegex: /^\/health\/?$/, requestMethod: RequestMethod.GET, }; function shouldExclude( route: ExcludeRouteMetadata, path: string, method: RequestMethod, ): boolean { return ( route.requestMethod === method && route.pathRegex.test(path) ); } shouldExclude(excludedHealthCheck, '/health', RequestMethod.GET); // true ``` ## AI Coding Instructions - Keep `path` as the human-readable route definition and use `pathRegex` for runtime path matching. - Ensure `pathRegex` matches both expected route parameters and optional trailing slashes when required. - Compare `requestMethod` with NestJS `RequestMethod` enum values rather than raw HTTP method strings. - Reset or avoid stateful regular expressions using the `g` or `y` flags before calling `.test()` repeatedly. - Use this metadata when integrating route exclusion logic into middleware, guards, interceptors, or router configuration. ## How it works `ExcludeRouteMetadata` is a TypeScript interface for a route that is excluded from matching behavior such as global-prefix application or middleware execution. It has no executable members itself. [packages/core/router/interfaces/exclude-route-metadata.interface.ts:3-18] Its required fields are: - `path: string` — the route path. [packages/core/router/interfaces/exclude-route-metadata.interface.ts:4-7] - `pathRegex: RegExp` — a regular expression for that path. [packages/core/router/interfaces/exclude-route-metadata.interface.ts:9-12] - `requestMethod: RequestMethod` — the HTTP method associated with the exclusion. [packages/core/router/interfaces/exclude-route-metadata.interface.ts:14-17] Internal mapping converts each configured exclusion from either a path string or `RouteInfo` into this shape. It converts legacy path syntax, builds `pathRegex` from the slash-prefixed converted path, and assigns `RequestMethod.ALL` for string entries or the source route’s method for `RouteInfo` entries. [packages/core/middleware/utils.ts:15-34] If regular-expression construction throws a `TypeError`, that mapper calls `LegacyRouteConverter.printError(originalPath)` and rethrows the same error. [packages/core/middleware/utils.ts:35-40] Exclusion matching first accepts a route when its metadata method is `RequestMethod.ALL` (or numeric `-1`) or equals the requested method; it then runs `pathRegex` against the slash-prefixed candidate path. [packages/core/router/utils/exclude-route.util.ts:5-22] For global prefixes, `NestApplication.setGlobalPrefix()` maps configured `options.exclude` entries into `ExcludeRouteMetadata` records and stores them in application configuration. [packages/core/nest-application.ts:379-390] During route-path creation, a matching exclusion leaves the route path without the global prefix; nonmatching paths receive the prefix. [packages/core/router/route-path-factory.ts:59-77][packages/core/router/route-path-factory.ts:117-143] For middleware exclusions, the request URL is read from the HTTP adapter, stripped of its query string, and matched with the adapter-reported request method. When matched, generated middleware wrappers call `next()` rather than invoking the middleware. [packages/core/middleware/utils.ts:67-78][packages/core/middleware/utils.ts:84-95][packages/core/middleware/utils.ts:118-135] ## Relationships - IMPORTS → `RequestMethod` # HandlerMetadata **Kind:** Interface **Source:** [`packages/core/helpers/handler-metadata-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/handler-metadata-storage.ts#L29) **Part of:** [Core](subsystem-packages-core) `HandlerMetadata` describes the runtime metadata required to invoke and serialize the result of a controller handler. It combines parameter resolution details, HTTP response configuration, SSE behavior, custom headers, and the response-handling function used by the request execution pipeline. ## Properties | Property | Type | |---|---| | `argsLength` | `number` | | `isSseHandler` | `boolean` | | `paramtypes` | `any[]` | | `httpStatusCode` | `number` | | `responseHeaders` | `any[]` | | `hasCustomHeaders` | `boolean` | | `getParamsMetadata` | `( moduleKey: string, contextId?: ContextId, inquirerId?: string, ) => (ParamProperties & { metatype?: any })[]` | | `fnHandleResponse` | `HandleResponseFn` | ## Diagram ```mermaid graph LR Request[Incoming Request] --> Metadata[HandlerMetadata] Metadata --> Params[getParamsMetadata] Params --> Handler[Controller Handler] Metadata --> Status[httpStatusCode] Metadata --> Headers[responseHeaders] Metadata --> SSE[isSseHandler] Handler --> ResponseHandler[fnHandleResponse] Status --> ResponseHandler Headers --> ResponseHandler SSE --> ResponseHandler ResponseHandler --> Response[HTTP Response] ``` ## Usage ```ts import type { HandlerMetadata } from './handler-metadata-storage'; const metadata: HandlerMetadata = { argsLength: 2, isSseHandler: false, paramtypes: [String, Number], httpStatusCode: 201, responseHeaders: [{ name: 'x-api-version', value: 'v1' }], hasCustomHeaders: true, getParamsMetadata: (moduleKey, contextId, inquirerId) => [ { index: 0, type: 'body', data: undefined, metatype: String, }, { index: 1, type: 'param', data: 'id', metatype: Number, }, ], fnHandleResponse: async ( result, response, request, ) => { response.status(201); response.setHeader('x-api-version', 'v1'); response.send(result); }, }; // The request pipeline uses this metadata to resolve handler arguments // and apply the configured response behavior. ``` ## AI Coding Instructions - Use `getParamsMetadata()` to resolve parameter metadata per module and DI context; do not treat parameter metadata as globally static when request-scoped providers are involved. - Keep `argsLength` aligned with the target handler's declared argument positions, including optional or injected parameters. - Set `isSseHandler` only for streaming Server-Sent Events handlers; SSE responses require different lifecycle and serialization behavior. - When adding response headers, update both `responseHeaders` and `hasCustomHeaders` so the response pipeline applies them correctly. - Ensure `fnHandleResponse` respects the configured HTTP status, headers, and adapter-specific response APIs. # InternalProvidersStorage **Kind:** Class **Source:** [`packages/core/injector/internal-providers-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/internal-providers-storage.ts#L4) **Part of:** [Core](subsystem-packages-core) # InvalidClassModuleException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-class-module.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-class-module.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # ModuleRefGetOrResolveOpts **Kind:** Interface **Source:** [`packages/core/injector/module-ref.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/module-ref.ts#L12) **Part of:** [Core](subsystem-packages-core) `ModuleRefGetOrResolveOpts` configures how a provider is retrieved or resolved from a module reference. Use `strict` to control whether lookup is limited to the current module context, and `each` to request all matching provider instances instead of a single result. ## Properties | Property | Type | |---|---| | `strict` | `boolean` | | `each` | `boolean` | ## Diagram ```mermaid graph LR A[ModuleRef.get / resolve] --> B[ModuleRefGetOrResolveOpts] B --> C{strict} C -->|true| D[Search current module context] C -->|false| E[Search broader module graph] B --> F{each} F -->|true| G[Return all matching instances] F -->|false| H[Return one matching instance] ``` ## Usage ```ts import { ModuleRef } from '@nestjs/core'; class UserService { constructor(private readonly moduleRef: ModuleRef) {} getLocalRepository() { return this.moduleRef.get(UserRepository, { strict: true, each: false, }); } getAllHandlers() { return this.moduleRef.get(APP_HANDLER, { strict: false, each: true, }); } } ``` ## AI Coding Instructions - Pass `strict: true` when the dependency must be registered in the current module and should not be resolved from imported or global modules. - Use `strict: false` for cross-module lookups, especially when resolving shared or globally available providers. - Set `each: true` only for multi-provider tokens where multiple matching instances are expected. - Handle the return shape carefully: `each: false` returns a single instance, while `each: true` returns a collection of instances. - Keep lookup options aligned with the `ModuleRef.get()` or `ModuleRef.resolve()` call so provider scope and module visibility behave as intended. ## Relationships - IMPORTS → `IntrospectionResult` - IMPORTS → `Scope` - IMPORTS → `Type` # NoopGraphInspector **Kind:** Constant **Source:** [`packages/core/inspector/noop-graph-inspector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/noop-graph-inspector.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts GraphInspector ``` ## Value ```ts new Proxy( GraphInspector.prototype, { get: () => noop, }, ) ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # ReplFnDefinition **Kind:** Type **Source:** [`packages/core/repl/repl.interfaces.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl.interfaces.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { name: string; aliases?: ReplFnDefinition['name'][]; description: string; signature: string; } ``` # ContextIdResolver **Kind:** Interface **Source:** [`packages/core/helpers/context-id-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-id-factory.ts#L19) **Part of:** [Core](subsystem-packages-core) `ContextIdResolver` defines how Nest resolves a dependency-injection context ID for a given request or runtime payload. It pairs the original `payload` with a `resolve` function that selects the appropriate `ContextId`, enabling custom request-scoped and durable provider behavior. ## Properties | Property | Type | |---|---| | `payload` | `unknown` | | `resolve` | `ContextIdResolverFn` | ## Diagram ```mermaid graph LR A[Incoming Request / Payload] --> B[ContextIdStrategy.attach] B --> C[ContextIdResolver] C --> D[payload] C --> E[resolve HostComponentInfo] E --> F[ContextId] F --> G[Request-Scoped Provider Resolution] ``` ## Usage ```ts import { ContextIdFactory, ContextIdResolver, ContextIdStrategy, HostComponentInfo, } from '@nestjs/core'; class CustomContextIdStrategy implements ContextIdStrategy { attach(contextId: object, request: unknown): ContextIdResolver { return { payload: request, resolve: (info: HostComponentInfo) => { // Reuse the same context for durable dependency trees. if (info.isTreeDurable) { return contextId; } // Create an isolated context for non-durable providers. return ContextIdFactory.create(); }, }; } } ContextIdFactory.apply(new CustomContextIdStrategy()); ``` ## AI Coding Instructions - Return both the original request or runtime value through `payload` and a `resolve` function for selecting context IDs. - Use `resolve` to distinguish durable provider trees from providers that require isolated request contexts. - Ensure `resolve` always returns a valid `ContextId`, typically the supplied `contextId` or one created with `ContextIdFactory.create()`. - Register custom resolver behavior through a `ContextIdStrategy` and `ContextIdFactory.apply()`, rather than constructing resolvers in application code. - Avoid storing mutable request-specific state in shared resolver instances; use the `payload` for per-request data. # createContextId **Kind:** Function **Source:** [`packages/core/helpers/context-id-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-id-factory.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Signature ```ts function createContextId(): ContextId ``` **Returns:** `ContextId` ## Relationships - IMPORTS → `isObject` # ENHANCER_TOKEN_TO_SUBTYPE_MAP **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L17) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Record< | typeof APP_GUARD | typeof APP_PIPE | typeof APP_FILTER | typeof APP_INTERCEPTOR, EnhancerSubtype > ``` ## Value ```ts { [APP_GUARD]: 'guard', [APP_INTERCEPTOR]: 'interceptor', [APP_PIPE]: 'pipe', [APP_FILTER]: 'filter', } as const ``` # InvalidClassScopeException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-class-scope.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-class-scope.exception.ts#L6) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `Abstract` - IMPORTS → `Type` - IMPORTS → `isFunction` # InvalidModuleException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-module.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-module.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # IRouteParamsFactory **Kind:** Interface **Source:** [`packages/core/router/interfaces/route-params-factory.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/route-params-factory.interface.ts#L3) **Part of:** [Core](subsystem-packages-core) ## Relationships - IMPORTS → `RouteParamtypes` # ParamProperties **Kind:** Interface **Source:** [`packages/core/router/router-execution-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-execution-context.ts#L50) **Part of:** [Core](subsystem-packages-core) `ParamProperties` describes how a controller method parameter is resolved during route execution. It stores the parameter’s position, route parameter type, optional metadata, transformation pipes, and an extractor function that reads the value from the request lifecycle. ## Properties | Property | Type | |---|---| | `index` | `number` | | `type` | `RouteParamtypes | string` | | `data` | `ParamData` | | `pipes` | `PipeTransform[]` | | `extractValue` | `( req: TRequest, res: TResponse, next: Function, ) => any` | ## Diagram ```mermaid graph LR Request[HTTP Request] --> Extract[extractValue(req, res, next)] Extract --> RawValue[Raw parameter value] RawValue --> Pipes[PipeTransform[]] Pipes --> ResolvedValue[Resolved method argument] Metadata[index, type, data] --> Extract ResolvedValue --> Handler[Controller handler parameter] ``` ## Usage ```ts import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import type { PipeTransform } from '@nestjs/common/interfaces'; import type { ParamProperties } from '@nestjs/core/router/router-execution-context'; const parseUserIdPipe: PipeTransform = { transform(value: string) { const id = Number(value); if (Number.isNaN(id)) { throw new Error('User ID must be a number'); } return id; }, }; const userIdParameter: ParamProperties = { index: 0, type: RouteParamtypes.PARAM, data: 'id', pipes: [parseUserIdPipe], extractValue: (req) => { const request = req as { params: Record }; return request.params.id; }, }; // Represents the first argument passed to a controller handler: // getUser(id: number) { ... } ``` ## AI Coding Instructions - Keep `index` aligned with the controller handler’s parameter position; indexes are zero-based. - Use `type` and `data` consistently: for `RouteParamtypes.PARAM`, `data` typically contains the route parameter name such as `"id"`. - Ensure `extractValue` safely handles the expected request shape and returns the raw value before pipes are applied. - Add `PipeTransform` instances for validation or conversion rather than embedding transformation logic in controller handlers. - Treat `ParamProperties` as router execution metadata; preserve its field contract when extending parameter decorator or route argument resolution behavior. ## Relationships - IMPORTS → `CanActivate` - IMPORTS → `ForbiddenException` - IMPORTS → `HttpServer` - IMPORTS → `ParamData` - IMPORTS → `PipeTransform` - IMPORTS → `RequestMethod` - IMPORTS → `CUSTOM_ROUTE_ARGS_METADATA` - IMPORTS → `HEADERS_METADATA` - IMPORTS → `HTTP_CODE_METADATA` - IMPORTS → `REDIRECT_METADATA` - IMPORTS → `RENDER_METADATA` - IMPORTS → `ROUTE_ARGS_METADATA` - IMPORTS → `SSE_METADATA` - IMPORTS → `RouteParamMetadata` - IMPORTS → `RouteParamtypes` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `isEmpty` - IMPORTS → `isString` # UndefinedDependencyException **Kind:** Class **Source:** [`packages/core/errors/exceptions/undefined-dependency.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/undefined-dependency.exception.ts#L6) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # UnknownElementException **Kind:** Class **Source:** [`packages/core/errors/exceptions/unknown-element.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/unknown-element.exception.ts#L3) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # CircularDependencyException **Kind:** Class **Source:** [`packages/core/errors/exceptions/circular-dependency.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/circular-dependency.exception.ts#L3) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # EnhancerMetadataCacheEntry **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/enhancer-metadata-cache-entry.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/enhancer-metadata-cache-entry.interface.ts#L5) **Part of:** [Core](subsystem-packages-core) `EnhancerMetadataCacheEntry` describes a cached metadata record for an enhancer discovered by the NestJS inspector. It links an enhancer—such as a guard, interceptor, pipe, or filter—to its target node, owning module, class or method, and resolved instance wrapper. The inspector uses these entries to efficiently associate enhancer metadata with the serialized dependency graph. ## Properties | Property | Type | |---|---| | `targetNodeId` | `string` | | `moduleToken` | `string` | | `classRef` | `Type` | | `methodKey` | `string | undefined` | | `enhancerRef` | `unknown` | | `enhancerInstanceWrapper` | `InstanceWrapper` | | `subtype` | `EnhancerSubtype` | ## Diagram ```mermaid graph LR Target[Target Node
targetNodeId] --> Entry[EnhancerMetadataCacheEntry] Module[Module
moduleToken] --> Entry Class[Controller or Provider
classRef] --> Entry Method[Optional Method
methodKey] --> Entry Enhancer[Enhancer Metadata
enhancerRef] --> Entry Wrapper[InstanceWrapper
enhancerInstanceWrapper] --> Entry Subtype[EnhancerSubtype
Guard / Pipe / Filter / Interceptor] --> Entry ``` ## Usage ```ts import { Type } from '@nestjs/common'; import { InstanceWrapper } from '../../injector/instance-wrapper'; import { EnhancerSubtype } from '../enums/enhancer-subtype.enum'; import { EnhancerMetadataCacheEntry } from '../interfaces/enhancer-metadata-cache-entry.interface'; function cacheEnhancer( entry: EnhancerMetadataCacheEntry, cache: Map, ) { const entries = cache.get(entry.targetNodeId) ?? []; entries.push(entry); cache.set(entry.targetNodeId, entries); } const entry: EnhancerMetadataCacheEntry = { targetNodeId: 'controller:users', moduleToken: 'UsersModule', classRef: UsersController as Type, methodKey: 'findAll', enhancerRef: AuthGuard, enhancerInstanceWrapper: authGuardWrapper as InstanceWrapper, subtype: EnhancerSubtype.GUARD, }; cacheEnhancer(entry, enhancerMetadataCache); ``` ## AI Coding Instructions - Preserve the relationship between `targetNodeId`, `moduleToken`, and `enhancerInstanceWrapper`; these values identify where an enhancer belongs in the inspected graph. - Treat `methodKey` as optional: `undefined` indicates a class-level enhancer rather than a method-level enhancer. - Use `subtype` to distinguish enhancer categories when serializing or grouping metadata; do not infer the category solely from `enhancerRef`. - Keep `enhancerRef` typed as `unknown` unless the consuming code has safely narrowed its runtime shape. - When adding cache entries, avoid replacing existing entries for the same target node because multiple enhancers may apply to one controller or method. ## Relationships - IMPORTS → `Type` - IMPORTS → `EnhancerSubtype` # Entrypoint **Kind:** Type **Source:** [`packages/core/inspector/interfaces/entrypoint.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/entrypoint.interface.ts#L17) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { id?: string; type: string; methodName: string; className: string; classNodeId: string; metadata: { key: string } & T; } ``` # ExceptionsFilter **Kind:** Interface **Source:** [`packages/core/router/interfaces/exceptions-filter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/exceptions-filter.interface.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Relationships - IMPORTS → `Controller` # ExternalHandlerMetadata **Kind:** Interface **Source:** [`packages/core/helpers/interfaces/external-handler-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/interfaces/external-handler-metadata.interface.ts#L5) **Part of:** [Core](subsystem-packages-core) `ExternalHandlerMetadata` describes the runtime metadata required to invoke an external handler with dependency-injected parameters. It records the handler's expected argument count, reflected parameter types, and a resolver for retrieving parameter metadata within a specific module and dependency-injection context. ## Properties | Property | Type | |---|---| | `argsLength` | `number` | | `paramtypes` | `any[]` | | `getParamsMetadata` | `( moduleKey: string, contextId?: ContextId, inquirerId?: string, ) => ParamPropertiesWithMetatype[]` | ## Diagram ```mermaid graph LR Handler[External Handler] --> Metadata[ExternalHandlerMetadata] Metadata --> Args[argsLength: number] Metadata --> Types[paramtypes: any[]] Metadata --> Resolver[getParamsMetadata()] Resolver --> Module[moduleKey] Resolver --> Context[contextId / inquirerId] Resolver --> Params[ParamPropertiesWithMetatype[]] ``` ## Usage ```ts import type { ContextId } from '@nestjs/core'; import type { ExternalHandlerMetadata } from './external-handler-metadata.interface'; const handlerMetadata: ExternalHandlerMetadata = { argsLength: 2, paramtypes: [UserService, RequestContext], getParamsMetadata( moduleKey: string, contextId?: ContextId, inquirerId?: string, ) { // Resolve parameter metadata for the active module/context. return resolveHandlerParams(moduleKey, contextId, inquirerId); }, }; const params = handlerMetadata.getParamsMetadata( 'users-module', requestContextId, ); if (params.length !== handlerMetadata.argsLength) { throw new Error('Resolved handler parameters do not match the handler signature.'); } ``` ## AI Coding Instructions - Keep `argsLength` aligned with the number of parameters expected by the external handler. - Preserve reflected constructor/parameter types in `paramtypes`; do not assume all entries are concrete classes. - Call `getParamsMetadata` with the correct `moduleKey` so dependencies are resolved from the intended module scope. - Forward `contextId` and `inquirerId` when resolving request-scoped or transient providers. - Validate returned parameter metadata before invoking a handler, especially when metadata may be incomplete or dynamically resolved. # HandleSseResponseFn **Kind:** Type **Source:** [`packages/core/helpers/handler-metadata-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/handler-metadata-storage.ts#L19) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts < TResult extends Observable = any, TResponse extends HeaderStream = any, TRequest extends IncomingMessage = any, >( result: TResult, res: TResponse, req: TRequest, ) => any ``` # INQUIRER **Kind:** Constant **Source:** [`packages/core/injector/inquirer/inquirer-constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/inquirer/inquirer-constants.ts#L1) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'INQUIRER' ``` ## Value ```ts 'INQUIRER' ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `HelloRequestService` — `integration/scopes/src/inject-inquirer/hello-request/hello-request.service.ts`:5 - `RequestLogger` — `integration/scopes/src/inject-inquirer/hello-request/request-logger.service.ts`:4 - `TransientLogger` — `integration/scopes/src/inject-inquirer/hello-transient/transient-logger.service.ts`:4 # ModuleNode **Kind:** Type **Source:** [`packages/core/inspector/interfaces/node.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/node.interface.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { metadata: { type: 'module'; global: boolean; dynamic: boolean; internal: boolean; }; } ``` ## Relationships - IMPORTS → `InjectionToken` - IMPORTS → `Scope` - IMPORTS → `EnhancerSubtype` # ModuleOverride **Kind:** Interface **Source:** [`packages/core/interfaces/module-override.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/interfaces/module-override.interface.ts#L3) **Part of:** [Core](subsystem-packages-core) `ModuleOverride` defines a replacement mapping between an existing `ModuleDefinition` and a new implementation. It is used by the module resolution or dependency injection system to substitute one module definition with another during configuration or application setup. ## Properties | Property | Type | |---|---| | `moduleToReplace` | `ModuleDefinition` | | `newModule` | `ModuleDefinition` | ## Diagram ```mermaid graph LR A[Original ModuleDefinition] --> B[ModuleOverride] C[Replacement ModuleDefinition] --> B B --> D[Module Resolution / DI System] D --> E[Uses newModule instead of moduleToReplace] ``` ## Usage ```ts import type { ModuleOverride } from '@your-scope/core'; const moduleOverride: ModuleOverride = { moduleToReplace: { name: 'NotificationModule', providers: [EmailNotificationService], }, newModule: { name: 'NotificationModule', providers: [MockNotificationService], }, }; // Pass the override into the application's module configuration. createApplication({ moduleOverrides: [moduleOverride], }); ``` ## AI Coding Instructions - Set `moduleToReplace` to the exact `ModuleDefinition` targeted by the application configuration. - Ensure `newModule` is a valid `ModuleDefinition` with compatible exports, providers, and dependencies. - Use overrides for environment-specific implementations, such as mocks in tests or alternate infrastructure adapters. - Avoid mutating either module definition after creating the override; treat override configuration as immutable setup data. - Verify that the module resolution integration consumes overrides before modules are instantiated. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # ParamsMetadata **Kind:** Type **Source:** [`packages/core/helpers/interfaces/params-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/interfaces/params-metadata.interface.ts#L3) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Record ``` ## Relationships - IMPORTS → `ParamData` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 - `MessageMappingProperties` — `packages/websockets/gateway-metadata-explorer.ts`:15 # SerializedGraphJson **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/serialized-graph-json.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/serialized-graph-json.interface.ts#L8) **Part of:** [Core](subsystem-packages-core) `SerializedGraphJson` defines the JSON-ready representation of an inspected graph. It stores graph nodes, edges, entrypoints, supplemental data, execution status, and metadata in a normalized structure suitable for serialization, transport, and visualization. ## Properties | Property | Type | |---|---| | `nodes` | `Record` | | `edges` | `Record` | | `entrypoints` | `Record[]>` | | `extras` | `Extras` | | `status` | `SerializedGraphStatus` | | `metadata` | `SerializedGraphMetadata` | ## Diagram ```mermaid graph LR Graph[SerializedGraphJson] Graph --> Nodes["nodes: Record"] Graph --> Edges["edges: Record"] Graph --> Entrypoints["entrypoints: Record[]>"] Graph --> Extras["extras: Extras"] Graph --> Status["status: SerializedGraphStatus"] Graph --> Metadata["metadata: SerializedGraphMetadata"] Edges --> Nodes Entrypoints --> Nodes ``` ## Usage ```ts import type { SerializedGraphJson } from './interfaces/serialized-graph-json.interface'; const serializedGraph: SerializedGraphJson = { nodes: { start: { id: 'start', type: 'input', }, process: { id: 'process', type: 'transform', }, }, edges: { 'start-to-process': { id: 'start-to-process', source: 'start', target: 'process', }, }, entrypoints: { default: [ { nodeId: 'start', }, ], }, extras: {}, status: 'ready', metadata: { name: 'Example graph', }, }; // Serialize for storage, inspector transport, or UI rendering. const json = JSON.stringify(serializedGraph); ``` ## AI Coding Instructions - Keep `nodes` and `edges` keyed by stable, unique IDs; ensure edge source and target references match node IDs. - Preserve the normalized record-based structure rather than converting graph data into arrays unless a consuming API explicitly requires it. - Treat `entrypoints` as grouped entrypoint definitions; support multiple `Entrypoint` values per entrypoint key. - Populate `status` and `metadata` consistently so inspector consumers can determine graph state and display graph context. - Use JSON-serializable values in `extras` and metadata fields when this object will be persisted or sent across process boundaries. ## How it works `SerializedGraphJson` is the exported TypeScript interface for the object returned by `SerializedGraph.toJSON()`. It describes a serialized graph as four required collections plus optional status and diagnostic metadata. [serialized-graph-json.interface.ts:8-15] [serialized-graph.ts:125-140] - `nodes` is a string-keyed record of `Node` values. A node has `id` and `label`, and represents either a module or a class-related item with its corresponding metadata. [serialized-graph-json.interface.ts:9] [node.interface.ts:4-47] - `edges` is a string-keyed record of `Edge` values. Each edge has an `id`, `source`, `target`, and metadata describing either a module-to-module or class-to-class connection. [serialized-graph-json.interface.ts:10] [edge.interface.ts:8-31] - `entrypoints` maps a string parent ID to an array of entrypoints. Each entrypoint records its type, method and class names, class-node ID, and metadata containing a `key`; `id` is optional. [serialized-graph-json.interface.ts:11] [entrypoint.interface.ts:17-24] - `extras` contains arrays for orphaned enhancers (`subtype` and `ref`) and attached enhancers (`nodeId`). [serialized-graph-json.interface.ts:12] [extras.interface.ts:6-21] - `status`, when present, is either `'partial'` or `'complete'`. [serialized-graph-json.interface.ts:13] [serialized-graph.ts:22] - `metadata`, when present, contains a `cause` whose type is `'unknown-dependencies'` or `'unknown'`, with optional dependency context, module ID, node ID, and error fields. [serialized-graph-json.interface.ts:14] [serialized-graph-metadata.interface.ts:3-11] `SerializedGraph.toJSON()` converts its internal node, edge, and entrypoint `Map` instances into the corresponding records with `Object.fromEntries`, and assigns its `extras` object directly to the result. [serialized-graph.ts:26-35] [serialized-graph.ts:125-131] It adds `status` when `_status` is truthy and `metadata` when `_metadata` is truthy; `_status` starts as `'complete'`, while metadata starts unset. [serialized-graph.ts:34-35] [serialized-graph.ts:133-139] The interface itself contains no runtime validation, error handling, or side effects; it only declares the object shape. [serialized-graph-json.interface.ts:8-15] # SerializedGraphMetadata **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L3) **Part of:** [Core](subsystem-packages-core) `SerializedGraphMetadata` describes diagnostic metadata attached to a serialized graph when graph construction or dependency resolution encounters a problem. Its `cause` field identifies the failure category and can include dependency context, module/node identifiers, and the original error for inspection tooling. ## Properties | Property | Type | |---|---| | `cause` | `{ type: 'unknown-dependencies' | 'unknown'; context?: InjectorDependencyContext; moduleId?: string; nodeId?: string; error?: any; }` | ## Diagram ```mermaid graph LR Graph[Serialized Graph] --> Metadata[SerializedGraphMetadata] Metadata --> Cause[cause] Cause --> Type["type: unknown-dependencies | unknown"] Cause --> Context["context?: InjectorDependencyContext"] Cause --> Module["moduleId?: string"] Cause --> Node["nodeId?: string"] Cause --> Error["error?: any"] ``` ## Usage ```ts import type { SerializedGraphMetadata } from '@nestjs/core/inspector/interfaces/serialized-graph-metadata.interface'; const metadata: SerializedGraphMetadata = { cause: { type: 'unknown-dependencies', moduleId: 'AppModule', nodeId: 'UsersService', error: new Error('Unable to resolve dependency DatabaseService'), }, }; // Attach metadata to serialized graph output for inspector/debugging consumers. console.error(metadata.cause.type, metadata.cause.error); ``` ## AI Coding Instructions - Set `cause.type` to `'unknown-dependencies'` when dependency injection resolution fails; use `'unknown'` for uncategorized graph failures. - Include `moduleId` and `nodeId` whenever they are available to make inspector output traceable. - Preserve the original thrown value in `error` rather than replacing it with a string. - Provide `context` only when dependency resolution context is available from the injector. - Treat all fields other than `cause.type` as optional when consuming serialized graph metadata. ## How it works `SerializedGraphMetadata` is a TypeScript interface for the optional `metadata` field of a serialized graph JSON object. That graph field is optional, while `cause` is required whenever metadata is present. [serialized-graph-json.interface.ts:8-14](packages/core/inspector/interfaces/serialized-graph-json.interface.ts#L8-L14) [serialized-graph-metadata.interface.ts:3-10](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L3-L10) Its required `cause.type` is restricted to: - `'unknown-dependencies'` - `'unknown'` [serialized-graph-metadata.interface.ts:4-5](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L4-L5) The `cause` object may also contain: - `context`: an `InjectorDependencyContext`, whose optional fields identify a property key, injection name/token, dependency index, or dependency array. [serialized-graph-metadata.interface.ts:6](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L6) [injector.ts:67-85](packages/core/injector/injector.ts#L67-L85) - `moduleId`: a string. [serialized-graph-metadata.interface.ts:7](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L7) - `nodeId`: a string. [serialized-graph-metadata.interface.ts:8](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L8) - `error`: an `any`-typed value. [serialized-graph-metadata.interface.ts:9](packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts#L9) During dependency-instance creation, if `createInstances` throws, `InstanceLoader` first inspects the modules, registers a partial graph with the caught error, then rethrows that error. [instance-loader.ts:25-38](packages/core/injector/instance-loader.ts#L25-L38) `GraphInspector.registerPartial` sets the graph status to `'partial'`. [graph-inspector.ts:38-40](packages/core/inspector/graph-inspector.ts#L38-L40) For an `UnknownDependenciesException`, it writes metadata with `type: 'unknown-dependencies'`, copies the exception’s dependency context, and conditionally records the module and node IDs. [graph-inspector.ts:41-49](packages/core/inspector/graph-inspector.ts#L41-L49) The exception exposes the context as required constructor input, while its module reference and node metadata are optional. [unknown-dependencies.exception.ts:6-17](packages/core/errors/exceptions/unknown-dependencies.exception.ts#L6-L17) For any other caught value, it writes `type: 'unknown'` and stores that value in `cause.error`; it does not populate `context`, `moduleId`, or `nodeId` in this branch. [graph-inspector.ts:50-57](packages/core/inspector/graph-inspector.ts#L50-L57) `SerializedGraph` stores this interface value through its `metadata` setter and includes it as `metadata` in `toJSON()` only when metadata has been assigned. [serialized-graph.ts:35](packages/core/inspector/serialized-graph.ts#L35) [serialized-graph.ts:56-58](packages/core/inspector/serialized-graph.ts#L56-L58) [serialized-graph.ts:125-139](packages/core/inspector/serialized-graph.ts#L125-L139) The partial graph is then registered in `PartialGraphHost`, whose `toJSON()` delegates to the stored graph’s `toJSON()`. [graph-inspector.ts:58](packages/core/inspector/graph-inspector.ts#L58) [partial-graph.host.ts:3-16](packages/core/inspector/partial-graph.host.ts#L3-L16) # UnknownModuleException **Kind:** Class **Source:** [`packages/core/errors/exceptions/unknown-module.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/unknown-module.exception.ts#L3) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # UuidFactoryMode **Kind:** Enum **Source:** [`packages/core/inspector/uuid-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/uuid-factory.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Values - `Random` - `Deterministic` ## Relationships - IMPORTS → `randomStringGenerator` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TestingModuleOptions` — `packages/testing/testing-module.builder.ts`:29 # Edge **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/edge.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/edge.interface.ts#L26) **Part of:** [Core](subsystem-packages-core) `Edge` represents a directed relationship between two entities in the inspector graph. It identifies the connection, its source and target node IDs, and metadata describing whether the relationship is module-to-module or class-to-class. ## Properties | Property | Type | |---|---| | `id` | `string` | | `source` | `string` | | `target` | `string` | | `metadata` | `ModuleToModuleEdgeMetadata | ClassToClassEdgeMetadata` | ## Diagram ```mermaid graph LR Source["Source entity
(source)"] --> Edge["Edge
id + metadata"] --> Target["Target entity
(target)"] Edge --- Metadata["ModuleToModuleEdgeMetadata
or ClassToClassEdgeMetadata"] ``` ## Usage ```ts import type { Edge } from '@core/inspector/interfaces/edge.interface'; const moduleDependency: Edge = { id: 'app-module->users-module', source: 'app-module', target: 'users-module', metadata: { type: 'module-to-module', // Additional ModuleToModuleEdgeMetadata fields }, }; // Use the edge when constructing an inspector dependency graph. graph.edges.push(moduleDependency); ``` ## AI Coding Instructions - Use stable, unique `id` values so graph edges can be reliably indexed, updated, and rendered. - Ensure `source` and `target` reference valid node IDs already present in the inspector graph. - Provide metadata that matches the relationship type: `ModuleToModuleEdgeMetadata` for module dependencies and `ClassToClassEdgeMetadata` for class relationships. - Treat edges as directed: `source -> target` may not represent the same relationship as `target -> source`. - Keep edge metadata aligned with the graph consumer’s expected discriminators and rendering logic. ## Relationships - IMPORTS → `InjectionToken` # FilterByInclude **Kind:** Interface **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L16) **Part of:** [Core](subsystem-packages-core) `FilterByInclude` defines an inclusion filter used by the discovery service. Its `include` field contains predicate functions that determine which discovered items should be retained during discovery processing. ## Properties | Property | Type | |---|---| | `include` | `Function[]` | ## Diagram ```mermaid graph LR A[Discovery Service] --> B[FilterByInclude] B --> C[include: Function[]] C --> D[Inclusion Predicate 1] C --> E[Inclusion Predicate 2] D --> F[Discovered Items] E --> F F --> G[Included Results] ``` ## Usage ```ts import type { FilterByInclude } from './discovery-service'; const filter: FilterByInclude = { include: [ (item) => item.enabled === true, (item) => item.name.startsWith('api-'), ], }; // Pass the filter to the discovery workflow. // Only items matching the configured inclusion predicates are retained. discoveryService.discover({ filter, }); ``` ## AI Coding Instructions - Provide inclusion logic as functions in the `include` array; keep each predicate focused on a single filtering concern. - Ensure predicate functions safely handle missing or optional properties on discovered items. - Use `FilterByInclude` when configuring discovery behavior that should explicitly retain matching items. - Avoid placing side effects in include predicates; they should only evaluate whether an item belongs in the results. ## Relationships - IMPORTS → `CustomDecorator` - IMPORTS → `flatten` - IMPORTS → `Injectable` - IMPORTS → `SetMetadata` # FilterByMetadataKey **Kind:** Interface **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L26) **Part of:** [Core](subsystem-packages-core) `FilterByMetadataKey` defines a discovery filter that targets entities containing a specific metadata key. It is used by the discovery service to narrow query results based on metadata structure rather than a metadata value. ## Properties | Property | Type | |---|---| | `metadataKey` | `string` | ## Diagram ```mermaid graph LR Client[Discovery Client] --> Filter[FilterByMetadataKey] Filter --> Key[metadataKey: string] Key --> DiscoveryService[Discovery Service] DiscoveryService --> Results[Matching Entities] ``` ## Usage ```ts import type { FilterByMetadataKey } from './discovery-service'; const filter: FilterByMetadataKey = { metadataKey: 'environment', }; // Pass the filter to the discovery service API that accepts metadata filters. const results = await discoveryService.discover({ filters: [filter], }); ``` ## AI Coding Instructions - Provide a non-empty `metadataKey` that matches the metadata field name stored on discoverable entities. - Use this interface when filtering by key presence; use a different filter type when matching specific metadata values. - Keep filter objects serializable because they may be passed through discovery request boundaries. - Ensure discovery service consumers handle empty result sets when no entities contain the requested key. # HttpEntrypointMetadata **Kind:** Type **Source:** [`packages/core/inspector/interfaces/entrypoint.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/entrypoint.interface.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { path: string; requestMethod: keyof typeof RequestMethod; methodVersion?: VersionValue; controllerVersion?: VersionValue; } ``` ## Relationships - IMPORTS → `RequestMethod` - IMPORTS → `VersionValue` # InstanceLink **Kind:** Interface **Source:** [`packages/core/injector/instance-links-host.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-links-host.ts#L10) **Part of:** [Core](subsystem-packages-core) `InstanceLink` describes a resolved dependency entry managed by the injector. It connects an injection `token` to its `InstanceWrapper`, the module-level wrapper `collection` where it was found, and the owning `moduleId` for module-aware resolution. ## Properties | Property | Type | |---|---| | `token` | `InjectionToken` | | `wrapperRef` | `InstanceWrapper` | | `collection` | `Map` | | `moduleId` | `string` | ## Diagram ```mermaid graph LR Token[InjectionToken] --> Link[InstanceLink] Link --> Wrapper[InstanceWrapper] Link --> Collection[Map] Link --> ModuleId[moduleId: string] Collection --> Wrapper ``` ## Usage ```ts import { InstanceLink } from './instance-links-host'; import { InstanceWrapper } from './instance-wrapper'; function inspectLink(link: InstanceLink) { console.log(`Resolved token from module: ${link.moduleId}`); console.log('Token:', link.token); console.log('Wrapper:', link.wrapperRef); // The collection contains all provider wrappers for the owning module. const registeredWrapper = link.collection.get(link.token); return registeredWrapper ?? link.wrapperRef; } // Typically created internally by the injector during dependency resolution. const link: InstanceLink = { token: MyService, wrapperRef: myServiceWrapper, collection: moduleProviders, moduleId: 'AppModule', }; ``` ## AI Coding Instructions - Treat `wrapperRef` as the authoritative wrapper selected during dependency resolution; use `collection` when module-level lookup context is needed. - Preserve the original `token`, including string, symbol, class, and custom injection-token values. - Keep `moduleId` associated with the link so cross-module resolution and diagnostics retain module context. - Do not assume `collection.get(token)` always returns the same wrapper as `wrapperRef`; aliases and lookup rules may affect resolution. ## Relationships - IMPORTS → `InjectionToken` - IMPORTS → `isFunction` # InstancePerContext **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L42) **Part of:** [Core](subsystem-packages-core) `InstancePerContext` tracks the lifecycle state of a provider instance within a specific dependency-injection context. It stores the resolved instance alongside flags and promises used to coordinate asynchronous construction, prevent duplicate instantiation, and determine whether constructor logic has already run. ## Properties | Property | Type | |---|---| | `instance` | `T` | | `isResolved` | `boolean` | | `isPending` | `boolean` | | `donePromise` | `Promise` | | `isConstructorCalled` | `boolean` | ## Diagram ```mermaid graph LR Context[Injection Context] --> Record[InstancePerContext] Record --> Instance[instance: T] Record --> Resolved[isResolved] Record --> Pending[isPending] Record --> Promise[donePromise] Record --> Constructed[isConstructorCalled] Pending -->|await completion| Promise Promise -->|resolution complete| Resolved Constructed -->|prevents duplicate constructor calls| Instance ``` ## Usage ```ts interface InstancePerContext { instance: T; isResolved: boolean; isPending: boolean; donePromise: Promise; isConstructorCalled: boolean; } class RequestService { constructor(public readonly requestId: string) {} } const contextInstance: InstancePerContext = { instance: new RequestService('request-123'), isResolved: true, isPending: false, donePromise: Promise.resolve(), isConstructorCalled: true, }; // A resolver can reuse the instance when it has already been created. if (contextInstance.isResolved) { console.log(contextInstance.instance.requestId); } ``` ## AI Coding Instructions - Treat `instance` as scoped to a single injection context; do not reuse it across unrelated contexts. - Set `isPending` before starting asynchronous resolution, and expose the completion work through `donePromise`. - Check `isResolved` and await `donePromise` when necessary to avoid creating duplicate instances during concurrent resolution. - Use `isConstructorCalled` to prevent constructor or initialization logic from running more than once for the same context record. - Keep lifecycle flags synchronized with promise completion so consumers never observe a resolved state before the instance is ready. # LazyModuleLoaderLoadOptions **Kind:** Interface **Source:** [`packages/core/injector/lazy-module-loader/lazy-module-loader-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/lazy-module-loader/lazy-module-loader-options.interface.ts#L1) **Part of:** [Core](subsystem-packages-core) `LazyModuleLoaderLoadOptions` configures how a lazy-loaded module is loaded by the NestJS dependency injection system. Its `logger` flag controls whether module loading activity should be logged, allowing callers to reduce log noise when loading modules dynamically. ## Properties | Property | Type | |---|---| | `logger` | `boolean` | ## Diagram ```mermaid graph LR A[Application Code] --> B[LazyModuleLoader] B --> C[LazyModuleLoaderLoadOptions] C --> D{logger enabled?} D -->|true| E[Log module loading activity] D -->|false| F[Load module silently] E --> G[Lazy-loaded Module] F --> G ``` ## Usage ```ts import { LazyModuleLoader } from '@nestjs/core'; import type { LazyModuleLoaderLoadOptions } from '@nestjs/core'; @Injectable() export class ReportsService { constructor(private readonly lazyModuleLoader: LazyModuleLoader) {} async loadReportsModule() { const options: LazyModuleLoaderLoadOptions = { logger: true, }; const moduleRef = await this.lazyModuleLoader.load( () => import('./reports/reports.module').then((module) => module.ReportsModule), options, ); return moduleRef; } } ``` ## AI Coding Instructions - Pass `logger: true` when lazy module loading should appear in application logs for debugging or operational visibility. - Use `logger: false` for expected or frequent lazy-loading operations where log output would be noisy. - Provide this options object as the second argument to `LazyModuleLoader.load()`. - Keep lazy module imports inside the loader callback so the module is not eagerly evaluated during application startup. # ParamProperties **Kind:** Interface **Source:** [`packages/core/helpers/context-utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-utils.ts#L15) **Part of:** [Core](subsystem-packages-core) `ParamProperties` describes the metadata required to resolve a handler or controller parameter at runtime. It identifies the parameter position, its declared type, extraction configuration, optional transformation pipes, and the extractor responsible for obtaining the raw value. ## Properties | Property | Type | |---|---| | `index` | `number` | | `type` | `T | string` | | `data` | `ParamData` | | `pipes` | `PipeTransform[]` | | `extractValue` | `IExtractor` | ## Diagram ```mermaid graph LR A[Incoming request/context] --> B[IExtractor] B --> C[Extracted value] C --> D[PipeTransform[]] D --> E[Resolved parameter value] E --> F[Handler argument at index] G[ParamProperties] --> H[index: number] G --> I[type: T | string] G --> J[data: ParamData] G --> K[pipes: PipeTransform[]] G --> L[extractValue: IExtractor] ``` ## Usage ```ts import type { ParamProperties } from './context-utils'; const userIdParam: ParamProperties = { index: 0, type: String, data: { name: 'id', source: 'params', }, pipes: [parseIntPipe], extractValue: { extract(context, data) { return context.params[data.name]; }, }, }; // Runtime parameter resolution flow: const rawValue = userIdParam.extractValue.extract(context, userIdParam.data); const value = userIdParam.pipes.reduce( (result, pipe) => pipe.transform(result), rawValue, ); handlerArguments[userIdParam.index] = value; ``` ## AI Coding Instructions - Use `index` as the authoritative position when assigning the resolved value into a handler argument array. - Keep `extractValue` focused on reading raw values from the current execution context; apply validation and conversion through `pipes`. - Preserve pipe order, since each `PipeTransform` should receive the output of the previous pipe. - Use `data` to pass extractor-specific configuration such as parameter names, headers, query keys, or request-body paths. - Support both constructor types and string-based types in `type`, especially when runtime type metadata may be unavailable. ## Relationships - IMPORTS → `ParamData` - IMPORTS → `PARAMTYPES_METADATA` - IMPORTS → `RESPONSE_PASSTHROUGH_METADATA` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `PipeTransform` - IMPORTS → `Type` - IMPORTS → `isFunction` # PropertyDependency **Kind:** Interface **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L56) **Part of:** [Core](subsystem-packages-core) The property-based dependency `PropertyDependency` describes a dependency that should be injected into a property of a target instance. It stores the property key, the dependency metadata used to resolve the value, whether the dependency is optional, and the resolved instance value. ## Properties | Property | Type | |---|---| | `key` | `symbol | string` | | `name` | `InjectorDependency` | | `isOptional` | `boolean` | | `instance` | `any` | ## Diagram ```mermaid graph LR A[Target Instance] --> B[PropertyDependency] B --> C[key: string | symbol] B --> D[name: InjectorDependency] D --> E[Injector Resolution] E --> F[instance: resolved value] B --> G[isOptional] G --> H[Allow missing dependency] ``` ## Usage ```ts import type { PropertyDependency } from './injector'; const loggerDependency: PropertyDependency = { key: 'logger', name: { token: LoggerService, }, isOptional: false, instance: undefined, }; // During injection, the injector resolves `name` and assigns the result. loggerDependency.instance = injector.get(loggerDependency.name.token); targetInstance[loggerDependency.key] = loggerDependency.instance; ``` ## AI Coding Instructions - Use `key` as the exact property name or symbol that will receive the injected value. - Resolve dependencies through the injector using `name`; do not construct dependency instances directly. - Respect `isOptional` when resolution fails—optional dependencies should not throw injection errors. - Treat `instance` as the resolved runtime value and update it only after successful dependency resolution. - Preserve symbol keys when copying or applying property dependency metadata. # RouteDefinition **Kind:** Interface **Source:** [`packages/core/router/paths-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/paths-explorer.ts#L17) **Part of:** [Core](subsystem-packages-core) `RouteDefinition` describes a discovered HTTP route within the router exploration process. It combines the route path, HTTP method, controller callback, method name, and optional API version so the framework can register and dispatch requests consistently. ## Properties | Property | Type | |---|---| | `path` | `string[]` | | `requestMethod` | `RequestMethod` | | `targetCallback` | `RouterProxyCallback` | | `methodName` | `string` | | `version` | `VersionValue` | ## Diagram ```mermaid graph LR Controller[Controller Method] --> Definition[RouteDefinition] Definition --> Path[path: string[]] Definition --> Method[requestMethod: RequestMethod] Definition --> Callback[targetCallback: RouterProxyCallback] Definition --> Name[methodName: string] Definition --> Version[version: VersionValue] Definition --> Router[Router Registration] ``` ## Usage ```ts import { RequestMethod } from '@nestjs/common'; import type { RouteDefinition } from './paths-explorer'; const usersController = { findAll() { return [{ id: 1, name: 'Ada' }]; }, }; const route: RouteDefinition = { path: ['users'], requestMethod: RequestMethod.GET, targetCallback: usersController.findAll.bind(usersController), methodName: 'findAll', version: '1', }; // Used by the router explorer to register GET /v1/users. ``` ## AI Coding Instructions - Preserve `path` as a string array; route exploration may produce multiple normalized paths for one handler. - Use `RequestMethod` enum values instead of raw HTTP method strings. - Bind `targetCallback` to its controller instance when constructing definitions manually, so `this` context is retained. - Keep `methodName` aligned with the original controller method for metadata lookup, logging, and diagnostics. - Pass the correct `version` value when integrating with versioned routing; avoid treating versioned and unversioned routes as interchangeable. ## How it works `RouteDefinition` is an exported TypeScript interface describing a discovered controller-method route. It contains: - `path`: one or more route-path strings. [`packages/core/router/paths-explorer.ts:17-23`](packages/core/router/paths-explorer.ts#L17-L23) - `requestMethod`: the `RequestMethod` metadata value for the controller method. [`packages/core/router/paths-explorer.ts:19`](packages/core/router/paths-explorer.ts#L19) - `targetCallback`: the instance method callback, typed to accept `(req, res, next)` and return `void` or `Promise`. [`packages/core/router/paths-explorer.ts:20`](packages/core/router/paths-explorer.ts#L20) [`packages/core/router/router-proxy.ts:4-8`](packages/core/router/router-proxy.ts#L4-L8) - `methodName`: the discovered method’s name. [`packages/core/router/paths-explorer.ts:21`](packages/core/router/paths-explorer.ts#L21) - Optional `version`: method-level version metadata. [`packages/core/router/paths-explorer.ts:22`](packages/core/router/paths-explorer.ts#L22) `PathsExplorer` creates a `RouteDefinition` while scanning method names on a controller prototype. A definition is created only when `PATH_METADATA` exists on the prototype method; methods without that metadata return `null` and are excluded from `scanForPaths` results. [`packages/core/router/paths-explorer.ts:36-50`](packages/core/router/paths-explorer.ts#L36-L50) [`packages/core/router/paths-explorer.ts:58-63`](packages/core/router/paths-explorer.ts#L58-L63) During construction, a string path is converted to a one-item array and given a leading slash. For a non-string path value, the code maps its entries and adds a leading slash to each. The request method and optional version come from reflection metadata on the prototype callback, while `targetCallback` comes from the controller instance. [`packages/core/router/paths-explorer.ts:58-81`](packages/core/router/paths-explorer.ts#L58-L81) In HTTP route registration, the route’s `version` is assigned to `routePathMetadata.methodVersion`; its request method selects the adapter router method; and every route path is expanded through `RoutePathFactory` before the handler is registered with the router. [`packages/core/router/router-explorer.ts:140-151`](packages/core/router/router-explorer.ts#L140-L151) [`packages/core/router/router-explorer.ts:163-173`](packages/core/router/router-explorer.ts#L163-L173) [`packages/core/router/router-explorer.ts:198-247`](packages/core/router/router-explorer.ts#L198-L247) ## Relationships - IMPORTS → `METHOD_METADATA` - IMPORTS → `PATH_METADATA` - IMPORTS → `VERSION_METADATA` - IMPORTS → `RequestMethod` - IMPORTS → `Controller` - IMPORTS → `VersionValue` - IMPORTS → `addLeadingSlash` - IMPORTS → `isString` - IMPORTS → `isUndefined` # RouteDefinition **Kind:** Interface **Source:** [`packages/core/router/router-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-explorer.ts#L49) **Part of:** [Core](subsystem-packages-core) `RouteDefinition` describes a resolved HTTP route that the router explorer can register with the underlying HTTP adapter. It combines one or more URL paths, the HTTP request method, the controller callback to execute, the original method name, and optional API version metadata. ## Properties | Property | Type | |---|---| | `path` | `string[]` | | `requestMethod` | `RequestMethod` | | `targetCallback` | `RouterProxyCallback` | | `methodName` | `string` | | `version` | `VersionValue` | ## Diagram ```mermaid graph LR A[Controller Method] --> B[RouteDefinition] B --> C[path: string[]] B --> D[requestMethod: RequestMethod] B --> E[targetCallback: RouterProxyCallback] B --> F[methodName: string] B --> G[version: VersionValue] B --> H[HTTP Router Registration] H --> I[Incoming Request] I --> E ``` ## Usage ```ts import { RequestMethod, VersioningType } from '@nestjs/common'; import type { RouteDefinition } from '@nestjs/core/router/router-explorer'; const routeDefinition: RouteDefinition = { path: ['/users', '/api/users'], requestMethod: RequestMethod.GET, methodName: 'findAll', version: '1', targetCallback: async (req, res, next) => { try { const users = await userService.findAll(); res.status(200).json(users); } catch (error) { next(error); } }, }; // The router explorer uses this metadata to register GET handlers // for each configured path and version. ``` ## AI Coding Instructions - Provide every normalized route path in `path`; the router explorer may register the same callback for multiple paths. - Use `RequestMethod` enum values rather than string literals such as `"GET"` or `"POST"`. - Ensure `targetCallback` is a router-compatible proxy callback that delegates errors to the framework exception pipeline. - Keep `methodName` aligned with the original controller method name for metadata lookup, logging, and debugging. - Preserve `version` metadata when creating or transforming route definitions so URI, header, or media-type versioning continues to work correctly. ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `PATH_METADATA` - IMPORTS → `RequestMethod` - IMPORTS → `VersioningType` - IMPORTS → `InternalServerErrorException` - IMPORTS → `Controller` - IMPORTS → `Type` - IMPORTS → `VersionValue` - IMPORTS → `Logger` - IMPORTS → `addLeadingSlash` - IMPORTS → `isUndefined` # APP_GUARD **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L15) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'APP_GUARD' ``` ## Value ```ts 'APP_GUARD' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `DurableModule` — `integration/scopes/src/durable/durable.module.ts`:8 - `AuthModule` — `sample/19-auth-jwt/src/auth/auth.module.ts`:10 # ExternalContextOptions **Kind:** Interface **Source:** [`packages/core/helpers/external-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/external-context-creator.ts#L32) **Part of:** [Core](subsystem-packages-core) `ExternalContextOptions` controls which framework-level enhancements are applied when creating an external execution context. It allows callers to enable or disable guards, interceptors, and exception filters independently for handlers invoked outside the standard request pipeline. ## Properties | Property | Type | |---|---| | `guards` | `boolean` | | `interceptors` | `boolean` | | `filters` | `boolean` | ## Diagram ```mermaid graph LR A[External Context Creation] --> B[ExternalContextOptions] B --> C{guards enabled?} B --> D{interceptors enabled?} B --> E{filters enabled?} C --> F[Apply Guards] D --> G[Apply Interceptors] E --> H[Apply Exception Filters] ``` ## Usage ```ts import { ExternalContextOptions } from './helpers/external-context-creator'; const options: ExternalContextOptions = { guards: true, interceptors: true, filters: false, }; // Pass options when creating an external handler context. // Guards and interceptors run, while exception filters are skipped. const handler = externalContextCreator.create( instance, method, methodName, options, ); ``` ## AI Coding Instructions - Provide all three boolean fields when constructing `ExternalContextOptions`; do not rely on implicit defaults. - Enable `guards` when external handlers must enforce authorization or access-control rules. - Enable `interceptors` when handlers require cross-cutting behavior such as logging, transformation, caching, or timing. - Enable `filters` when exceptions should be processed through configured exception filters instead of propagating directly. - Keep option values aligned with the execution environment so external contexts behave consistently with the intended application pipeline. ## How it works `ExternalContextOptions` is an exported TypeScript interface used as the `options` parameter of `ExternalContextCreator.create()` to select whether the generated external handler runs guards, creates/runs interceptors, and wraps execution in external exception-filter handling. Its three optional boolean fields are `guards`, `interceptors`, and `filters`. [packages/core/helpers/external-context-creator.ts:32-36](packages/core/helpers/external-context-creator.ts#L32-L36) [packages/core/helpers/external-context-creator.ts:91-108](packages/core/helpers/external-context-creator.ts#L91-L108) - When `options` is omitted, `create()` defaults all three fields to `true`. [packages/core/helpers/external-context-creator.ts:102-106](packages/core/helpers/external-context-creator.ts#L102-L106) - `guards` controls creation of the guard activation function. A truthy value creates it; a falsy or omitted field sets it to `null`, so the target does not invoke guard activation. [packages/core/helpers/external-context-creator.ts:150-152](packages/core/helpers/external-context-creator.ts#L150-L152) [packages/core/helpers/external-context-creator.ts:164-167](packages/core/helpers/external-context-creator.ts#L164-L167) - When enabled and guards exist, failed guard activation throws `ForbiddenException` with `FORBIDDEN_MESSAGE`. [packages/core/helpers/external-context-creator.ts:338-357](packages/core/helpers/external-context-creator.ts#L338-L357) - `interceptors` controls whether interceptor instances are created. A truthy value creates them; otherwise the handler passes an empty interceptor array to `interceptorsConsumer.intercept()`. [packages/core/helpers/external-context-creator.ts:135-143](packages/core/helpers/external-context-creator.ts#L135-L143) [packages/core/helpers/external-context-creator.ts:168-175](packages/core/helpers/external-context-creator.ts#L168-L175) - `filters` controls the returned function. A truthy value returns an `ExternalErrorProxy` wrapper; otherwise `create()` returns the unwrapped target. [packages/core/helpers/external-context-creator.ts:178-184](packages/core/helpers/external-context-creator.ts#L178-L184) - The proxy catches errors from the target, creates an `ExecutionContextHost` from the call arguments, sets its context type, and passes the error and host to the exception handler. [packages/core/helpers/external-proxy.ts:11-18](packages/core/helpers/external-proxy.ts#L11-L18) The options do not control pipe creation or parameter-pipe application: `create()` constructs pipes before testing these flags, and its handler applies parameter pipes when parameter metadata exists. [packages/core/helpers/external-context-creator.ts:114-120](packages/core/helpers/external-context-creator.ts#L114-L120) [packages/core/helpers/external-context-creator.ts:153-162](packages/core/helpers/external-context-creator.ts#L153-L162) # FORBIDDEN_MESSAGE **Kind:** Constant **Source:** [`packages/core/guards/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/guards/constants.ts#L1) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'Forbidden resource' ``` ## Value ```ts 'Forbidden resource' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `RpcHandlerMetadata` — `packages/microservices/context/rpc-context-creator.ts`:35 - `WsHandlerMetadata` — `packages/websockets/context/ws-context-creator.ts`:34 # HandlerResponseBasicFn **Kind:** Type **Source:** [`packages/core/helpers/handler-metadata-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/handler-metadata-storage.ts#L13) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts ( result: TResult, res: TResponse, req?: any, ) => any ``` # IEntryNestModule **Kind:** Type **Source:** [`packages/core/nest-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts#L39) **Part of:** [Core](subsystem-packages-core) Represents the entry (root) module type accepted by the NestFactory methods. `IEntryNestModule` represents the root NestJS module passed to `NestFactory` when creating an application or microservice. It provides the module metadata Nest needs to initialize dependency injection, controllers, providers, imports, and application lifecycle behavior. ## Definition ```ts | Type | DynamicModule | ForwardReference | Promise ``` ## Diagram ```mermaid graph LR Root[IEntryNestModule
Root module type] --> Factory[NestFactory] Factory --> App[Nest application instance] Root --> Imports[Imported modules] Root --> Providers[Providers] Root --> Controllers[Controllers] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { NestFactory, IEntryNestModule } from '@nestjs/core'; @Module({ controllers: [], providers: [], }) class AppModule {} async function bootstrap() { const entryModule: IEntryNestModule = AppModule; const app = await NestFactory.create(entryModule); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Pass a NestJS module class decorated with `@Module()` as the `IEntryNestModule` value; do not pass a module instance. - Use this type for APIs that accept the application's root module and delegate startup to `NestFactory`. - Keep root-module responsibilities focused on application composition: import feature modules and register global providers where appropriate. - Ensure controllers and providers are declared in the root module or reachable through its imported module graph. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `HttpServer` - IMPORTS → `INestApplication` - IMPORTS → `INestApplicationContext` - IMPORTS → `INestMicroservice` - IMPORTS → `Type` - IMPORTS → `NestMicroserviceOptions` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `NestApplicationOptions` - IMPORTS → `ConsoleLogger` - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `isFunction` - IMPORTS → `isNil` - IMPORTS → `-nestjs-microservices` - IMPORTS → `-nestjs-platform-express` # inquirerProvider **Kind:** Constant **Source:** [`packages/core/injector/inquirer/inquirer-providers.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/inquirer/inquirer-providers.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Provider ``` ## Value ```ts { provide: INQUIRER, scope: Scope.TRANSIENT, useFactory: noop, } ``` ## Relationships - IMPORTS → `Provider` - IMPORTS → `Scope` # InvalidClassException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-class.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-class.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # InvalidMiddlewareConfigurationException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-middleware-configuration.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-middleware-configuration.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # InvalidMiddlewareException **Kind:** Class **Source:** [`packages/core/errors/exceptions/invalid-middleware.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/invalid-middleware.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # MiddlewareEntrypointMetadata **Kind:** Type **Source:** [`packages/core/inspector/interfaces/entrypoint.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/entrypoint.interface.ts#L11) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { path: string; requestMethod: keyof typeof RequestMethod; version?: VersionValue; } ``` # ModuleFactory **Kind:** Interface **Source:** [`packages/core/injector/compiler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/compiler.ts#L8) **Part of:** [Core](subsystem-packages-core) `ModuleFactory` describes the compiled representation of a module used by the injector/compiler pipeline. It links a module class (`type`) to its unique registration token and any runtime-provided `dynamicMetadata` required to construct or configure a dynamic module. ## Properties | Property | Type | |---|---| | `type` | `Type` | | `token` | `string` | | `dynamicMetadata` | `Partial` | ## Diagram ```mermaid graph LR A[Module Class
Type<any>] --> B[ModuleFactory] C[Dynamic Module Metadata
Partial<DynamicModule>] --> B B --> D[token: string] B --> E[Injector / Compiler] E --> F[Resolved Module Instance] ``` ## Usage ```ts import type { DynamicModule, Type } from '@nestjs/common'; interface ModuleFactory { type: Type; token: string; dynamicMetadata: Partial; } class DatabaseModule {} const databaseModuleFactory: ModuleFactory = { type: DatabaseModule, token: 'database-module-token', dynamicMetadata: { providers: [ { provide: 'DATABASE_URL', useValue: process.env.DATABASE_URL, }, ], exports: ['DATABASE_URL'], }, }; // Pass the compiled module definition to the injector/compiler flow. registerCompiledModule(databaseModuleFactory); ``` ## AI Coding Instructions - Preserve `token` stability: it should uniquely identify the module and its dynamic configuration within the container. - Use `type` for the concrete module class; do not replace it with an instance or plain object. - Treat `dynamicMetadata` as optional/partial metadata and guard against missing properties before reading arrays such as `providers`, `imports`, or `exports`. - Ensure dynamic module metadata matches the `DynamicModule` contract so injector resolution can register providers and exports correctly. - When generating factories, keep token creation and metadata normalization centralized in the compiler pipeline. ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `ForwardReference` - IMPORTS → `Type` # ReflectableDecorator **Kind:** Type **Source:** [`packages/core/services/reflector.service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/services/reflector.service.ts#L31) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts (( opts?: TParam, ) => CustomDecorator) & { KEY: string; } ``` # requestProvider **Kind:** Constant **Source:** [`packages/core/router/request/request-providers.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/request/request-providers.ts#L5) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Provider ``` ## Value ```ts { provide: REQUEST, scope: Scope.REQUEST, useFactory: noop, } ``` ## Relationships - IMPORTS → `Provider` - IMPORTS → `Scope` # Resolver **Kind:** Interface **Source:** [`packages/core/router/interfaces/resolver.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/resolver.interface.ts#L1) **Part of:** [Core](subsystem-packages-core) # RouterProxyCallback **Kind:** Type **Source:** [`packages/core/router/router-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-proxy.ts#L4) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts ( req: TRequest, res: TResponse, next: () => void, ) => void | Promise ``` # RouteTree **Kind:** Interface **Source:** [`packages/core/router/interfaces/routes.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/routes.interface.ts#L3) **Part of:** [Core](subsystem-packages-core) `RouteTree` defines a hierarchical route configuration for the router. Each node maps a URL `path` to a module and can contain nested route nodes or module types as `children`, allowing the application to compose route trees declaratively. ## Properties | Property | Type | |---|---| | `path` | `string` | | `module` | `Type` | | `children` | `(RouteTree | Type)[]` | ## Diagram ```mermaid graph LR Root["RouteTree"] Path["path: string"] Module["module: Type<any>"] Children["children: (RouteTree | Type<any>)[]"] Root --> Path Root --> Module Root --> Children Children --> NestedRoute["Nested RouteTree"] Children --> ChildModule["Child Module Type"] ``` ## Usage ```ts import type { Type } from '@blaze/core'; import type { RouteTree } from '@blaze/core/router'; class AppModule {} class UsersModule {} class UserProfileModule {} const routes: RouteTree = { path: '/', module: AppModule, children: [ { path: '/users', module: UsersModule, children: [UserProfileModule], }, ], }; ``` ## AI Coding Instructions - Define `path` values as router-recognized URL segments and keep nested paths consistent with the parent route structure. - Set `module` to the module responsible for handling the route; it must be a runtime class/type, not an instance. - Use nested `RouteTree` objects when child routes need their own path and children configuration. - Use `Type` entries directly in `children` only for child modules that do not require explicit route metadata. - Avoid placing arbitrary values in `children`; every entry must be either a valid `RouteTree` or a module type. ## How it works ## Structure `RouteTree` is an exported TypeScript interface for one node in a module-route hierarchy. It has a required `path: string`, optional `module?: Type`, and optional `children?: (RouteTree | Type)[]`; `Routes` is an array of these nodes. [packages/core/router/interfaces/routes.interface.ts:3-9] `Type` is a constructible function type with a `new (...args: any[])` signature, so `module` and direct `children` entries are class/constructor references at the type level. [packages/common/interfaces/type.interface.ts:1-3] ## Route-tree behavior A node with both a truthy `module` and a truthy `path` becomes a flattened `{ module, path }` route entry. [packages/core/router/utils/flatten-route-paths.util.ts:10-13] A node may omit `module` and act as a path grouping node for `children`; the flattener still descends into its children. [packages/core/router/utils/flatten-route-paths.util.ts:11-14] Nested object children whose `path` is a string have their paths rewritten to the normalized concatenation of the parent path and child path before recursive processing. [packages/core/router/utils/flatten-route-paths.util.ts:16-20,25] Tests show this produces accumulated paths such as `/parent/child/child2` for nested route objects. [packages/core/test/router/utils/flat-routes.spec.ts:44-68,104-116] A direct constructor in `children` is flattened as a module at its parent node’s path. [packages/core/router/utils/flatten-route-paths.util.ts:16-23] This shape is exercised with `children: [AuthModule, CatsModule, DogsModule]`, producing one route entry per module at `/v1`. [packages/core/test/router/utils/flat-routes.spec.ts:100-102,122-128] Path normalization adds a leading slash, removes trailing slashes, collapses repeated slashes, and maps an absent or empty path to `/`. [packages/common/utils/shared.utils.ts:33-38] For example, a route configured as `path: '/module-path/'` is tested at `/module-path/test`. [integration/hello-world/e2e/router-module-middleware.spec.ts:49-54,62-65] ## Consumption by `RouterModule` `RouterModule.register()` accepts `Routes` and places that array in a provider under the `ROUTES` symbol. [packages/core/router/router-module.ts:9,29-38] On construction, `RouterModule` recursively clones route objects while retaining direct constructor entries, then initializes from the clone. [packages/core/router/router-module.ts:21-27,41-56] Initialization flattens the cloned tree, normalizes each resulting path, stores it as reflection metadata on the target module under a key derived from `MODULE_PATH` and the container application ID, and records matching module references in a `WeakSet` associated with that container. [packages/core/router/router-module.ts:58-75,78-93] If a flattened module constructor is not found in the container, the cache update returns without adding it. [packages/core/router/router-module.ts:86-92] The interface and registration method contain no explicit runtime validation or explicit error handling for route fields. [packages/core/router/interfaces/routes.interface.ts:3-7] During flattening, an object child without a string `path` is treated as a module constructor rather than as a nested route object. [packages/core/router/utils/flatten-route-paths.util.ts:16-23] ## Relationships - IMPORTS → `Type` # UndefinedForwardRefException **Kind:** Class **Source:** [`packages/core/errors/exceptions/undefined-forwardref.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/undefined-forwardref.exception.ts#L5) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `Type` # UndefinedModuleException **Kind:** Class **Source:** [`packages/core/errors/exceptions/undefined-module.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/undefined-module.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # UnknownExportException **Kind:** Class **Source:** [`packages/core/errors/exceptions/unknown-export.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/unknown-export.exception.ts#L4) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # UnknownRequestMappingException **Kind:** Class **Source:** [`packages/core/errors/exceptions/unknown-request-mapping.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions/unknown-request-mapping.exception.ts#L5) **Part of:** [Core](subsystem-packages-core) **Extends:** `RuntimeException` # AdditionalHeaders **Kind:** Type **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L38) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Record< string, string[] | string | number | undefined > ``` ## Relationships - IMPORTS → `MessageEvent` - IMPORTS → `isNil` - IMPORTS → `isObject` - IMPORTS → `isUndefined` # CustomHeader **Kind:** Interface **Source:** [`packages/core/router/router-response-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-response-controller.ts#L18) **Part of:** [Core](subsystem-packages-core) `CustomHeader` defines a single HTTP response header managed by the router response controller. Each header has a `name` and a `value`, where the value can be static or generated dynamically when the response is prepared. ## Properties | Property | Type | |---|---| | `name` | `string` | | `value` | `string | (() => string)` | ## Diagram ```mermaid graph LR Controller[Router Response Controller] --> Header[CustomHeader] Header --> Name[name: string] Header --> Value[value: string] Header --> DynamicValue[value: () => string] DynamicValue --> ResolvedValue[Resolved response header value] ``` ## Usage ```ts import type { CustomHeader } from '@your-package/core'; const staticHeader: CustomHeader = { name: 'Cache-Control', value: 'public, max-age=3600', }; const dynamicHeader: CustomHeader = { name: 'X-Request-Time', value: () => new Date().toISOString(), }; // Pass headers to the router response controller configuration. const headers: CustomHeader[] = [staticHeader, dynamicHeader]; ``` ## AI Coding Instructions - Use lowercase or conventional HTTP header names consistently with the surrounding response-controller configuration. - Provide a string for fixed header values and a `() => string` callback only when the value must be resolved dynamically. - Ensure dynamic value callbacks are synchronous and always return a string. - Avoid placing request-specific asynchronous work in `value`; compute it before creating the header or use the appropriate response middleware integration point. ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `HttpStatus` - IMPORTS → `Logger` - IMPORTS → `RequestMethod` - IMPORTS → `MessageEvent` - IMPORTS → `isObject` # Extras **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/extras.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/extras.interface.ts#L18) **Part of:** [Core](subsystem-packages-core) `Extras` groups enhancer definitions discovered by the inspector into two categories: orphaned enhancers and enhancers attached to known targets. It provides a consistent shape for consumers that need to inspect, display, or process enhancer metadata while preserving whether each enhancer is currently associated with an entity. ## Properties | Property | Type | |---|---| | `orphanedEnhancers` | `Array` | | `attachedEnhancers` | `Array` | ## Diagram ```mermaid graph LR Extras[Extras] Orphaned[orphanedEnhancers
Array<OrphanedEnhancerDefinition>] Attached[attachedEnhancers
Array<AttachedEnhancerDefinition>] Extras --> Orphaned Extras --> Attached ``` ## Usage ```ts import type { Extras } from "./interfaces/extras.interface"; function summarizeExtras(extras: Extras): string[] { return [ `Attached enhancers: ${extras.attachedEnhancers.length}`, `Orphaned enhancers: ${extras.orphanedEnhancers.length}`, ]; } const extras: Extras = { attachedEnhancers: [], orphanedEnhancers: [], }; console.log(summarizeExtras(extras)); ``` ## AI Coding Instructions - Always provide both `attachedEnhancers` and `orphanedEnhancers`; use empty arrays when no definitions exist. - Place enhancer definitions in `attachedEnhancers` only when they have a valid inspected target or association. - Preserve orphaned definitions instead of discarding them, as they may be required for diagnostics or later reconciliation. - Use the specific `AttachedEnhancerDefinition` and `OrphanedEnhancerDefinition` types rather than mixing both categories into a shared untyped array. ## How it works `Extras` is a TypeScript interface for the `extras` section of a serialized inspector graph. A `SerializedGraphJson` contains `extras: Extras` alongside its nodes, edges, and entrypoints. [serialized-graph-json.interface.ts:8-14] It requires two arrays: - `orphanedEnhancers: Array` records globally registered filters, pipes, interceptors, and guards. Each entry has a `subtype` limited to `'guard'`, `'interceptor'`, `'pipe'`, or `'filter'`, plus a `ref` typed as `unknown`. [extras.interface.ts:10-20] [constants.ts:26-34] - `attachedEnhancers: Array` records enhancers attached through `APP_PIPE`, `APP_GUARD`, `APP_INTERCEPTOR`, or `APP_FILTER`; each entry contains the associated graph `nodeId`. [extras.interface.ts:3-8] [core/constants.ts:13-28] `SerializedGraph` initializes both arrays as empty and appends entries through `insertOrphanedEnhancer()` and `insertAttachedEnhancer()`. It includes the same `extras` object in `toJSON()` output; neither insertion method validates entries or removes duplicates. [serialized-graph.ts:26-34] [serialized-graph.ts:111-119] [serialized-graph.ts:125-140] When application methods register global filters, pipes, interceptors, or guards, each resulting item is added as an orphaned enhancer with its corresponding subtype. Before it reaches the graph, `GraphInspector` replaces the entry’s `ref` with `entry.ref.constructor.name`, falling back to `'Object'` when no constructor name is available. [nest-application.ts:403-454] [graph-inspector.ts:86-91] For attached enhancers, the scanner resolves the registered application provider’s wrapper, records it as attached, and applies it through the request-scoped/transient or regular provider path. [scanner.ts:666-703] `GraphInspector.insertAttachedEnhancer()` looks up the wrapper’s existing graph node, sets that node’s `metadata.global` to `true`, and appends its ID to `attachedEnhancers`; there is no runtime check for a missing node before accessing its metadata. [graph-inspector.ts:93-98] # ModuleDebugEntry **Kind:** Type **Source:** [`packages/core/repl/repl-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-context.ts#L22) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { controllers: Record; providers: Record; } ``` ## Relationships - IMPORTS → `INestApplicationContext` - IMPORTS → `InjectionToken` - IMPORTS → `Logger` # Node **Kind:** Type **Source:** [`packages/core/inspector/interfaces/node.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/node.interface.ts#L44) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts { id: string; label: string; } & (ClassNode | ModuleNode) ``` # OrphanedEnhancerDefinition **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/extras.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/extras.interface.ts#L13) **Part of:** [Core](subsystem-packages-core) Enhancers registered through "app.useGlobalPipes()", "app.useGlobalGuards()", "app.useGlobalInterceptors()", and "app.useGlobalFilters()" methods. `OrphanedEnhancerDefinition` describes globally registered NestJS enhancers that are not attached to a specific module provider definition. It is used by the inspector to track pipes, guards, interceptors, and filters registered through application-level methods such as `app.useGlobalGuards()` and preserve both their enhancer subtype and original runtime reference. ## Properties | Property | Type | |---|---| | `subtype` | `EnhancerSubtype` | | `ref` | `unknown` | ## Diagram ```mermaid graph LR App[Nest Application] -->|useGlobalPipes / Guards / Interceptors / Filters| Enhancer[Global Enhancer Instance] Enhancer --> Definition[OrphanedEnhancerDefinition] Definition --> Subtype[subtype: EnhancerSubtype] Definition --> Ref[ref: unknown] Definition --> Inspector[Core Inspector] ``` ## Usage ```ts import type { OrphanedEnhancerDefinition } from '@nestjs/core/inspector/interfaces/extras.interface'; import { EnhancerSubtype } from '@nestjs/core/inspector/interfaces/enhancer-metadata-cache.interface'; const globalGuard = { canActivate: () => true, }; const definition: OrphanedEnhancerDefinition = { subtype: EnhancerSubtype.GUARD, ref: globalGuard, }; // The inspector can retain this definition for later graph analysis. function registerOrphanedEnhancer( enhancer: OrphanedEnhancerDefinition, ): void { console.log(`Registered global ${enhancer.subtype}`, enhancer.ref); } registerOrphanedEnhancer(definition); ``` ## AI Coding Instructions - Use this interface only for enhancers registered globally through `useGlobalPipes`, `useGlobalGuards`, `useGlobalInterceptors`, or `useGlobalFilters`. - Set `subtype` to the matching `EnhancerSubtype`; do not infer the enhancer kind solely from the shape of `ref`. - Preserve the original enhancer instance, class, or token in `ref`, since it is intentionally typed as `unknown`. - Treat these definitions as inspector metadata rather than dependency-injection provider metadata; globally registered enhancers may not have a module ownership relationship. # ParamMetadata **Kind:** Interface **Source:** [`packages/core/helpers/interfaces/params-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/interfaces/params-metadata.interface.ts#L4) **Part of:** [Core](subsystem-packages-core) `ParamMetadata` describes metadata for a single parameter in a handler, resolver, or decorated method. It stores the parameter's positional `index` and associated `data`, allowing the framework to resolve and inject the correct value at runtime. ## Properties | Property | Type | |---|---| | `index` | `number` | | `data` | `ParamData` | ## Diagram ```mermaid graph LR Handler[Handler Method] --> Params[Parameter List] Params --> Metadata[ParamMetadata] Metadata --> Index[index: number] Metadata --> Data[data: ParamData] Metadata --> Resolver[Parameter Resolver] ``` ## Usage ```ts import type { ParamMetadata } from './helpers/interfaces/params-metadata.interface'; const userIdParam: ParamMetadata = { index: 0, data: { name: 'userId', type: 'param', }, }; function resolveParameter(metadata: ParamMetadata, request: Request) { if (metadata.data.type === 'param') { return request.params[metadata.data.name]; } return undefined; } const userId = resolveParameter(userIdParam, request); ``` ## AI Coding Instructions - Keep `index` aligned with the parameter's zero-based position in the target method signature. - Use the appropriate `ParamData` shape when creating metadata; avoid replacing it with untyped objects. - Preserve parameter metadata ordering when collecting metadata for a method or resolver. - Use `ParamMetadata` with the parameter-resolution pipeline rather than reading request or context values directly in framework internals. # PropertyMetadata **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L50) **Part of:** [Core](subsystem-packages-core) `PropertyMetadata` describes a property-level dependency managed by the injector. It associates a property key with the `InstanceWrapper` that contains the dependency's registration, lifecycle, and resolved instance information. The interface is typically used when collecting metadata for property injection on a class instance. ## Properties | Property | Type | |---|---| | `key` | `symbol | string` | | `wrapper` | `InstanceWrapper` | ## Diagram ```mermaid graph LR A[Target Class Property] --> B[PropertyMetadata] B --> C[key: symbol | string] B --> D[wrapper: InstanceWrapper] D --> E[Provider Definition] D --> F[Resolved Dependency Instance] ``` ## Usage ```ts import { InstanceWrapper } from './instance-wrapper'; interface PropertyMetadata { key: symbol | string; wrapper: InstanceWrapper; } class Logger { log(message: string) { console.log(message); } } class UserService { logger!: Logger; } const loggerWrapper = new InstanceWrapper({ token: Logger, metatype: Logger, }); const propertyMetadata: PropertyMetadata = { key: 'logger', wrapper: loggerWrapper, }; // Injector logic can use the metadata to assign the resolved dependency. const userService = new UserService(); userService[propertyMetadata.key] = loggerWrapper.instance; userService.logger.log('Property dependency injected'); ``` ## AI Coding Instructions - Use `key` as the exact property name or symbol defined on the target class; do not substitute the provider token unless they are intentionally the same. - Always provide an `InstanceWrapper` that represents the dependency provider and its lifecycle state. - Support both string and symbol property keys when reading or assigning injected properties. - Keep property metadata collection separate from instance assignment; the injector should resolve the wrapper before setting the target property. - When adding property injection behavior, preserve wrapper scope and lifecycle handling rather than directly constructing dependencies. ## How it works ## `PropertyMetadata` `PropertyMetadata` is an exported TypeScript interface that records one property dependency for an `InstanceWrapper`. It contains: - `key`: the target property name or symbol (`string | symbol`). [packages/core/injector/instance-wrapper.ts:50-53] - `wrapper`: the `InstanceWrapper` for the dependency associated with that property. [packages/core/injector/instance-wrapper.ts:50-53] It has no methods, runtime validation, or direct side effects; it is a compile-time interface whose values are stored in an `InstanceWrapper`’s internal metadata cache under `properties`. [packages/core/injector/instance-wrapper.ts:55-58] # RedirectResponse **Kind:** Interface **Source:** [`packages/core/router/router-response-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-response-controller.ts#L23) **Part of:** [Core](subsystem-packages-core) `RedirectResponse` represents the data required to issue an HTTP redirect from the router response controller. It pairs a destination URL with the HTTP status code that determines how clients should handle the redirect, such as `302` for temporary redirects or `301` for permanent redirects. ## Properties | Property | Type | |---|---| | `url` | `string` | | `statusCode` | `number` | ## Diagram ```mermaid graph LR Router[Router Handler] --> ResponseController[Router Response Controller] ResponseController --> RedirectResponse RedirectResponse --> URL[url: string] RedirectResponse --> Status[statusCode: number] ResponseController --> HTTPRedirect[HTTP Redirect Response] ``` ## Usage ```ts import type { RedirectResponse } from './router-response-controller'; const redirectToLogin: RedirectResponse = { url: '/login?returnUrl=%2Fdashboard', statusCode: 302, }; // Pass the redirect response to the router response controller. responseController.redirect(redirectToLogin); ``` ## AI Coding Instructions - Always provide a valid redirect target in `url`; preserve or encode query parameters when building dynamic URLs. - Use an appropriate HTTP redirect status code: `301`/`308` for permanent redirects and `302`/`307` for temporary redirects. - Keep redirect construction within routing or response-controller logic rather than returning raw redirect objects from unrelated services. - Validate or constrain externally supplied redirect URLs to prevent open redirect vulnerabilities. # targetModulesByContainer **Kind:** Constant **Source:** [`packages/core/router/router-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-module.ts#L11) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts new WeakMap< ModulesContainer, WeakSet >() ``` ## Value ```ts new WeakMap< ModulesContainer, WeakSet >() ``` # AttachedEnhancerDefinition **Kind:** Interface **Source:** [`packages/core/inspector/interfaces/extras.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/interfaces/extras.interface.ts#L6) **Part of:** [Core](subsystem-packages-core) Enhancers attached through APP_PIPE, APP_GUARD, APP_INTERCEPTOR, and APP_FILTER tokens. `AttachedEnhancerDefinition` represents an enhancer registered through NestJS application-level tokens such as `APP_PIPE`, `APP_GUARD`, `APP_INTERCEPTOR`, or `APP_FILTER`. It links the discovered enhancer definition to the identifier of the dependency graph node that provides or declares it. ## Properties | Property | Type | |---|---| | `nodeId` | `string` | ## Diagram ```mermaid graph LR A[APP_PIPE / APP_GUARD / APP_INTERCEPTOR / APP_FILTER] --> B[AttachedEnhancerDefinition] B --> C[nodeId: string] C --> D[Inspector dependency graph node] ``` ## Usage ```ts import type { AttachedEnhancerDefinition } from './interfaces/extras.interface'; const attachedGuard: AttachedEnhancerDefinition = { nodeId: 'auth-guard-provider-node', }; function registerAttachedEnhancer( enhancer: AttachedEnhancerDefinition, ) { console.log(`Tracking application enhancer node: ${enhancer.nodeId}`); } registerAttachedEnhancer(attachedGuard); ``` ## AI Coding Instructions - Use `nodeId` to reference the corresponding provider or dependency-graph node; do not store the enhancer instance directly in this interface. - Populate this definition only for enhancers attached through `APP_PIPE`, `APP_GUARD`, `APP_INTERCEPTOR`, or `APP_FILTER`. - Ensure `nodeId` matches the identifier generated by the inspector's graph or provider-discovery process. - Keep this interface lightweight and serializable because it may be stored or emitted as inspector metadata. ## Relationships - IMPORTS → `EnhancerSubtype` # DiscoverableDecorator **Kind:** Type **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L42) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts ((opts?: T) => CustomDecorator) & { KEY: string; } ``` # ParamsFactory **Kind:** Interface **Source:** [`packages/core/helpers/external-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/external-context-creator.ts#L28) **Part of:** [Core](subsystem-packages-core) ## Relationships - IMPORTS → `ForbiddenException` - IMPORTS → `ParamData` - IMPORTS → `CUSTOM_ROUTE_ARGS_METADATA` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `PipeTransform` - IMPORTS → `isEmpty` # APP_FILTER **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L16) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'APP_FILTER' ``` ## Value ```ts 'APP_FILTER' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RecipesModule` — `integration/graphql-code-first/src/recipes/recipes.module.ts`:8 # REQUEST_CONTEXT_ID **Kind:** Constant **Source:** [`packages/core/router/request/request-constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/request/request-constants.ts#L2) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Symbol('REQUEST_CONTEXT_ID') ``` ## Value ```ts Symbol('REQUEST_CONTEXT_ID') ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ListenersController` — `packages/microservices/listeners-controller.ts`:45 # anonymousMiddleware **Kind:** Middleware **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L77) **Part of:** [Core](subsystem-packages-core) ## Relationships - IMPORTS → `RequestMethod` - IMPORTS → `HttpServer` - IMPORTS → `RouteInfo` - IMPORTS → `Type` - IMPORTS → `addLeadingSlash` - IMPORTS → `isFunction` - IMPORTS → `isString` # APP_PIPE **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L14) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'APP_PIPE' ``` ## Value ```ts 'APP_PIPE' ``` # ContextIdResolverFn **Kind:** Type **Source:** [`packages/core/helpers/context-id-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-id-factory.ts#L17) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts (info: HostComponentInfo) => ContextId ``` # CONTROLLER_ID_KEY **Kind:** Constant **Source:** [`packages/core/injector/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/constants.ts#L3) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'CONTROLLER_ID' ``` ## Value ```ts 'CONTROLLER_ID' ``` # DiscoveryOptions **Kind:** Type **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L37) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts FilterByInclude | FilterByMetadataKey ``` # handler **Kind:** API Endpoint **Source:** [`packages/core/middleware/middleware-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/middleware-module.ts#L287) **Part of:** [Core](subsystem-packages-core) ## Endpoint `GET /` ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `InjectionToken` - IMPORTS → `Logger` - IMPORTS → `RequestMethod` - IMPORTS → `MiddlewareConfiguration` - IMPORTS → `NestMiddleware` - IMPORTS → `RouteInfo` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `isUndefined` # handler **Kind:** API Endpoint **Source:** [`packages/core/middleware/middleware-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/middleware-module.ts#L287) **Part of:** [Core](subsystem-packages-core) ## Endpoint `GET /` ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `InjectionToken` - IMPORTS → `Logger` - IMPORTS → `RequestMethod` - IMPORTS → `MiddlewareConfiguration` - IMPORTS → `NestMiddleware` - IMPORTS → `RouteInfo` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `isUndefined` # handler **Kind:** API Endpoint **Source:** [`packages/core/middleware/resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/resolver.ts#L18) **Part of:** [Core](subsystem-packages-core) ## Endpoint `ALL /` ## Relationships - IMPORTS → `InjectionToken` # HANDLER_METADATA_SYMBOL **Kind:** Constant **Source:** [`packages/core/helpers/handler-metadata-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/handler-metadata-storage.ts#L9) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Symbol.for('handler_metadata:cache') ``` ## Value ```ts Symbol.for('handler_metadata:cache') ``` ## Relationships - IMPORTS → `Controller` - IMPORTS → `Type` # HandleResponseFn **Kind:** Type **Source:** [`packages/core/helpers/handler-metadata-storage.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/handler-metadata-storage.ts#L11) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts HandlerResponseBasicFn | HandleSseResponseFn ``` # HeaderStream **Kind:** Type **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L59) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts WritableHeaderStream & ReadHeaders ``` # InjectorDependency **Kind:** Type **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L51) **Part of:** [Core](subsystem-packages-core) The type of an injectable dependency `InjectorDependency` represents a value that can be requested from the dependency injector. It is used when declaring or passing dependency requirements so the injector can identify the appropriate provider and resolve an instance at runtime. This type keeps dependency declarations consistent across injector registration and resolution APIs. ## Definition ```ts InjectionToken ``` ## Diagram ```mermaid graph LR Consumer[Consumer / Service] --> Dependency[InjectorDependency] Dependency --> Injector[Injector] Injector --> Provider[Registered Provider] Provider --> Instance[Resolved Instance] Instance --> Consumer ``` ## Usage ```ts import type { InjectorDependency } from './injector'; class Logger { log(message: string): void { console.log(message); } } // A class/token that can be resolved by the injector. const loggerDependency: InjectorDependency = Logger; function requiresDependency(dependency: InjectorDependency) { return dependency; } requiresDependency(loggerDependency); ``` ## AI Coding Instructions - Use `InjectorDependency` for values passed to injector APIs that represent a dependency requirement or provider lookup key. - Prefer declared service classes or supported injection tokens rather than ad hoc string values unless the surrounding injector API explicitly supports them. - Keep dependency declarations aligned with registered providers; an unresolved dependency will fail when the injector attempts resolution. - Import this type with `import type` when it is only used for TypeScript annotations. ## Relationships - IMPORTS → `InjectionToken` - IMPORTS → `Logger` - IMPORTS → `LoggerService` - IMPORTS → `OptionalFactoryDependency` - IMPORTS → `Scope` - IMPORTS → `OPTIONAL_DEPS_METADATA` - IMPORTS → `OPTIONAL_PROPERTY_DEPS_METADATA` - IMPORTS → `PARAMTYPES_METADATA` - IMPORTS → `PROPERTY_DEPS_METADATA` - IMPORTS → `SELF_DECLARED_DEPS_METADATA` - IMPORTS → `Controller` - IMPORTS → `ForwardReference` - IMPORTS → `Injectable` - IMPORTS → `Type` - IMPORTS → `isFunction` - IMPORTS → `isNil` - IMPORTS → `isObject` - IMPORTS → `isString` - IMPORTS → `isSymbol` - IMPORTS → `isUndefined` # INSTANCE_ID_SYMBOL **Kind:** Constant **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L23) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Symbol.for('instance_metadata:id') ``` ## Value ```ts Symbol.for('instance_metadata:id') ``` # INSTANCE_METADATA_SYMBOL **Kind:** Constant **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L22) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Symbol.for('instance_metadata:cache') ``` ## Value ```ts Symbol.for('instance_metadata:cache') ``` ## Relationships - IMPORTS → `Logger` - IMPORTS → `LoggerService` - IMPORTS → `Provider` - IMPORTS → `Scope` - IMPORTS → `Type` - IMPORTS → `EnhancerSubtype` - IMPORTS → `FactoryProvider` - IMPORTS → `InjectionToken` - IMPORTS → `randomStringGenerator` - IMPORTS → `isNil` - IMPORTS → `isString` - IMPORTS → `isUndefined` # INVALID_EXCEPTION_FILTER **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L262) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts `Invalid exception filters (@UseFilters()).` ``` ## Value ```ts `Invalid exception filters (@UseFilters()).` ``` # INVALID_MIDDLEWARE_CONFIGURATION **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L260) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts `An invalid middleware configuration has been passed inside the module 'configure()' method.` ``` ## Value ```ts `An invalid middleware configuration has been passed inside the module 'configure()' method.` ``` # metatype **Kind:** API Endpoint **Source:** [`packages/core/middleware/middleware-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/middleware-module.ts#L202) **Part of:** [Core](subsystem-packages-core) ## Endpoint `GET /` # MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L263) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts `Unable to load @nestjs/microservices package. (Please make sure that it's already installed.)` ``` ## Value ```ts `Unable to load @nestjs/microservices package. (Please make sure that it's already installed.)` ``` # moduleKey **Kind:** API Endpoint **Source:** [`packages/core/middleware/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/container.ts#L27) **Part of:** [Core](subsystem-packages-core) ## Endpoint `GET /` # moduleName **Kind:** API Endpoint **Source:** [`packages/core/middleware/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/container.ts#L68) **Part of:** [Core](subsystem-packages-core) ## Endpoint `GET /` ## Relationships - IMPORTS → `InjectionToken` - IMPORTS → `Type` - IMPORTS → `MiddlewareConfiguration` # modulesContainer **Kind:** API Endpoint **Source:** [`packages/core/middleware/routes-mapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/routes-mapper.ts#L148) **Part of:** [Core](subsystem-packages-core) ## Endpoint `GET /` ## Relationships - IMPORTS → `MODULE_PATH` - IMPORTS → `PATH_METADATA` - IMPORTS → `VERSION_METADATA` - IMPORTS → `RouteInfo` - IMPORTS → `Type` - IMPORTS → `VERSION_NEUTRAL` - IMPORTS → `VersionValue` - IMPORTS → `addLeadingSlash` - IMPORTS → `isString` - IMPORTS → `isUndefined` # NestFactory **Kind:** Constant **Source:** [`packages/core/nest-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts#L402) **Part of:** [Core](subsystem-packages-core) Use NestFactory to create an application instance. ### Specifying an entry module Pass the required *root module* for the application via the module parameter. By convention, it is usually called `ApplicationModule`. Starting with this module, Nest assembles the dependency graph and begins the process of Dependency Injection and instantiates the classes needed to launch your application. `NestFactory` creates and initializes Nest application instances from a root module. It starts the dependency-injection graph, configures the selected runtime adapter, and returns an application object that can be configured and started. ## Definition ```ts new NestFactoryStatic() ``` ## Value ```ts new NestFactoryStatic() ``` ## Diagram ```mermaid graph LR A[ApplicationModule] --> B[NestFactory] B --> C[Dependency Injection Container] C --> D[Providers and Controllers] B --> E[Nest Application Instance] E --> F[Configure Middleware / Pipes / Guards] F --> G[app.listen()] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { ApplicationModule } from './application.module'; async function bootstrap() { const app = await NestFactory.create(ApplicationModule); app.setGlobalPrefix('api'); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Pass the application's root module (commonly `ApplicationModule` or `AppModule`) as the first argument to `NestFactory.create()`. - Await application creation before configuring global middleware, pipes, guards, interceptors, or filters. - Configure the returned application instance before calling `app.listen()` so startup behavior is consistent. - Use the appropriate factory method for the runtime: `create()` for HTTP applications, `createMicroservice()` for microservices, and `createApplicationContext()` for standalone contexts. # REPL_INITIALIZED_MESSAGE **Kind:** Constant **Source:** [`packages/core/repl/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/constants.ts#L1) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'REPL initialized' ``` ## Value ```ts 'REPL initialized' ``` # ReplFunctionClass **Kind:** Type **Source:** [`packages/core/repl/repl.interfaces.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl.interfaces.ts#L21) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts new (replContext: ReplContext) => ReplFunction ``` # Routes **Kind:** Type **Source:** [`packages/core/router/interfaces/routes.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/interfaces/routes.interface.ts#L9) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts RouteTree[] ``` # ROUTES **Kind:** Constant **Source:** [`packages/core/router/router-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-module.ts#L9) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts Symbol('ROUTES') ``` ## Value ```ts Symbol('ROUTES') ``` ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Inject` - IMPORTS → `Module` - IMPORTS → `Type` - IMPORTS → `MODULE_PATH` - IMPORTS → `normalizePath` # SerializedGraphStatus **Kind:** Type **Source:** [`packages/core/inspector/serialized-graph.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/serialized-graph.ts#L22) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts 'partial' | 'complete' ``` ## Relationships - IMPORTS → `InjectionToken` # UNHANDLED_RUNTIME_EXCEPTION **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L261) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts `Unhandled Runtime Exception.` ``` ## Value ```ts `Unhandled Runtime Exception.` ``` # WritableHeaderStream **Kind:** Type **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L58) **Part of:** [Core](subsystem-packages-core) ## Definition ```ts NodeJS.WritableStream & WriteHeaders ``` # SubscribeMessage **Kind:** Function **Source:** [`packages/websockets/decorators/subscribe-message.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/subscribe-message.decorator.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) Subscribes to messages that fulfils chosen pattern. `SubscribeMessage()` marks a WebSocket gateway method as a handler for a specific incoming message pattern. When a connected client emits the matching event, NestJS routes the payload and socket context to the decorated method. ## Signature ```ts function SubscribeMessage(message: T): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `message` | `T` | **Returns:** `MethodDecorator` ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|emit event + payload| Server[WebSocket Server] Server -->|match message pattern| Decorator["@SubscribeMessage('event')"] Decorator --> Handler[Gateway Handler Method] Handler -->|optional response| Client ``` ## Usage ```ts import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, } from '@nestjs/websockets'; import { Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('chat:message') handleChatMessage( @MessageBody() message: { text: string }, @ConnectedSocket() client: Socket, ) { return { event: 'chat:received', data: { clientId: client.id, text: message.text, }, }; } } ``` ## AI Coding Instructions - Apply `@SubscribeMessage()` only to methods in classes configured as WebSocket gateways. - Use stable, descriptive message patterns such as `chat:message` or `user:updated` to avoid event-name collisions. - Extract incoming data with `@MessageBody()` and connection details with `@ConnectedSocket()` rather than manually parsing handler arguments. - Validate and sanitize message payloads before performing business logic or broadcasting results. - Return a `{ event, data }` object when the handler should emit a response event back to the client. ## Used by 12 references from 12 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (12) - `ChatGateway` — `integration/inspector/src/chat/chat.gateway.ts`:10 - `AckGateway` — `integration/websockets/src/ack.gateway.ts`:8 - `ApplicationGateway` — `integration/websockets/src/app.gateway.ts`:12 - `CoreGateway` — `integration/websockets/src/core.gateway.ts`:8 - `ErrorGateway` — `integration/websockets/src/error.gateway.ts`:8 - `ExamplePathGateway` — `integration/websockets/src/example-path.gateway.ts`:3 - `NamespaceGateway` — `integration/websockets/src/namespace.gateway.ts`:3 - `ServerGateway` — `integration/websockets/src/server.gateway.ts`:6 …and 4 more. # WebSocketsController **Kind:** Class **Source:** [`packages/websockets/web-sockets-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/web-sockets-controller.ts#L29) **Part of:** [Websockets](subsystem-packages-websockets) `WebSocketsController` is the framework-level coordinator that discovers WebSocket gateway entrypoints and connects them to the configured socket server. It subscribes gateway lifecycle hooks (`init`, `connection`, `disconnect`) and message handlers, then normalizes handler results into observables for transport delivery. ## Methods | Method | Signature | Returns | |---|---|---| | `connectGatewayToServer` | `connectGatewayToServer(instance: NestGateway, metatype: Type | Function, moduleKey: string, instanceWrapperId: string)` | `void` | | `subscribeToServerEvents` | `subscribeToServerEvents(instance: NestGateway, options: T, port: number, moduleKey: string, instanceWrapperId: string)` | `void` | | `subscribeEvents` | `subscribeEvents(instance: NestGateway, subscribersMap: MessageMappingProperties[], observableServer: ServerAndEventStreamsHost)` | `void` | | `getConnectionHandler` | `getConnectionHandler(context: WebSocketsController, instance: NestGateway, subscribersMap: MessageMappingProperties[], disconnect: Subject, connection: Subject)` | `void` | | `subscribeInitEvent` | `subscribeInitEvent(instance: NestGateway, event: Subject)` | `void` | | `subscribeConnectionEvent` | `subscribeConnectionEvent(instance: NestGateway, event: Subject)` | `void` | | `subscribeDisconnectEvent` | `subscribeDisconnectEvent(instance: NestGateway, event: Subject)` | `void` | | `subscribeMessages` | `subscribeMessages(subscribersMap: MessageMappingProperties[], client: T, instance: NestGateway)` | `void` | | `pickResult` | `pickResult(deferredResult: Promise)` | `Promise>` | | `inspectEntrypointDefinitions` | `inspectEntrypointDefinitions(instance: NestGateway, port: number, messageHandlers: MessageMappingProperties[], instanceWrapperId: string)` | `void` | ## Where it refuses work - `WebSocketsController` stops the work with `InvalidSocketPortException` when `!Number.isInteger(port)`. - `WebSocketsController` stops the work with an early return when `this.appOptions.preview`. - `WebSocketsController` stops the work with an early return when `isObservable(result)`. - `WebSocketsController` stops the work with an early return when `result instanceof Promise`. - `WebSocketsController` stops the work with an early return when `!gatewayClassName`. ## Diagram ```mermaid graph LR A[Gateway Provider] --> B[WebSocketsController] B --> C[inspectEntrypointDefinitions] B --> D[connectGatewayToServer] D --> E[Socket Server] B --> F[subscribeToServerEvents] F --> G[subscribeInitEvent] F --> H[subscribeConnectionEvent] F --> I[subscribeDisconnectEvent] F --> J[subscribeMessages] J --> K[getConnectionHandler] K --> L[pickResult] L --> M[Observable Response] E --> N[Connected Clients] ``` ## Usage ```ts import { SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway({ namespace: '/chat' }) export class ChatGateway { @WebSocketServer() server: Server; handleConnection(client: Socket) { console.log(`Client connected: ${client.id}`); } handleDisconnect(client: Socket) { console.log(`Client disconnected: ${client.id}`); } @SubscribeMessage('chat:message') handleMessage(client: Socket, payload: { text: string }) { return { event: 'chat:message', data: { clientId: client.id, text: payload.text, }, }; } } // WebSocketsController is created by Nest internally during application startup. // It discovers ChatGateway, attaches it to the Socket.IO server, subscribes to // lifecycle events, and routes "chat:message" events to handleMessage(). ``` ## AI Coding Instructions - Treat `WebSocketsController` as framework infrastructure; applications should define gateways and message handlers rather than instantiate this class directly. - Keep gateway event handlers compatible with the result pipeline: return values that can be converted into observable WebSocket responses when appropriate. - When adding lifecycle behavior, preserve the separate initialization, connection, and disconnect subscription paths. - Ensure new gateway entrypoint metadata can be discovered by `inspectEntrypointDefinitions()` and connected through `connectGatewayToServer()`. - Avoid subscribing message handlers more than once for the same gateway/server pair, as this can cause duplicated client responses. ## How it works ## Role `WebSocketsController` is the runtime coordinator that connects a gateway instance to a WebSocket server, discovers its message-mapped methods, creates their WebSocket execution contexts, registers lifecycle callbacks, and binds client connections and message handlers through the configured I/O adapter. [packages/websockets/web-sockets-controller.ts:29-43](packages/websockets/web-sockets-controller.ts#L29-L43) [packages/websockets/web-sockets-controller.ts:66-127](packages/websockets/web-sockets-controller.ts#L66-L127) `SocketModule` constructs this controller during WebSocket-module registration and calls `connectGatewayToServer()` only for provider metatypes carrying `GATEWAY_METADATA`. [packages/websockets/socket-module.ts:50-65](packages/websockets/socket-module.ts#L50-L65) [packages/websockets/socket-module.ts:77-94](packages/websockets/socket-module.ts#L77-L94) ## Gateway connection and validation - `connectGatewayToServer(instance, metatype, moduleKey, instanceWrapperId)` reads gateway options and port metadata from the gateway metatype; missing metadata becomes `{}` and `0`, respectively. [packages/websockets/web-sockets-controller.ts:45-53](packages/websockets/web-sockets-controller.ts#L45-L53) - The port must be an integer. A non-integer value throws `InvalidSocketPortException`, whose message is `Invalid port () in gateway `. [packages/websockets/web-sockets-controller.ts:54-56](packages/websockets/web-sockets-controller.ts#L54-L56) [packages/websockets/errors/invalid-socket-port.exception.ts:3-6](packages/websockets/errors/invalid-socket-port.exception.ts#L3-L6) - After validation, it delegates gateway setup to `subscribeToServerEvents()` with the resolved metadata, module key, and wrapper ID. [packages/websockets/web-sockets-controller.ts:57-63](packages/websockets/web-sockets-controller.ts#L57-L63) ## Message mappings and entrypoint inspection - `subscribeToServerEvents()` scans the gateway prototype for methods marked with `MESSAGE_MAPPING_METADATA`; for each, it records the message metadata, method name, callback, and whether parameter metadata contains an ACK parameter. [packages/websockets/web-sockets-controller.ts:73-86](packages/websockets/web-sockets-controller.ts#L73-L86) [packages/websockets/gateway-metadata-explorer.ts:26-57](packages/websockets/gateway-metadata-explorer.ts#L26-L57) [packages/websockets/gateway-metadata-explorer.ts:60-79](packages/websockets/gateway-metadata-explorer.ts#L60-L79) - Each discovered callback is replaced with a function created by `WsContextCreator` using the gateway instance, original callback, module key, and method name. [packages/websockets/web-sockets-controller.ts:74-85](packages/websockets/web-sockets-controller.ts#L74-L85) - The resulting wrapper builds a WebSocket context, obtains exception filters, pipes, guards, and interceptors, runs guards, applies pipes when parameter metadata exists, and invokes the original callback through an exception-handling proxy. A denied guard throws `WsException` with the guards package’s forbidden-message constant. [packages/websockets/context/ws-context-creator.ts:57-129](packages/websockets/context/ws-context-creator.ts#L57-L129) [packages/websockets/context/ws-context-creator.ts:143-162](packages/websockets/context/ws-context-creator.ts#L143-L162) - For every mapped method, `inspectEntrypointDefinitions()` inserts a graph entrypoint definition of type `websocket`, containing the method name, gateway constructor name, wrapper ID, port, and message as both `key` and `message`. [packages/websockets/web-sockets-controller.ts:88-93](packages/websockets/web-sockets-controller.ts#L88-L93) [packages/websockets/web-sockets-controller.ts:203-225](packages/websockets/web-sockets-controller.ts#L203-L225) ## Preview mode and server setup - Entrypoint inspection occurs before the preview-mode check. When `appOptions.preview` is truthy, setup returns without locating or creating a socket server, assigning server properties, or binding events. [packages/websockets/web-sockets-controller.ts:88-104](packages/websockets/web-sockets-controller.ts#L88-L104) - Outside preview mode, the controller asks `SocketServerProvider` for a server keyed by port and path, assigns that server to gateway instance properties marked with `GATEWAY_SERVER_METADATA`, then subscribes gateway events. [packages/websockets/web-sockets-controller.ts:98-104](packages/websockets/web-sockets-controller.ts#L98-L104) [packages/websockets/web-sockets-controller.ts:227-236](packages/websockets/web-sockets-controller.ts#L227-L236) - The server provider reuses a matching stored server when possible; otherwise it calls the configured adapter’s `create(port, partialOptions)`, stores the resulting server/event-stream host, and creates a namespace-specific host when gateway metadata has a namespace. [packages/websockets/socket-server-provider.ts:14-32](packages/websockets/socket-server-provider.ts#L14-L32) [packages/websockets/socket-server-provider.ts:34-55](packages/websockets/socket-server-provider.ts#L34-L55) ## Lifecycle events and client connections - `subscribeEvents()` subscribes optional gateway lifecycle methods—`afterInit`, `handleConnection`, and `handleDisconnect`—to the server host’s `init`, `connection`, and `disconnect` subjects, then registers a connection callback through `adapter.bindClientConnect(server, handler)`. [packages/websockets/web-sockets-controller.ts:106-127](packages/websockets/web-sockets-controller.ts#L106-L127) [packages/websockets/interfaces/nest-gateway.interface.ts:4-8](packages/websockets/interfaces/nest-gateway.interface.ts#L4-L8) - The server host’s factory immediately emits its server through `init`, and creates subjects for connection and disconnect events. [packages/websockets/factories/server-and-event-streams-factory.ts:4-17](packages/websockets/factories/server-and-event-streams-factory.ts#L4-L17) - Connection lifecycle handling suppresses consecutive connection notifications whose first arguments are the same reference before invoking `handleConnection(...args)`. [packages/websockets/web-sockets-controller.ts:154-162](packages/websockets/web-sockets-controller.ts#L154-L162) [packages/websockets/utils/compare-element.util.ts:1-7](packages/websockets/utils/compare-element.util.ts#L1-L7) - Disconnect lifecycle handling suppresses consecutive duplicate disconnect values before invoking `handleDisconnect`. [packages/websockets/web-sockets-controller.ts:164-170](packages/websockets/web-sockets-controller.ts#L164-L170) - When the adapter invokes the registered connection handler, it emits the complete connection argument list to the connection subject, binds message mappings for the first argument as the client, and, if the adapter implements `bindClientDisconnect`, emits that client to the disconnect subject when the adapter’s disconnect callback runs. [packages/websockets/web-sockets-controller.ts:129-146](packages/websockets/web-sockets-controller.ts#L129-L146) - After binding, it logs one line per mapped message in the form ` subscribed to the "" message`; it emits no such logs when the instance has no constructor name. [packages/websockets/web-sockets-controller.ts:238-251](packages/websockets/web-sockets-controller.ts#L238-L251) ## Message invocation and return values - For each connected client, `subscribeMessages()` binds every discovered handler through `adapter.bindMessageHandlers`; each callback is bound with the gateway as `this` and the client as its first argument. [packages/websockets/web-sockets-controller.ts:172-188](packages/websockets/web-sockets-controller.ts#L172-L188) - The transform passed to the adapter awaits the callback’s deferred result, leaves observables unchanged, converts promises to observables, and wraps all other values in a one-value observable; `mergeAll()` then flattens the resulting observable. [packages/websockets/web-sockets-controller.ts:185-201](packages/websockets/web-sockets-controller.ts#L185-L201) - The adapter contract requires client-connect binding and message-handler binding; client-disconnect binding is optional. [packages/common/interfaces/websockets/web-socket-adapter.interface.ts:15-29](packages/common/interfaces/websockets/web-socket-adapter.interface.ts#L15-L29) ## Relationships - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `Type` - IMPORTS → `Logger` - IMPORTS → `ApplicationConfig` - IMPORTS → `GraphInspector` - IMPORTS → `MetadataScanner` # WsContextCreator **Kind:** Class **Source:** [`packages/websockets/context/ws-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/context/ws-context-creator.ts#L40) **Part of:** [Websockets](subsystem-packages-websockets) `WsContextCreator` builds the executable wrapper for WebSocket gateway handlers. It resolves handler metadata, parameter values, guards, pipes, interceptors, and exception filters before delegating execution through the WebSocket proxy layer. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: Controller, callback: (...args: unknown[]) => void, moduleKey: string, methodName: string)` | `(...args: any[]) => Promise` | | `reflectCallbackParamtypes` | `reflectCallbackParamtypes(instance: Controller, callback: (...args: any[]) => any)` | `any[]` | | `reflectCallbackPattern` | `reflectCallbackPattern(callback: (...args: any[]) => any)` | `string` | | `createGuardsFn` | `createGuardsFn(guards: any[], instance: Controller, callback: (...args: unknown[]) => any, contextType: TContext)` | `Function | null` | | `getMetadata` | `getMetadata(instance: Controller, methodName: string, contextType: TContext)` | `WsHandlerMetadata` | | `exchangeKeysForValues` | `exchangeKeysForValues(keys: string[], metadata: TMetadata, moduleContext: string, paramsFactory: WsParamsFactory, contextFactory: (args: unknown[]) => ExecutionContextHost)` | `ParamProperties[]` | | `createPipesFn` | `createPipesFn(pipes: PipeTransform[], paramsOptions: (ParamProperties & { metatype?: unknown })[])` | `void` | | `getParamValue` | `getParamValue(value: T, { metatype, type, data }: { metatype: any; type: any; data: any }, pipes: PipeTransform[])` | `Promise` | ## Where it refuses work - `WsContextCreator` stops the work with `WsException` when `!canActivate`. - `WsContextCreator` stops the work with an early return when `cacheMetadata`. ## Diagram ```mermaid graph LR A[Incoming WebSocket event] --> B[WsContextCreator.create] B --> C[Reflect handler metadata and pattern] C --> D[Create guards] C --> E[Create pipes] C --> F[Create interceptors] C --> G[Create exception filter handler] D --> H[Validate execution] E --> I[Transform handler parameters] F --> J[Invoke gateway callback] G --> K[Handle WebSocket exceptions] H --> I I --> F J --> K ``` ## Usage ```ts import { WsContextCreator } from '@nestjs/websockets'; class ChatGateway { async handleMessage(client: unknown, payload: { text: string }) { console.log(`Received: ${payload.text}`); } } // WsContextCreator is typically created and injected by Nest's WebSocket // runtime rather than instantiated directly. class GatewayHandlerBinder { constructor(private readonly wsContextCreator: WsContextCreator) {} bind(gateway: ChatGateway, server: { on(event: string, handler: Function): void }) { const handler = this.wsContextCreator.create( gateway, gateway.handleMessage, 'ChatModule', 'handleMessage', ); server.on('message', handler); } } ``` ## AI Coding Instructions - Treat `WsContextCreator` as framework infrastructure; prefer gateway decorators and Nest module configuration over manually constructing it. - Preserve the handler creation flow: metadata reflection, guards, pipes, interceptors, and exception filters must all be included in wrapped handlers. - Ensure parameter metadata matches the gateway callback signature, since `getParamValue()` and pipe execution depend on reflected parameter configuration. - Do not invoke gateway callbacks directly when framework behavior is required; use the function returned by `create()` so guards, pipes, and exception handling run. - Keep WebSocket message patterns stable, as `reflectCallbackPattern()` is used to associate handlers with incoming events. ## How it works ## `WsContextCreator` `WsContextCreator` builds the executable wrapper for a WebSocket gateway callback. Its constructor receives the WebSocket proxy plus contexts/consumers for exception filters, pipes, guards, and interceptors; it also creates its own context utility, WebSocket parameter factory, and per-handler metadata cache. [packages/websockets/context/ws-context-creator.ts:40-55] # AbstractWsAdapter **Kind:** Class **Source:** [`packages/websockets/adapters/ws-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/adapters/ws-adapter.ts#L13) **Part of:** [Websockets](subsystem-packages-websockets) `AbstractWsAdapter` is the base class for WebSocket transport adapters in NestJS. It provides shared lifecycle behavior for client connection/disconnection events and server cleanup, while concrete adapters implement server creation and message-handler binding for a specific WebSocket library. **Implements:** `WebSocketAdapter` ## Methods | Method | Signature | Returns | |---|---|---| | `bindClientConnect` | `bindClientConnect(server: TServer, callback: Function)` | `void` | | `bindClientDisconnect` | `bindClientDisconnect(client: TClient, callback: Function)` | `void` | | `close` | `close(server: TServer)` | `void` | | `dispose` | `dispose()` | `void` | | `create` | `create(port: number, options: TOptions)` | `TServer` | | `bindMessageHandlers` | `bindMessageHandlers(client: TClient, handlers: WsMessageHandler[], transform: (data: any) => Observable)` | `void` | ## Properties | Property | Type | |---|---| | `httpServer` | `any` | ## Diagram ```mermaid graph LR App[Nest Application] --> Adapter[AbstractWsAdapter] Adapter --> Create[create()] Adapter --> Connect[bindClientConnect()] Adapter --> Disconnect[bindClientDisconnect()] Adapter --> Messages[bindMessageHandlers()] Adapter --> Close[close() / dispose()] Create --> Server[WebSocket Server] Server --> Client[WebSocket Client] Client --> Messages ``` ## Usage ```ts import { AbstractWsAdapter } from '@nestjs/websockets'; class CustomWsAdapter extends AbstractWsAdapter { create(port: number): MyServer { return createMyWebSocketServer(port); } bindMessageHandlers(client: MyClient, handlers, transform) { client.on('message', async rawMessage => { const message = JSON.parse(rawMessage.toString()); for (const handler of handlers) { if (handler.message === message.event) { const response = await transform( handler.callback(message.data, client), ); client.send(JSON.stringify(response)); } } }); } } // main.ts async function bootstrap() { const app = await NestFactory.create(AppModule); app.useWebSocketAdapter(new CustomWsAdapter(app)); await app.listen(3000); } ``` ## AI Coding Instructions - Extend `AbstractWsAdapter` rather than instantiating it directly; implement `create()` and `bindMessageHandlers()` for the chosen WebSocket library. - Use `bindClientConnect()` and `bindClientDisconnect()` to attach lifecycle callbacks instead of duplicating connection event wiring. - Ensure incoming messages are parsed and routed to the matching Nest gateway handler in `bindMessageHandlers()`. - Always support adapter cleanup through `close()` and `dispose()`, especially when the underlying server keeps open client connections. - Register the concrete adapter with `app.useWebSocketAdapter()` during application bootstrap. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `IoAdapter` — `packages/platform-socket.io/adapters/io-adapter.ts`:14 - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 # SocketModule **Kind:** Class **Source:** [`packages/websockets/socket-module.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/socket-module.ts#L27) **Part of:** [Websockets](subsystem-packages-websockets) `SocketModule` coordinates WebSocket gateway registration and connection lifecycle management. It registers available gateways, connects them to the server, and provides a unified `close()` method for shutting down active socket resources. ## Methods | Method | Signature | Returns | |---|---|---| | `register` | `register(container: NestContainer, applicationConfig: ApplicationConfig, graphInspector: GraphInspector, appOptions: TAppOptions, httpServer: THttpServer)` | `void` | | `connectAllGateways` | `connectAllGateways(providers: Map>, moduleName: string)` | `void` | | `connectGatewayToServer` | `connectGatewayToServer(wrapper: InstanceWrapper, moduleName: string)` | `void` | | `close` | `close()` | `Promise` | ## Where it refuses work - `SocketModule` stops the work with an early return when `!metadataKeys.includes(GATEWAY_METADATA)`. - `SocketModule` stops the work with an early return when `!this.applicationConfig`. - `SocketModule` stops the work with an early return when `!adapter`. ## Diagram ```mermaid graph LR App[Application Bootstrap] --> Module[SocketModule] Module --> Register[register()] Register --> Gateways[WebSocket Gateways] Module --> ConnectAll[connectAllGateways()] ConnectAll --> ConnectGateway[connectGatewayToServer()] ConnectGateway --> Server[WebSocket Server] Module --> Close[close()] Close --> Gateways ``` ## Usage ```ts import { SocketModule } from './packages/websockets/socket-module'; // Create the module using the dependencies required by your application. const socketModule = new SocketModule(/* gateway and server dependencies */); // Register configured gateways and establish their server connections. socketModule.register(); socketModule.connectAllGateways(); // During application shutdown, close socket connections cleanly. async function shutdown() { await socketModule.close(); } ``` ## AI Coding Instructions - Call `register()` before attempting to connect gateways so gateway definitions and handlers are available. - Use `connectAllGateways()` for standard application startup; use `connectGatewayToServer()` when connecting an individual gateway as part of custom orchestration. - Always await `close()` during shutdown to release WebSocket connections and related resources cleanly. - Keep gateway-specific behavior inside gateway implementations; `SocketModule` should remain responsible for registration and connection lifecycle coordination. - Ensure server dependencies are initialized before invoking gateway connection methods. ## How it works `SocketModule` is the WebSocket gateway lifecycle coordinator. It scans Nest container providers for classes marked with the `websockets:is_gateway` metadata key, initializes a WebSocket adapter when it finds the first such gateway, and delegates gateway attachment to `WebSocketsController`. [packages/websockets/socket-module.ts:68-95](packages/websockets/socket-module.ts#L68-L95) The `@WebSocketGateway()` decorator writes that marker together with gateway port and options metadata. [packages/websockets/decorators/socket-gateway.decorator.ts:20-29](packages/websockets/decorators/socket-gateway.decorator.ts#L20-L29) - `register(container, applicationConfig, graphInspector, appOptions, httpServer?)` stores the application configuration, application options, and optional HTTP server; creates a WebSocket execution-context creator; creates `SocketServerProvider` and `WebSocketsController` instances; then visits the providers in every container module. [packages/websockets/socket-module.ts:39-66](packages/websockets/socket-module.ts#L39-L66) - During that scan, it ignores missing wrappers and wrappers flagged as `isNotMetatype`; every remaining wrapper is checked for the gateway metadata key on its metatype. Non-gateway providers are skipped. [packages/websockets/socket-module.ts:68-85](packages/websockets/socket-module.ts#L68-L85) - The first detected gateway initializes the adapter. If `ApplicationConfig` already has an IO adapter, the module sets that adapter’s `forceCloseConnections` property from application options. Otherwise, it dynamically loads `@nestjs/platform-socket.io`, constructs its `IoAdapter` with the optional HTTP server, sets the same property, and saves the adapter in `ApplicationConfig`. [packages/websockets/socket-module.ts:116-136](packages/websockets/socket-module.ts#L116-L136) If the default adapter package cannot be loaded, `loadAdapter` logs an error and calls `process.exit(1)`. [packages/core/helpers/load-adapter.ts:11-21](packages/core/helpers/load-adapter.ts#L11-L21) - For each marked gateway, it calls `WebSocketsController.connectGatewayToServer()` with the gateway instance, its class, module name, and wrapper ID. [packages/websockets/socket-module.ts:86-95](packages/websockets/socket-module.ts#L86-L95) That controller reads the gateway’s port and options metadata and throws `InvalidSocketPortException` when the port is not an integer. [packages/websockets/web-sockets-controller.ts:45-64](packages/websockets/web-sockets-controller.ts#L45-L64) - The context creator assembled by the module includes WebSocket exception filters, pipes, guards, and interceptors. [packages/websockets/socket-module.ts:138-149](packages/websockets/socket-module.ts#L138-L149) The controller wraps discovered message handlers through that context creator, records WebSocket entrypoint definitions in the graph inspector, and, unless preview mode is enabled, creates or finds a socket server, assigns it to server-decorated gateway properties, and subscribes handlers. [packages/websockets/web-sockets-controller.ts:73-104](packages/websockets/web-sockets-controller.ts#L73-L104) - Server instances are tracked by socket configuration. The server provider reuses an existing host with the same port and path, creates a new adapter server when none exists, and creates separately tracked namespace hosts when a namespace is configured. [packages/websockets/socket-server-provider.ts:14-32](packages/websockets/socket-server-provider.ts#L14-L32) [packages/websockets/socket-server-provider.ts:34-73](packages/websockets/socket-server-provider.ts#L34-L73) - `close()` is a no-op when registration has not set `applicationConfig`, or when that configuration has no adapter. Otherwise, it calls `adapter.close(server)` concurrently for every tracked host whose `server` value is truthy, awaits `adapter.dispose()`, and clears the tracked hosts. [packages/websockets/socket-module.ts:97-114](packages/websockets/socket-module.ts#L97-L114) - Nest applications invoke `register()` while registering modules, passing the container, application config, graph inspector, app options, and HTTP server. [packages/core/nest-application.ts:140-161](packages/core/nest-application.ts#L140-L161) [packages/core/nest-application.ts:164-176](packages/core/nest-application.ts#L164-L176) Application disposal awaits `SocketModule.close()` before closing the HTTP adapter. [packages/core/nest-application.ts:98-101](packages/core/nest-application.ts#L98-L101) ## Relationships - IMPORTS → `NestApplicationOptions` - IMPORTS → `InjectionToken` - IMPORTS → `Injectable` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `ApplicationConfig` - IMPORTS → `GuardsConsumer` - IMPORTS → `GuardsContextCreator` - IMPORTS → `loadAdapter` - IMPORTS → `NestContainer` - IMPORTS → `InstanceWrapper` - IMPORTS → `GraphInspector` - IMPORTS → `InterceptorsConsumer` - IMPORTS → `InterceptorsContextCreator` - IMPORTS → `PipesConsumer` - IMPORTS → `PipesContextCreator` - IMPORTS → `-nestjs-platform-socket-io` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `NestApplication` — `packages/core/nest-application.ts`:54 - `NestMicroservice` — `packages/microservices/nest-microservice.ts`:35 # BaseWsExceptionFilter **Kind:** Class **Source:** [`packages/websockets/exceptions/base-ws-exception-filter.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/exceptions/base-ws-exception-filter.ts#L46) **Part of:** [Websockets](subsystem-packages-websockets) `BaseWsExceptionFilter` is the default foundation for handling exceptions thrown during WebSocket message processing. It distinguishes `WsException` instances from unknown errors, emits structured error payloads to the connected client, and provides safe fallback handling for unexpected failures. **Implements:** `WsExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: TError, host: ArgumentsHost)` | `void` | | `handleError` | `handleError(client: TClient, exception: TError, cause: ErrorPayload['cause'])` | `void` | | `handleUnknownError` | `handleUnknownError(exception: TError, client: TClient, data: ErrorPayload['cause'])` | `void` | | `isExceptionObject` | `isExceptionObject(err: any)` | `err is Error` | ## Properties | Property | Type | |---|---| | `logger` | `any` | ## Where it refuses work - `BaseWsExceptionFilter` stops the work with an early return when `!(exception instanceof WsException)`. - `BaseWsExceptionFilter` stops the work with an early return when `isObject(result)`. ## Diagram ```mermaid graph LR A[WebSocket handler throws error] --> B[BaseWsExceptionFilter.catch] B --> C{Is WsException?} C -->|Yes| D[handleError] C -->|No| E[handleUnknownError] D --> F[Emit exception event to client] E --> G[Create generic error payload] G --> F ``` ## Usage ```ts import { Catch, WsException } from '@nestjs/common'; import { BaseWsExceptionFilter } from '@nestjs/websockets'; import type { ArgumentsHost } from '@nestjs/common'; @Catch() export class GatewayExceptionFilter extends BaseWsExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { // Add application-specific logging or monitoring here. console.error('WebSocket exception:', exception); // Delegate standard client error handling to the base filter. super.catch(exception, host); } } // In a gateway: import { UseFilters, SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; @WebSocketGateway() @UseFilters(new GatewayExceptionFilter()) export class EventsGateway { @SubscribeMessage('create-event') createEvent() { throw new WsException({ code: 'EVENT_CREATION_FAILED', message: 'Unable to create the event.', }); } } ``` ## AI Coding Instructions - Extend `BaseWsExceptionFilter` when custom logging, metrics, or error transformation is needed; call `super.catch()` to preserve standard WebSocket error delivery. - Throw `WsException` for expected client-facing failures so `handleError()` can emit the intended error payload. - Do not expose stack traces, database details, or internal exception messages through unknown-error responses. - Ensure filters are registered with `@UseFilters()` on the gateway, controller, or individual message handler as appropriate. - Remember that errors are emitted to the WebSocket client through the `exception` event rather than returned as HTTP responses. # WsException **Kind:** Class **Source:** [`packages/websockets/errors/ws-exception.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/errors/ws-exception.ts#L3) **Part of:** [Websockets](subsystem-packages-websockets) `WsException` represents an error that should be sent through the WebSocket error-handling flow. It accepts either a string or object payload, initializes a message for standard error reporting, and preserves the original error value for consumers that need structured details. **Extends:** `Error` ## Methods | Method | Signature | Returns | |---|---|---| | `initMessage` | `initMessage()` | `void` | | `getError` | `getError()` | `string | object` | ## Diagram ```mermaid graph LR A[WebSocket handler] --> B[new WsException(error)] B --> C[initMessage()] C --> D[Exception message] B --> E[getError()] E --> F[String or structured error payload] F --> G[WebSocket exception filter/client response] ``` ## Usage ```ts import { WsException } from '@nestjs/websockets'; function handleSubscribe(topic?: string) { if (!topic) { throw new WsException({ status: 'error', code: 'TOPIC_REQUIRED', message: 'A subscription topic is required.', }); } return { status: 'ok', topic }; } // The original payload remains available when handling the exception. const exception = new WsException('Subscription failed'); console.log(exception.message); // "Subscription failed" console.log(exception.getError()); // "Subscription failed" ``` ## AI Coding Instructions - Throw `WsException` from WebSocket handlers when an error should be delivered through the WebSocket exception pipeline. - Pass a string for simple client-facing errors; pass an object when clients need structured fields such as `code`, `status`, or validation details. - Use `getError()` when writing exception filters or adapters that must access the original error payload. - Do not assume `getError()` always returns a string; handle both string and object values safely. - Keep error payloads serializable and avoid including internal stack traces or sensitive server details. ## How it works ## `WsException` `WsException` is an `Error` subclass that carries a WebSocket error value as either a `string` or an `object`. Its constructor stores that value in a private, readonly `error` field, calls `Error`’s no-argument constructor, and initializes the inherited `message` property. [packages/websockets/errors/ws-exception.ts:3-7] ## Relationships - IMPORTS → `isObject` - IMPORTS → `isString` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `ApplicationGateway` — `integration/websockets/src/app.gateway.ts`:12 - `ErrorGateway` — `integration/websockets/src/error.gateway.ts`:8 - `RequestFilter` — `integration/websockets/src/request.filter.ts`:4 # GatewayMetadataExplorer **Kind:** Class **Source:** [`packages/websockets/gateway-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/gateway-metadata-explorer.ts#L22) **Part of:** [Websockets](subsystem-packages-websockets) `GatewayMetadataExplorer` discovers WebSocket gateway methods decorated as message handlers or lifecycle hooks. It uses Nest’s metadata scanning utilities to convert gateway method metadata into `MessageMappingProperties` entries that the WebSocket runtime can register and invoke. ## Methods | Method | Signature | Returns | |---|---|---| | `explore` | `explore(instance: NestGateway)` | `MessageMappingProperties[]` | | `exploreMethodMetadata` | `exploreMethodMetadata(instancePrototype: object, methodName: string)` | `MessageMappingProperties | null` | | `scanForServerHooks` | `scanForServerHooks(instance: NestGateway)` | `IterableIterator` | ## Where it refuses work - `GatewayMetadataExplorer` stops the work with an early return when `isUndefined(isMessageMapping)`. - `GatewayMetadataExplorer` stops the work with an early return when `!paramsMetadata`. ## Diagram ```mermaid graph LR Gateway[Gateway instance] --> Explorer[GatewayMetadataExplorer] Explorer --> Scanner[MetadataScanner] Scanner --> Methods[Gateway prototype methods] Methods --> Accessor[MetadataAccessor] Accessor --> Mappings[MessageMappingProperties] Accessor --> Hooks[Gateway lifecycle hook names] ``` ## Usage ```ts import { GatewayMetadataExplorer } from '@nestjs/websockets'; const explorer = app.get(GatewayMetadataExplorer); const gatewayInstance = app.get(EventsGateway); // Discover methods decorated with @SubscribeMessage() const messageMappings = explorer.explore(gatewayInstance); for (const mapping of messageMappings) { console.log(`Message "${mapping.message}" handled by ${mapping.methodName}`); } // Discover lifecycle methods such as handleConnection or handleDisconnect for (const hookName of explorer.scanForServerHooks(gatewayInstance)) { console.log(`Gateway hook found: ${hookName}`); } ``` ## AI Coding Instructions - Use `explore()` to discover `@SubscribeMessage()` handlers; do not manually inspect gateway methods when metadata-based discovery is available. - Keep message handler decorators on prototype methods, since metadata scanning operates on the gateway prototype. - Treat `exploreMethodMetadata()` returning `null` as an expected result for methods without message-mapping metadata. - Use `scanForServerHooks()` when integrating gateway lifecycle methods such as connection, disconnect, and initialization hooks. - Prefer resolving this class through Nest dependency injection rather than constructing it manually, because it depends on `MetadataScanner` and `MetadataAccessor`. # SocketsContainer **Kind:** Class **Source:** [`packages/websockets/sockets-container.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/sockets-container.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) `SocketsContainer` manages the collection of `ServerAndEventStreamsHost` instances used by the WebSocket layer. It provides lookup, registration, enumeration, and cleanup operations so socket server hosts can be reused and managed consistently during application lifecycle events. ## Methods | Method | Signature | Returns | |---|---|---| | `getAll` | `getAll()` | `Map` | | `getOneByConfig` | `getOneByConfig(options: T)` | `ServerAndEventStreamsHost` | | `addOne` | `addOne(options: T, host: ServerAndEventStreamsHost)` | `void` | | `clear` | `clear()` | `void` | ## Diagram ```mermaid graph LR A[WebSocket Configuration] --> B[SocketsContainer] B -->|addOne| C[ServerAndEventStreamsHost] B -->|getOneByConfig| C B -->|getAll| D[Map of Socket Hosts] B -->|clear| E[Release Registered Hosts] ``` ## Usage ```ts import { SocketsContainer } from './sockets-container'; import { ServerAndEventStreamsHost } from './server-and-event-streams-host'; const socketsContainer = new SocketsContainer(); // Create or obtain a configured host from the WebSocket bootstrap flow. const host = new ServerAndEventStreamsHost(/* websocket adapter */); // Register the host using the socket server configuration. socketsContainer.addOne( { port: 3000, path: '/socket.io' }, host, ); // Reuse the registered host when processing the same configuration. const registeredHost = socketsContainer.getOneByConfig({ port: 3000, path: '/socket.io', }); // Inspect all active socket hosts. console.log(socketsContainer.getAll()); // Clear registrations during application shutdown or test cleanup. socketsContainer.clear(); ``` ## AI Coding Instructions - Register hosts through `addOne()` rather than mutating the map returned by `getAll()`. - Use the same socket configuration values when calling `addOne()` and `getOneByConfig()` so host reuse works correctly. - Treat `SocketsContainer` as application infrastructure; create and populate it during WebSocket server bootstrap. - Call `clear()` during teardown to prevent socket host state from leaking between application instances or tests. ## How it works ## `SocketsContainer` `SocketsContainer` is an in-memory collection of `ServerAndEventStreamsHost` objects, indexed by a hash derived from gateway configuration objects. Its backing collection is a `Map`, although its internal key-generation method returns a `string`. [packages/websockets/sockets-container.ts:4-8] [packages/websockets/sockets-container.ts:33-37] A stored host has a `server` plus `init`, `connection`, and `disconnect` RxJS subjects. [packages/websockets/interfaces/server-and-event-streams-host.interface.ts:6-11] # WsExceptionsHandler **Kind:** Class **Source:** [`packages/websockets/exceptions/ws-exceptions-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/exceptions/ws-exceptions-handler.ts#L12) **Part of:** [Websockets](subsystem-packages-websockets) `WsExceptionsHandler` is the WebSocket transport exception dispatcher in NestJS. It selects and invokes matching custom exception filters first, then falls back to the base WebSocket exception filter to serialize and emit an error response to the connected client. **Extends:** `BaseWsExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `handle` | `handle(exception: Error | WsException, host: ArgumentsHost)` | `void` | | `setCustomFilters` | `setCustomFilters(filters: ExceptionFilterMetadata[])` | `void` | | `invokeCustomFilters` | `invokeCustomFilters(exception: T, args: ArgumentsHost)` | `boolean` | ## Where it refuses work - `WsExceptionsHandler` stops the work with `InvalidExceptionFilterException` when `!Array.isArray(filters)`. - `WsExceptionsHandler` stops the work with an early return when `this.invokeCustomFilters(exception, host) || !client.emit`. - `WsExceptionsHandler` stops the work with an early return when `isEmpty(this.filters)`. ## Diagram ```mermaid graph LR A[WebSocket handler throws exception] --> B[WsExceptionsHandler.handle] B --> C{Matching custom filter?} C -->|Yes| D[invokeCustomFilters] D --> E[Custom filter catch method] C -->|No| F[BaseWsExceptionFilter.catch] F --> G[Emit error to WebSocket client] ``` ## Usage ```ts import { ArgumentsHost, Catch } from '@nestjs/common'; import { WsException } from '@nestjs/websockets'; import { WsExceptionsHandler } from '@nestjs/websockets/exceptions/ws-exceptions-handler'; @Catch(WsException) class WsErrorFilter { catch(exception: WsException, host: ArgumentsHost) { const client = host.switchToWs().getClient(); client.emit('error', { message: exception.getError(), source: 'custom-ws-filter', }); } } // This is typically configured internally by NestJS. const exceptionsHandler = new WsExceptionsHandler(); const filter = new WsErrorFilter(); exceptionsHandler.setCustomFilters([ { exceptionMetatypes: [WsException], func: filter.catch.bind(filter), }, ]); // `host` is the ArgumentsHost created by NestJS for an incoming WS event. exceptionsHandler.handle(new WsException('Invalid payload'), host); ``` ## AI Coding Instructions - Register custom WebSocket filters before calling `handle()`; matching filters take precedence over the default error behavior. - Bind filter methods with `filter.catch.bind(filter)` when creating filter metadata so class instance state remains available. - Return control after a custom filter handles an exception; otherwise the base filter may emit a duplicate error response. - Use `WsException` for expected client-facing WebSocket failures and reserve unexpected `Error` instances for server-side faults. - Prefer NestJS gateway-level filter registration (such as `@UseFilters()`) over manually constructing this internal handler in application code. ## How it works ## `WsExceptionsHandler` `WsExceptionsHandler` is a public WebSocket exception handler that extends `BaseWsExceptionFilter`. It keeps an initially empty list of custom exception-filter metadata and handles an exception either through a matching custom filter or through the base WebSocket error-emission path. [ws-exceptions-handler.ts:12-13](packages/websockets/exceptions/ws-exceptions-handler.ts#L12-L13) ## Relationships - IMPORTS → `ArgumentsHost` - IMPORTS → `ExceptionFilterMetadata` - IMPORTS → `selectExceptionFilterMetadata` - IMPORTS → `isEmpty` - IMPORTS → `InvalidExceptionFilterException` # ExceptionFiltersContext **Kind:** Class **Source:** [`packages/websockets/context/exception-filters-context.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/context/exception-filters-context.ts#L10) **Part of:** [Websockets](subsystem-packages-websockets) `ExceptionFiltersContext` builds and resolves WebSocket exception filters for gateway handlers. It combines method-level and global filter metadata into a `WsExceptionsHandler`, allowing WebSocket errors to be processed consistently through Nest’s exception-filter pipeline. **Extends:** `BaseExceptionFilterContext` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(instance: object, callback: (client: TClient, data: any) => any, moduleKey: string)` | `WsExceptionsHandler` | | `getGlobalMetadata` | `getGlobalMetadata()` | `T` | ## Where it refuses work - `ExceptionFiltersContext` stops the work with an early return when `isEmpty(filters)`. ## Diagram ```mermaid graph LR Gateway[WebSocket Gateway Handler] --> Context[ExceptionFiltersContext] Context --> Metadata[Exception Filter Metadata] Context --> GlobalFilters[Global / Request-Scoped Filters] Metadata --> Handler[WsExceptionsHandler] GlobalFilters --> Handler Handler --> Client[WebSocket Client Error Response] ``` ## Usage ```ts import { ExceptionFiltersContext } from '@nestjs/websockets'; import { NestContainer } from '@nestjs/core'; import { ApplicationConfig } from '@nestjs/core'; const container = new NestContainer(); const applicationConfig = new ApplicationConfig(); const exceptionFiltersContext = new ExceptionFiltersContext( container, applicationConfig, ); const wsExceptionsHandler = exceptionFiltersContext.create( gatewayInstance, gatewayInstance.handleMessage, 'ChatGatewayModule', ); // Use the resolved handler when invoking a WebSocket gateway method. wsExceptionsHandler.handle( new Error('Unable to process message'), host, ); ``` ## AI Coding Instructions - Use `create()` when preparing a WebSocket gateway callback so method- and class-level exception filters are resolved before execution. - Preserve filter ordering: custom filters are applied in reverse order to match Nest’s exception-filter execution behavior. - Use `getGlobalMetadata()` when extending filter resolution logic; it includes configured global filters and request-scoped filters when applicable. - Avoid bypassing `WsExceptionsHandler` for gateway errors, as doing so can skip custom filters and inconsistent client error serialization. ## How it works ## `ExceptionFiltersContext` `ExceptionFiltersContext` is a public WebSocket exception-filter context builder. It extends `BaseExceptionFilterContext` and is constructed with a `NestContainer`, which the inherited implementation uses to resolve class-based filters from a module’s injectable collection. [`packages/websockets/context/exception-filters-context.ts:10-13`](packages/websockets/context/exception-filters-context.ts#L10-L13) [`packages/core/exceptions/base-exception-filter-context.ts:14-16`](packages/core/exceptions/base-exception-filter-context.ts#L14-L16) [`packages/core/exceptions/base-exception-filter-context.ts:59-71`](packages/core/exceptions/base-exception-filter-context.ts#L59-L71) ## Relationships - IMPORTS → `EXCEPTION_FILTERS_METADATA` - IMPORTS → `isEmpty` - IMPORTS → `BaseExceptionFilterContext` - IMPORTS → `NestContainer` # SocketServerProvider **Kind:** Class **Source:** [`packages/websockets/socket-server-provider.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/socket-server-provider.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) `SocketServerProvider` discovers the application server and its associated event streams so WebSocket gateways can attach to the correct underlying transport. It acts as an integration layer between the WebSocket module and the HTTP application host, exposing `scanForSocketServer()` for resolving the active server context. ## Methods | Method | Signature | Returns | |---|---|---| | `scanForSocketServer` | `scanForSocketServer(options: T, port: number)` | `ServerAndEventStreamsHost` | ## Where it refuses work - `SocketServerProvider` stops the work with an early return when `serverAndStreamsHost && options.namespace`. - `SocketServerProvider` stops the work with an early return when `!namespace`. - `SocketServerProvider` stops the work with an early return when `!isString(namespace)`. ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[SocketServerProvider] B --> C[scanForSocketServer()] C --> D[ServerAndEventStreamsHost] D --> E[HTTP Server] D --> F[Event Streams] E --> G[WebSocket Gateway / Adapter] ``` ## Usage ```ts import { SocketServerProvider } from '@nestjs/websockets'; class WebSocketBootstrapService { constructor( private readonly socketServerProvider: SocketServerProvider, ) {} resolveServer() { const serverHost = this.socketServerProvider.scanForSocketServer(); // Use the resolved host when configuring a WebSocket adapter // or attaching gateway infrastructure. return serverHost; } } ``` ## AI Coding Instructions - Treat `SocketServerProvider` as framework infrastructure; obtain it through dependency injection instead of instantiating it manually. - Call `scanForSocketServer()` only after the application server has been initialized and registered in the module/container context. - Preserve the `ServerAndEventStreamsHost` return type when passing the resolved server context to WebSocket-related integrations. - Avoid assuming a specific HTTP implementation; the provider should remain compatible with the configured platform adapter and server host. - When modifying discovery behavior, ensure both the HTTP server and event-stream capabilities remain available to WebSocket consumers. ## How it works ## `SocketServerProvider` `SocketServerProvider` is a class that obtains or creates WebSocket server hosts for gateway metadata and a port. It receives a `SocketsContainer` and an `ApplicationConfig` in its constructor. [packages/websockets/socket-server-provider.ts:8-12] ## Relationships - IMPORTS → `addLeadingSlash` - IMPORTS → `isString` - IMPORTS → `ApplicationConfig` # WsProxy **Kind:** Class **Source:** [`packages/websockets/context/ws-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/context/ws-proxy.ts#L6) **Part of:** [Websockets](subsystem-packages-websockets) `WsProxy` creates an asynchronous proxy function for WebSocket-backed operations. It centralizes request forwarding and error handling so callers can invoke WebSocket actions through a Promise-based interface. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(targetCallback: (...args: unknown[]) => Promise, exceptionsHandler: WsExceptionsHandler, targetPattern: string)` | `(...args: unknown[]) => Promise` | | `handleError` | `handleError(exceptionsHandler: WsExceptionsHandler, args: unknown[], error: T)` | `void` | ## When something fails - `WsProxy` handles failure in 1 place: it logs it and continues in all 1. ## Diagram ```mermaid graph LR Client[Application Code] --> Proxy[WsProxy] Proxy --> Create[create()] Create --> Handler[Async Proxy Function] Handler --> Socket[WebSocket Context] Socket --> Response[Promise Result] Socket --> Error[handleError()] Error --> Client ``` ## Usage ```ts import { WsProxy } from '@your-package/websockets'; // Construct the proxy with the WebSocket context/configuration required // by your application. const wsProxy = new WsProxy(/* websocket context */); // Create the async function used to invoke WebSocket-backed operations. const invoke = wsProxy.create(); try { const result = await invoke('users.get', { id: 'user-123' }); console.log('WebSocket response:', result); } catch (error) { console.error('WebSocket request failed:', error); } ``` ## AI Coding Instructions - Use `create()` once per configured proxy instance and retain the returned async function for WebSocket calls. - Treat calls through the created proxy as asynchronous and always `await` them or return their Promise. - Route transport and remote-operation failures through `handleError()` rather than duplicating WebSocket error normalization in callers. - Ensure the WebSocket context is initialized and connected before invoking the function returned by `create()`. - Preserve the proxy’s argument forwarding behavior when extending it; proxy calls may accept arbitrary argument lists. ## Relationships - IMPORTS → `ExecutionContextHost` # compareElementAt **Kind:** Function **Source:** [`packages/websockets/utils/compare-element.util.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/utils/compare-element.util.ts#L1) **Part of:** [Websockets](subsystem-packages-websockets) ## Signature ```ts function compareElementAt(prev: unknown[], curr: unknown[], index: number) ``` ## Parameters | Name | Type | |---|---| | `prev` | `unknown[]` | | `curr` | `unknown[]` | | `index` | `number` | # WebSocketGateway **Kind:** Function **Source:** [`packages/websockets/decorators/socket-gateway.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/socket-gateway.decorator.ts#L17) **Part of:** [Websockets](subsystem-packages-websockets) `WebSocketGateway()` marks a class as a NestJS WebSocket gateway, allowing it to receive and emit real-time, event-based messages. Nest reads the decorator metadata during application startup, creates the configured WebSocket server adapter, and routes matching client events to gateway handlers. ## Signature ```ts function WebSocketGateway(portOrOptions: number | T, options: T): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `portOrOptions` | `number | T` | | `options` | `T` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Client[Browser / WebSocket Client] --> Server[WebSocket Server Adapter] Server --> Gateway[@WebSocketGateway() Class] Gateway --> Handler[@SubscribeMessage() Handler] Handler --> Gateway Gateway --> Client ``` ## Usage ```ts import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway({ cors: { origin: 'http://localhost:3000', }, }) export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('chat:message') handleMessage( @MessageBody() message: { text: string }, @ConnectedSocket() client: Socket, ) { this.server.emit('chat:message', { senderId: client.id, text: message.text, }); } } ``` ## AI Coding Instructions - Apply `@WebSocketGateway()` only to provider classes registered in a Nest module. - Use `@SubscribeMessage('event-name')` methods to handle incoming client events. - Configure gateway options, such as `cors`, `namespace`, or `transports`, in the decorator when required by the client integration. - Use `@WebSocketServer()` to emit messages to connected clients instead of creating a server instance manually. - Validate incoming payloads with DTOs and pipes before broadcasting or processing client-provided data. # WebSocketGateway **Kind:** Function **Source:** [`packages/websockets/decorators/socket-gateway.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/socket-gateway.decorator.ts#L17) **Part of:** [Websockets](subsystem-packages-websockets) `WebSocketGateway()` marks a class as a NestJS WebSocket gateway, allowing it to receive and emit real-time, event-based messages. Nest reads the decorator metadata during application startup, creates the configured WebSocket server adapter, and routes matching client events to gateway handlers. ## Signature ```ts function WebSocketGateway(portOrOptions: number | T, options: T): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `portOrOptions` | `number | T` | | `options` | `T` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Client[Browser / WebSocket Client] --> Server[WebSocket Server Adapter] Server --> Gateway[@WebSocketGateway() Class] Gateway --> Handler[@SubscribeMessage() Handler] Handler --> Gateway Gateway --> Client ``` ## Usage ```ts import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway({ cors: { origin: 'http://localhost:3000', }, }) export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('chat:message') handleMessage( @MessageBody() message: { text: string }, @ConnectedSocket() client: Socket, ) { this.server.emit('chat:message', { senderId: client.id, text: message.text, }); } } ``` ## AI Coding Instructions - Apply `@WebSocketGateway()` only to provider classes registered in a Nest module. - Use `@SubscribeMessage('event-name')` methods to handle incoming client events. - Configure gateway options, such as `cors`, `namespace`, or `transports`, in the decorator when required by the client integration. - Use `@WebSocketServer()` to emit messages to connected clients instead of creating a server instance manually. - Validate incoming payloads with DTOs and pipes before broadcasting or processing client-provided data. # WebSocketGateway **Kind:** Function **Source:** [`packages/websockets/decorators/socket-gateway.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/socket-gateway.decorator.ts#L17) **Part of:** [Websockets](subsystem-packages-websockets) `WebSocketGateway()` marks a class as a NestJS WebSocket gateway, allowing it to receive and emit real-time, event-based messages. Nest reads the decorator metadata during application startup, creates the configured WebSocket server adapter, and routes matching client events to gateway handlers. ## Signature ```ts function WebSocketGateway(portOrOptions: number | T, options: T): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `portOrOptions` | `number | T` | | `options` | `T` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Client[Browser / WebSocket Client] --> Server[WebSocket Server Adapter] Server --> Gateway[@WebSocketGateway() Class] Gateway --> Handler[@SubscribeMessage() Handler] Handler --> Gateway Gateway --> Client ``` ## Usage ```ts import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway({ cors: { origin: 'http://localhost:3000', }, }) export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('chat:message') handleMessage( @MessageBody() message: { text: string }, @ConnectedSocket() client: Socket, ) { this.server.emit('chat:message', { senderId: client.id, text: message.text, }); } } ``` ## AI Coding Instructions - Apply `@WebSocketGateway()` only to provider classes registered in a Nest module. - Use `@SubscribeMessage('event-name')` methods to handle incoming client events. - Configure gateway options, such as `cors`, `namespace`, or `transports`, in the decorator when required by the client integration. - Use `@WebSocketServer()` to emit messages to connected clients instead of creating a server instance manually. - Validate incoming payloads with DTOs and pipes before broadcasting or processing client-provided data. # WebSocketGateway **Kind:** Function **Source:** [`packages/websockets/decorators/socket-gateway.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/socket-gateway.decorator.ts#L17) **Part of:** [Websockets](subsystem-packages-websockets) `WebSocketGateway()` marks a class as a NestJS WebSocket gateway, allowing it to receive and emit real-time, event-based messages. Nest reads the decorator metadata during application startup, creates the configured WebSocket server adapter, and routes matching client events to gateway handlers. ## Signature ```ts function WebSocketGateway(portOrOptions: number | T, options: T): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `portOrOptions` | `number | T` | | `options` | `T` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR Client[Browser / WebSocket Client] --> Server[WebSocket Server Adapter] Server --> Gateway[@WebSocketGateway() Class] Gateway --> Handler[@SubscribeMessage() Handler] Handler --> Gateway Gateway --> Client ``` ## Usage ```ts import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway({ cors: { origin: 'http://localhost:3000', }, }) export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('chat:message') handleMessage( @MessageBody() message: { text: string }, @ConnectedSocket() client: Socket, ) { this.server.emit('chat:message', { senderId: client.id, text: message.text, }); } } ``` ## AI Coding Instructions - Apply `@WebSocketGateway()` only to provider classes registered in a Nest module. - Use `@SubscribeMessage('event-name')` methods to handle incoming client events. - Configure gateway options, such as `cors`, `namespace`, or `transports`, in the decorator when required by the client integration. - Use `@WebSocketServer()` to emit messages to connected clients instead of creating a server instance manually. - Validate incoming payloads with DTOs and pipes before broadcasting or processing client-provided data. # MessageBody **Kind:** Function **Source:** [`packages/websockets/decorators/message-body.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/message-body.decorator.ts#L54) **Part of:** [Websockets](subsystem-packages-websockets) `MessageBody()` binds a WebSocket handler parameter to the payload of an incoming message. It can also apply pipes to the full payload or a selected payload property before the handler receives the value. ## Signature ```ts function MessageBody(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[WebSocket client] --> Message[Incoming message payload] Message --> Decorator[@MessageBody()] Decorator --> Pipes[Configured pipes] Pipes --> Handler[Gateway handler parameter] ``` ## Usage ```typescript import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; import { ValidationPipe } from '@nestjs/common'; import { MessageBody } from '@nestjs/websockets'; class CreateCatDto { name: string; age: number; } @WebSocketGateway() export class CatsGateway { @SubscribeMessage('createCat') create( @MessageBody(new ValidationPipe()) createDto: CreateCatDto, ) { return { event: 'catCreated', data: createDto, }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only on parameters of WebSocket gateway message handlers. - Pass pipes such as `ValidationPipe` when the message payload must be validated or transformed. - Keep the parameter type aligned with the expected client message payload. - Use a property name with `@MessageBody('propertyName')` when a handler only needs part of the payload. - Do not use `@Body()` for WebSocket handlers; it is intended for HTTP request bodies. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # MessageBody **Kind:** Function **Source:** [`packages/websockets/decorators/message-body.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/message-body.decorator.ts#L54) **Part of:** [Websockets](subsystem-packages-websockets) `MessageBody()` binds a WebSocket handler parameter to the payload of an incoming message. It can also apply pipes to the full payload or a selected payload property before the handler receives the value. ## Signature ```ts function MessageBody(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[WebSocket client] --> Message[Incoming message payload] Message --> Decorator[@MessageBody()] Decorator --> Pipes[Configured pipes] Pipes --> Handler[Gateway handler parameter] ``` ## Usage ```typescript import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; import { ValidationPipe } from '@nestjs/common'; import { MessageBody } from '@nestjs/websockets'; class CreateCatDto { name: string; age: number; } @WebSocketGateway() export class CatsGateway { @SubscribeMessage('createCat') create( @MessageBody(new ValidationPipe()) createDto: CreateCatDto, ) { return { event: 'catCreated', data: createDto, }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only on parameters of WebSocket gateway message handlers. - Pass pipes such as `ValidationPipe` when the message payload must be validated or transformed. - Keep the parameter type aligned with the expected client message payload. - Use a property name with `@MessageBody('propertyName')` when a handler only needs part of the payload. - Do not use `@Body()` for WebSocket handlers; it is intended for HTTP request bodies. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # MessageBody **Kind:** Function **Source:** [`packages/websockets/decorators/message-body.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/message-body.decorator.ts#L54) **Part of:** [Websockets](subsystem-packages-websockets) `MessageBody()` binds a WebSocket handler parameter to the payload of an incoming message. It can also apply pipes to the full payload or a selected payload property before the handler receives the value. ## Signature ```ts function MessageBody(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[WebSocket client] --> Message[Incoming message payload] Message --> Decorator[@MessageBody()] Decorator --> Pipes[Configured pipes] Pipes --> Handler[Gateway handler parameter] ``` ## Usage ```typescript import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; import { ValidationPipe } from '@nestjs/common'; import { MessageBody } from '@nestjs/websockets'; class CreateCatDto { name: string; age: number; } @WebSocketGateway() export class CatsGateway { @SubscribeMessage('createCat') create( @MessageBody(new ValidationPipe()) createDto: CreateCatDto, ) { return { event: 'catCreated', data: createDto, }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only on parameters of WebSocket gateway message handlers. - Pass pipes such as `ValidationPipe` when the message payload must be validated or transformed. - Keep the parameter type aligned with the expected client message payload. - Use a property name with `@MessageBody('propertyName')` when a handler only needs part of the payload. - Do not use `@Body()` for WebSocket handlers; it is intended for HTTP request bodies. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # MessageBody **Kind:** Function **Source:** [`packages/websockets/decorators/message-body.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/message-body.decorator.ts#L54) **Part of:** [Websockets](subsystem-packages-websockets) `MessageBody()` binds a WebSocket handler parameter to the payload of an incoming message. It can also apply pipes to the full payload or a selected payload property before the handler receives the value. ## Signature ```ts function MessageBody(propertyOrPipe: string | (Type | PipeTransform), pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `propertyOrPipe` | `string | (Type | PipeTransform)` | | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[WebSocket client] --> Message[Incoming message payload] Message --> Decorator[@MessageBody()] Decorator --> Pipes[Configured pipes] Pipes --> Handler[Gateway handler parameter] ``` ## Usage ```typescript import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; import { ValidationPipe } from '@nestjs/common'; import { MessageBody } from '@nestjs/websockets'; class CreateCatDto { name: string; age: number; } @WebSocketGateway() export class CatsGateway { @SubscribeMessage('createCat') create( @MessageBody(new ValidationPipe()) createDto: CreateCatDto, ) { return { event: 'catCreated', data: createDto, }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only on parameters of WebSocket gateway message handlers. - Pass pipes such as `ValidationPipe` when the message payload must be validated or transformed. - Keep the parameter type aligned with the expected client message payload. - Use a property name with `@MessageBody('propertyName')` when a handler only needs part of the payload. - Do not use `@Body()` for WebSocket handlers; it is intended for HTTP request bodies. ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` # createPipesWsParamDecorator **Kind:** Function **Source:** [`packages/websockets/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/utils/param.utils.ts#L25) **Part of:** [Websockets](subsystem-packages-websockets) ## Signature ```ts function createPipesWsParamDecorator(paramtype: WsParamtype) ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `WsParamtype` | # GatewayMetadata **Kind:** Interface **Source:** [`packages/websockets/interfaces/gateway-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/gateway-metadata.interface.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) External interface `GatewayMetadata` defines the configuration used to initialize and operate a WebSocket gateway. It captures the gateway namespace, HTTP path, client-serving behavior, transport adapters/parsers, and connection or heartbeat timeout settings. ## Properties | Property | Type | |---|---| | `namespace` | `string | RegExp` | | `path` | `string` | | `serveClient` | `boolean` | | `adapter` | `any` | | `parser` | `any` | | `connectTimeout` | `number` | | `pingTimeout` | `number` | | `pingInterval` | `number` | | `upgradeTimeout` | `number` | | `maxHttpBufferSize` | `number` | | `allowRequest` | `( req: any, fn: (err: string | null | undefined, success: boolean) => void, ) => void` | | `transports` | `Array<'polling' | 'websocket'>` | | `allowUpgrades` | `boolean` | | `perMessageDeflate` | `boolean | object` | | `httpCompression` | `boolean | object` | | `wsEngine` | `string` | | `initialPacket` | `any` | | `cookie` | `any` | | `cors` | `CorsOptions` | | `allowEIO3` | `boolean` | | `destroyUpgrade` | `boolean` | | `destroyUpgradeTimeout` | `number` | ## Diagram ```mermaid graph LR GatewayMetadata --> Namespace["namespace: string | RegExp"] GatewayMetadata --> Path["path: string"] GatewayMetadata --> Client["serveClient: boolean"] GatewayMetadata --> Transport["adapter / parser"] GatewayMetadata --> Timeouts["Connection and upgrade timeouts"] GatewayMetadata --> Heartbeat["Ping interval and timeout"] GatewayMetadata --> Buffer["maxHttpBufferSize"] Timeouts --> Connect["connectTimeout"] Timeouts --> Upgrade["upgradeTimeout"] Heartbeat --> PingInterval["pingInterval"] Heartbeat --> PingTimeout["pingTimeout"] ``` ## Usage ```ts import type { GatewayMetadata } from './interfaces/gateway-metadata.interface'; const chatGatewayMetadata: GatewayMetadata = { namespace: '/chat', path: '/socket.io', serveClient: true, adapter: undefined, parser: undefined, connectTimeout: 10_000, pingTimeout: 20_000, pingInterval: 25_000, upgradeTimeout: 10_000, maxHttpBufferSize: 1e6, }; // Pass this metadata to the gateway/WebSocket server initialization layer. initializeGateway(chatGatewayMetadata); ``` ## AI Coding Instructions - Use `namespace` to isolate gateway endpoints; provide a `RegExp` only when dynamic namespace matching is required. - Keep `path` aligned with the client connection configuration, or clients will fail to establish a WebSocket connection. - Configure `pingInterval` and `pingTimeout` together; ensure the timeout allows for expected network latency. - Treat `adapter` and `parser` as integration points for the underlying WebSocket implementation and provide compatible instances. - Set `maxHttpBufferSize` conservatively to limit oversized payloads and reduce memory-pressure risks. ## Relationships - IMPORTS → `CorsOptions` # WsParamsFactory **Kind:** Class **Source:** [`packages/websockets/factories/ws-params-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/factories/ws-params-factory.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) `WsParamsFactory` resolves WebSocket handler parameter values from the runtime argument array. It maps WebSocket parameter types—such as the connected socket or message payload—to the values injected into gateway handler methods. ## Methods | Method | Signature | Returns | |---|---|---| | `exchangeKeyForValue` | `exchangeKeyForValue(type: number, data: string | undefined, args: unknown[])` | `void` | ## Where it refuses work - `WsParamsFactory` stops the work with an early return when `!args`. ## Diagram ```mermaid graph LR A[WebSocket event arguments] --> B[WsParamsFactory.exchangeKeyForValue] B --> C{WsParamtype} C -->|SOCKET| D[Socket client: args[0]] C -->|PAYLOAD| E[Message payload: args[1]] E -->|Property key provided| F[Payload property] ``` ## Usage ```ts import { WsParamsFactory } from '@nestjs/websockets/factories/ws-params-factory'; import { WsParamtype } from '@nestjs/websockets/enums/ws-paramtype.enum'; const paramsFactory = new WsParamsFactory(); const client = { id: 'socket-123' }; const payload = { roomId: 'general', message: 'Hello' }; const args = [client, payload]; const socket = paramsFactory.exchangeKeyForValue( WsParamtype.SOCKET, undefined, args, ); const message = paramsFactory.exchangeKeyForValue( WsParamtype.PAYLOAD, 'message', args, ); console.log(socket); // { id: 'socket-123' } console.log(message); // "Hello" ``` ## AI Coding Instructions - Treat `args[0]` as the WebSocket client and `args[1]` as the incoming event payload. - Use `WsParamtype.SOCKET` to resolve the client connection and `WsParamtype.PAYLOAD` to resolve the full payload or a payload property. - Pass a payload property key only when extracting a nested top-level value; omit it to receive the complete payload. - Keep parameter-resolution behavior aligned with WebSocket decorators such as `@ConnectedSocket()` and `@MessageBody()`. - Avoid depending on this factory as a general-purpose object accessor; it is intended for WebSocket handler argument binding. ## Relationships - IMPORTS → `isFunction` # createWsParamDecorator **Kind:** Function **Source:** [`packages/websockets/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/utils/param.utils.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) ## Signature ```ts function createWsParamDecorator(paramtype: WsParamtype): (...pipes: (Type | PipeTransform)[]) => ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `WsParamtype` | **Returns:** `(...pipes: (Type | PipeTransform)[]) => ParameterDecorator` ## Relationships - IMPORTS → `PipeTransform` - IMPORTS → `Type` - IMPORTS → `assignMetadata` - IMPORTS → `isNil` - IMPORTS → `isString` # ServerAndEventStreamsFactory **Kind:** Class **Source:** [`packages/websockets/factories/server-and-event-streams-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/factories/server-and-event-streams-factory.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) `ServerAndEventStreamsFactory` creates a `ServerAndEventStreamsHost` around an existing WebSocket server instance. It provides the WebSocket layer with a consistent host object that can expose the underlying server and its event-stream capabilities to the rest of the framework. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(server: T)` | `ServerAndEventStreamsHost` | ## Diagram ```mermaid graph LR A[WebSocket Adapter / Server] --> B[ServerAndEventStreamsFactory] B -->|create()| C[ServerAndEventStreamsHost] C --> D[WebSocket Server Instance] C --> E[Event Stream Handlers] ``` ## Usage ```ts import { Server } from 'socket.io'; import { ServerAndEventStreamsFactory } from '@nestjs/websockets/factories/server-and-event-streams-factory'; const io = new Server(3000, { cors: { origin: '*', }, }); const factory = new ServerAndEventStreamsFactory(); const host = factory.create(io); // Access the wrapped server through the host. host.server.on('connection', socket => { socket.emit('connected', { message: 'Welcome!' }); }); ``` ## AI Coding Instructions - Use this factory when framework code needs a `ServerAndEventStreamsHost` rather than a raw WebSocket server instance. - Preserve the generic server type (`T`) so adapter-specific APIs, such as Socket.IO methods, remain type-safe. - Pass an already initialized server instance; this factory wraps server/event-stream infrastructure and should not be responsible for server startup configuration. - Keep adapter-specific behavior outside the factory—implement transport setup and connection options in the WebSocket adapter or bootstrap layer. - Treat this as framework infrastructure; prefer public WebSocket module APIs in application code when available. ## How it works ## `ServerAndEventStreamsFactory` `ServerAndEventStreamsFactory` is an exported class with one static method, `create(server)`, which constructs a `ServerAndEventStreamsHost` around a supplied server value. [server-and-event-streams-factory.ts:4-5](packages/websockets/factories/server-and-event-streams-factory.ts#L4-L5) # MessageMappingProperties **Kind:** Interface **Source:** [`packages/websockets/gateway-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/gateway-metadata-explorer.ts#L15) **Part of:** [Websockets](subsystem-packages-websockets) `MessageMappingProperties` describes the metadata required to connect an incoming WebSocket message to a gateway handler method. It stores the message pattern, handler name, executable callback, and whether acknowledgment handling is performed manually by the handler. ## Properties | Property | Type | |---|---| | `message` | `any` | | `methodName` | `string` | | `callback` | `(...args: any[]) => Observable | Promise` | | `isAckHandledManually` | `boolean` | ## Diagram ```mermaid graph LR Client[WebSocket Client] --> Message[Incoming Message] Message --> Mapping[MessageMappingProperties] Mapping --> Pattern[message] Mapping --> Handler[methodName] Mapping --> Callback[callback] Mapping --> Ack[isAckHandledManually] Callback --> Result[Observable or Promise Result] ``` ## Usage ```ts import { Observable, of } from 'rxjs'; interface MessageMappingProperties { message: any; methodName: string; callback: (...args: any[]) => Observable | Promise; isAckHandledManually: boolean; } const messageMapping: MessageMappingProperties = { message: 'chat:send', methodName: 'handleChatMessage', callback: async (client, payload) => { return { event: 'chat:received', data: { clientId: client.id, message: payload.message, }, }; }, isAckHandledManually: false, }; // Example callback invocation during message dispatch messageMapping.callback({ id: 'client-1' }, { message: 'Hello' }) .then((result) => console.log(result)); ``` ## AI Coding Instructions - Ensure `callback` always returns either an `Observable` or a `Promise`; wrap synchronous values with `Promise.resolve()` or `of()`. - Use `message` as the routing pattern that identifies which incoming WebSocket event should invoke the handler. - Set `isAckHandledManually` to `true` only when the handler explicitly invokes the client acknowledgment callback. - Preserve `methodName` for diagnostics, logging, and metadata exploration; it should match the associated gateway method name. - Avoid assuming a specific message payload shape because `message` and callback arguments are intentionally typed as `any`. ## Relationships - IMPORTS → `isFunction` - IMPORTS → `isUndefined` - IMPORTS → `MetadataScanner` - IMPORTS → `ParamsMetadata` - IMPORTS → `ContextUtils` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `IoAdapter` — `packages/platform-socket.io/adapters/io-adapter.ts`:14 - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 # WebSocketServer **Kind:** Function **Source:** [`packages/websockets/decorators/gateway-server.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/gateway-server.decorator.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) Attaches native Web Socket Server to a given property. `WebSocketServer()` is a property decorator that attaches the underlying native WebSocket server instance to a gateway class property. Nest initializes the property after the gateway is created, allowing gateway methods to emit events, broadcast messages, or access adapter-specific server APIs. ## Signature ```ts function WebSocketServer(): PropertyDecorator ``` **Returns:** `PropertyDecorator` ## Diagram ```mermaid graph LR A[WebSocketGateway] --> B[WebSocketServer Decorator] B --> C[Gateway Server Property] D[Nest WebSockets Runtime] --> E[Create Native Server] E --> C C --> F[Emit or Broadcast Events] ``` ## Usage ```ts import { SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class EventsGateway { @WebSocketServer() server: Server; @SubscribeMessage('message') handleMessage(client: Socket, payload: { text: string }) { this.server.emit('message', { from: client.id, text: payload.text, }); } } ``` ## AI Coding Instructions - Use `@WebSocketServer()` only on gateway class properties decorated with `@WebSocketGateway()`. - Type the decorated property with the native server implementation used by the configured adapter, such as Socket.IO's `Server`. - Do not manually instantiate or assign the server property; Nest populates it during gateway initialization. - Use the injected server for server-wide operations such as `emit`, room broadcasting, and adapter-specific APIs. - Ensure event handlers account for the selected WebSocket adapter, since native server APIs differ between Socket.IO and `ws`. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `EventsGateway` — `sample/02-gateways/src/events/events.gateway.ts`:12 - `EventsGateway` — `sample/16-gateways-ws/src/events/events.gateway.ts`:11 # WsResponse **Kind:** Interface **Source:** [`packages/websockets/interfaces/ws-response.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/ws-response.interface.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) `WsResponse` defines the standard envelope for messages sent through the WebSocket layer. It pairs an `event` name with typed `data`, allowing clients and servers to route and process real-time responses consistently. ## Properties | Property | Type | |---|---| | `event` | `string` | | `data` | `T` | ## Diagram ```mermaid graph LR Server[WebSocket Server] --> Response[WsResponse] Response --> Event[event: string] Response --> Data[data: T] Response --> Client[WebSocket Client] ``` ## Usage ```ts import type { WsResponse } from './interfaces/ws-response.interface'; interface UserConnectedPayload { userId: string; connectedAt: string; } const response: WsResponse = { event: 'user.connected', data: { userId: 'user_123', connectedAt: new Date().toISOString(), }, }; socket.emit(response.event, response.data); ``` ## AI Coding Instructions - Use `WsResponse` for WebSocket response payloads to keep event names and data consistently structured. - Define a dedicated payload interface or type for `T` instead of using `any`. - Keep `event` values stable and descriptive, such as `user.connected` or `message.created`. - Emit the event and payload using `socket.emit(response.event, response.data)` when the transport expects separate arguments. - Ensure client-side listeners use the same event name and payload type as the corresponding response. ## How it works `WsResponse` is a public TypeScript interface for an object with two required fields: `event`, a `string`, and `data`, whose type is the generic parameter `T` (defaulting to `any`). [packages/websockets/interfaces/ws-response.interface.ts:1-7] It is re-exported through the interfaces barrel and the package root, so it is available from `@nestjs/websockets`. [packages/websockets/interfaces/index.ts:1-5] [packages/websockets/index.ts:9-14] The interface has no methods or runtime implementation; the shown declaration contains no validation, error handling, or side effects. [packages/websockets/interfaces/ws-response.interface.ts:4-7] In the gateway sample, a message handler is typed as returning `Observable>` and maps `1`, `2`, and `3` into objects shaped as `{ event: 'events', data: item }`. [sample/02-gateways/src/events/events.gateway.ts:21-24] ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `EventsGateway` — `sample/02-gateways/src/events/events.gateway.ts`:12 - `EventsGateway` — `sample/16-gateways-ws/src/events/events.gateway.ts`:11 # ErrorPayload **Kind:** Interface **Source:** [`packages/websockets/exceptions/base-ws-exception-filter.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/exceptions/base-ws-exception-filter.ts#L11) **Part of:** [Websockets](subsystem-packages-websockets) `ErrorPayload` defines the standardized error message shape emitted by the WebSocket exception handling layer. It identifies the payload as an error, provides a human-readable message, and preserves the underlying `Cause` for clients or downstream handlers that need additional context. ## Properties | Property | Type | |---|---| | `status` | `'error'` | | `message` | `string` | | `cause` | `Cause` | ## Diagram ```mermaid graph LR A[WebSocket handler throws an error] --> B[Base WebSocket Exception Filter] B --> C[ErrorPayload] C --> D[status: "error"] C --> E[message: string] C --> F[cause: Cause] C --> G[WebSocket client receives error event] ``` ## Usage ```ts import type { ErrorPayload } from './base-ws-exception-filter'; function createErrorPayload( message: string, cause: Cause, ): ErrorPayload { return { status: 'error', message, cause, }; } const payload = createErrorPayload( 'Unable to join the room.', { code: 'ROOM_NOT_FOUND', details: { roomId: 'room-123' }, }, ); // Example: emit through a WebSocket server or gateway client.emit('exception', payload); ``` ## AI Coding Instructions - Always set `status` to the literal value `'error'`; do not use arbitrary status strings. - Keep `message` safe and client-friendly; avoid exposing stack traces, secrets, or internal database details. - Populate `cause` with the original structured error context so exception filters can preserve error metadata. - Use `ErrorPayload` consistently for WebSocket error emissions rather than creating endpoint-specific error shapes. - Ensure WebSocket clients handle the `status`, `message`, and `cause` fields when processing exception events. ## How it works `ErrorPayload` is an exported TypeScript interface for the non-object WebSocket exception payload shape. Its default `cause` type contains a string `pattern` and `unknown` `data`. [base-ws-exception-filter.ts:11-24] - `status` is required and is limited to the literal value `'error'`. [base-ws-exception-filter.ts:15] - `message` is required and is a string. [base-ws-exception-filter.ts:17-19] - `cause` is optional and has the generic `Cause` type. [base-ws-exception-filter.ts:20-23] - The interface is exported again through the WebSocket exceptions index. [exceptions/index.ts:1] `BaseWsExceptionFilter` constructs an `ErrorPayload` for a `WsException` whose `getError()` result is not an object, setting `status` to `'error'` and `message` to that result. It emits this payload on the client’s `'exception'` event. [base-ws-exception-filter.ts:76-92] `WsException.getError()` returns the value passed to its constructor, whose declared type is `string | object`; therefore this payload path is for string-valued `WsException` errors. [ws-exception.ts:3-6, ws-exception.ts:24-26] For exceptions that are not `WsException` instances, the filter constructs an `ErrorPayload` with `status: 'error'` and the message `'Internal server error'`, then emits it on `'exception'`. [base-ws-exception-filter.ts:72-74, base-ws-exception-filter.ts:100-110, core/constants.ts:3-8] If the exception is not an `IntrinsicException`, this unknown-error path also logs the exception. [base-ws-exception-filter.ts:112-115] A `cause` is attached only when both a cause argument exists and `includeCause` is enabled. The filter defaults `includeCause` to `true` and defaults `causeFactory` to a function returning `{ pattern, data }`; a configured `causeFactory` determines the attached cause value. [base-ws-exception-filter.ts:51-55, base-ws-exception-filter.ts:88-90, base-ws-exception-filter.ts:106-108] The `catch` method obtains the WebSocket pattern and data from the arguments host and passes them as the cause input. [base-ws-exception-filter.ts:57-65] A `WsException` carrying an object does **not** get wrapped as an `ErrorPayload`; the filter emits that object directly on `'exception'`. [base-ws-exception-filter.ts:77-81] ## Relationships - IMPORTS → `ArgumentsHost` - IMPORTS → `IntrinsicException` - IMPORTS → `Logger` - IMPORTS → `WsExceptionFilter` - IMPORTS → `isObject` - IMPORTS → `MESSAGES` # Ack **Kind:** Function **Source:** [`packages/websockets/decorators/ack.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/ack.decorator.ts#L26) **Part of:** [Websockets](subsystem-packages-websockets) WebSockets `ack` parameter decorator. Extracts the `ack` callback function from the arguments of a ws event. This decorator signals to the framework that the `ack` callback will be handled manually within the method, preventing the framework from automatically sending an acknowledgement based on the return value. `Ack` is a WebSocket parameter decorator that injects the event acknowledgement callback into a handler method. Using this decorator tells the framework that the handler will send its own acknowledgement response instead of automatically acknowledging the event from the method’s return value. ## Signature ```ts function Ack(): ParameterDecorator ``` **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[WebSocket client] -->|emit event with ack callback| Gateway[Gateway event handler] Gateway -->|@Ack()| AckParam[ack callback parameter] AckParam -->|manual acknowledgement| Client Gateway -. return value is not auto-acknowledged .-> Framework[WebSocket framework] ``` ## Usage ```ts import { Ack, SubscribeMessage } from '@nestjs/websockets'; export class ChatGateway { @SubscribeMessage('send-message') handleMessage( @Ack() ack: (response: { ok: boolean; messageId?: string }) => void, ) { const messageId = crypto.randomUUID(); // Perform application work before responding. ack({ ok: true, messageId, }); } } ``` ## AI Coding Instructions - Use `@Ack()` only on WebSocket event handler parameters where the acknowledgement must be sent manually. - Call the injected `ack` callback with the response payload expected by the connected client. - Do not rely on the handler return value to acknowledge an event when `@Ack()` is present. - Keep acknowledgement handling inside the handler or delegate it to a service, ensuring the callback is invoked after the relevant async work completes. - Ensure client-side event emissions provide an acknowledgement callback when the server handler expects one. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AckGateway` — `integration/websockets/src/ack.gateway.ts`:8 # ConnectedSocket **Kind:** Constant **Source:** [`packages/websockets/decorators/connected-socket.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/connected-socket.decorator.ts#L7) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createWsParamDecorator( WsParamtype.SOCKET, ) ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `CoreGateway` — `integration/websockets/src/core.gateway.ts`:8 # ServerAndEventStreamsHost **Kind:** Interface **Source:** [`packages/websockets/interfaces/server-and-event-streams-host.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/server-and-event-streams-host.interface.ts#L6) **Part of:** [Websockets](subsystem-packages-websockets) `ServerAndEventStreamsHost` defines a shared host for a server instance and its lifecycle event streams. It exposes the server object along with RxJS subjects for initialization, client connections, and disconnections, allowing websocket integrations to publish and observe server events consistently. ## Properties | Property | Type | |---|---| | `server` | `T` | | `init` | `ReplaySubject` | | `connection` | `Subject` | | `disconnect` | `Subject` | ## Diagram ```mermaid graph LR Host[ServerAndEventStreamsHost] Server[T server] Init[ReplaySubject
init] Connection[Subject
connection] Disconnect[Subject
disconnect] Host --> Server Host --> Init Host --> Connection Host --> Disconnect Init --> Consumers[Server lifecycle consumers] Connection --> Consumers Disconnect --> Consumers ``` ## Usage ```ts import { ReplaySubject, Subject } from 'rxjs'; import type { ServerAndEventStreamsHost } from './server-and-event-streams-host.interface'; interface WebSocketServer { close(): void; } const websocketServer: WebSocketServer = { close() { console.log('Server closed'); }, }; const host: ServerAndEventStreamsHost = { server: websocketServer, init: new ReplaySubject(1), connection: new Subject(), disconnect: new Subject(), }; // Notify subscribers that the server is ready. host.init.next(host.server); // Publish connection lifecycle events. host.connection.subscribe((client) => { console.log('Client connected:', client.id); }); host.disconnect.subscribe((client) => { console.log('Client disconnected:', client.id); }); host.connection.next({ id: 'client-1' }); host.disconnect.next({ id: 'client-1' }); ``` ## AI Coding Instructions - Use `init` as a `ReplaySubject` so late subscribers can receive the initialized server instance. - Emit the server instance through `init.next(server)` only after the server is fully configured and ready to accept connections. - Publish connection and disconnection payloads through the corresponding subjects; keep payload shapes consistent across adapters. - Prefer strongly typed connection payloads over `any` when extending or consuming this interface. - Clean up subject subscriptions and complete streams during server shutdown when the owning lifecycle supports it. ## How it works ## `ServerAndEventStreamsHost` `ServerAndEventStreamsHost` is a public exported TypeScript interface for a websocket server value and three RxJS event streams. Its generic server type defaults to `any`. [server-and-event-streams-host.interface.ts:3-10] | Member | Type | Observed role | |---|---|---| | `server` | `T` | Holds the underlying server object. [server-and-event-streams-host.interface.ts:6-8] The websocket controller passes it to the adapter’s client-connect binding and assigns it to gateway properties marked as server hooks. [web-sockets-controller.ts:111-126] [web-sockets-controller.ts:227-235] | | `init` | `ReplaySubject` | Carries server initialization values. [server-and-event-streams-host.interface.ts:8] The factory creates this subject and immediately emits the supplied `server` value. [server-and-event-streams-factory.ts:5-7] When a gateway has `afterInit`, the controller subscribes that hook to this stream. [web-sockets-controller.ts:148-152] | | `connection` | `Subject` | Carries client connection argument arrays. [server-and-event-streams-host.interface.ts:9] The controller emits the adapter connection handler’s complete argument list to it, then invokes `handleConnection` with those arguments when that hook exists; duplicate consecutive connections with the same first argument are filtered before the hook call. [web-sockets-controller.ts:129-145] [web-sockets-controller.ts:154-161] | | `disconnect` | `Subject` | Carries disconnected client values. [server-and-event-streams-host.interface.ts:10] If the adapter exposes `bindClientDisconnect`, the connection handler registers a callback that emits the client to this subject. [web-sockets-controller.ts:142-145] When a gateway has `handleDisconnect`, the controller subscribes that hook after `distinctUntilChanged()`. [web-sockets-controller.ts:164-169] | # DEFAULT_CALLBACK_METADATA **Kind:** Constant **Source:** [`packages/websockets/context/ws-metadata-constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/context/ws-metadata-constants.ts#L3) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts { [`${WsParamtype.ACK}:2`]: { index: 2, data: undefined, pipes: [] }, [`${WsParamtype.PAYLOAD}:1`]: { index: 1, data: undefined, pipes: [] }, [`${WsParamtype.SOCKET}:0`]: { index: 0, data: undefined, pipes: [] }, } ``` ## Value ```ts { [`${WsParamtype.ACK}:2`]: { index: 2, data: undefined, pipes: [] }, [`${WsParamtype.PAYLOAD}:1`]: { index: 1, data: undefined, pipes: [] }, [`${WsParamtype.SOCKET}:0`]: { index: 0, data: undefined, pipes: [] }, } ``` # InvalidSocketPortException **Kind:** Class **Source:** [`packages/websockets/errors/invalid-socket-port.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/errors/invalid-socket-port.exception.ts#L3) **Part of:** [Websockets](subsystem-packages-websockets) **Extends:** `RuntimeException` ## Relationships - IMPORTS → `RuntimeException` # NestGateway **Kind:** Interface **Source:** [`packages/websockets/interfaces/nest-gateway.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/nest-gateway.interface.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) `NestGateway` defines lifecycle hooks for WebSocket gateway classes in NestJS. Implement these optional methods to access the initialized server, react to client connections, and clean up when clients disconnect. ## Properties | Property | Type | |---|---| | `afterInit` | `(server: any) => void` | | `handleConnection` | `(...args: any[]) => void` | | `handleDisconnect` | `(client: any) => void` | ## Diagram ```mermaid graph LR A[WebSocket Server Initialized] --> B[afterInit(server)] B --> C[Client Connects] C --> D[handleConnection(...args)] D --> E[Client Disconnects] E --> F[handleDisconnect(client)] ``` ## Usage ```ts import { WebSocketGateway } from '@nestjs/websockets'; import type { NestGateway } from '@nestjs/websockets'; @WebSocketGateway() export class EventsGateway implements NestGateway { afterInit(server: any): void { console.log('WebSocket server initialized'); } handleConnection(client: any, ...args: any[]): void { console.log(`Client connected: ${client.id}`); } handleDisconnect(client: any): void { console.log(`Client disconnected: ${client.id}`); } } ``` ## AI Coding Instructions - Implement `NestGateway` on classes decorated with `@WebSocketGateway()` when lifecycle callbacks are needed. - Use `afterInit` to configure or inspect the underlying WebSocket server after it is created. - Keep `handleConnection(...args)` flexible because adapter-specific connection arguments may follow the client object. - Release client-specific resources, subscriptions, and session state in `handleDisconnect`. - Avoid assuming a specific client or server API when supporting multiple WebSocket adapters; narrow `any` values to the adapter type in use. # WsHandlerMetadata **Kind:** Interface **Source:** [`packages/websockets/context/ws-context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/context/ws-context-creator.ts#L34) **Part of:** [Websockets](subsystem-packages-websockets) `WsHandlerMetadata` describes the reflected metadata required to create and invoke a WebSocket handler. It captures the handler's argument count and parameter types, and provides a module-aware function for retrieving WebSocket parameter metadata. ## Properties | Property | Type | |---|---| | `argsLength` | `number` | | `paramtypes` | `any[]` | | `getParamsMetadata` | `(moduleKey: string) => WsParamProperties[]` | ## Diagram ```mermaid graph LR A[WebSocket Gateway Handler] --> B[WsHandlerMetadata] B --> C[argsLength: number] B --> D[paramtypes: any[]] B --> E[getParamsMetadata(moduleKey)] E --> F[WsParamProperties[]] F --> G[WsContextCreator] ``` ## Usage ```ts import type { WsHandlerMetadata } from '@nestjs/websockets'; const handlerMetadata: WsHandlerMetadata = { argsLength: 2, paramtypes: [Object, Object], getParamsMetadata: (moduleKey) => { if (moduleKey !== 'chat-module') { return []; } return [ { index: 0, data: undefined, pipes: [], factory: /* WebSocket parameter factory */, }, ]; }, }; // Pass metadata to the WebSocket context creation flow. const paramsMetadata = handlerMetadata.getParamsMetadata('chat-module'); ``` ## AI Coding Instructions - Preserve `argsLength` so generated handler argument arrays match the original method signature. - Keep `paramtypes` aligned with the reflected parameter types for the gateway handler method. - Implement `getParamsMetadata` as module-aware; metadata may differ based on the resolved `moduleKey`. - Return an empty `WsParamProperties[]` when no parameter decorators or metadata apply. - Integrate this metadata with `WsContextCreator` when constructing pipes, extracting socket payloads, or resolving decorated parameters. ## Relationships - IMPORTS → `CUSTOM_ROUTE_ARGS_METADATA` - IMPORTS → `PARAMTYPES_METADATA` - IMPORTS → `ContextType` - IMPORTS → `Controller` - IMPORTS → `PipeTransform` - IMPORTS → `isEmpty` - IMPORTS → `FORBIDDEN_MESSAGE` - IMPORTS → `GuardsConsumer` - IMPORTS → `GuardsContextCreator` - IMPORTS → `ContextUtils` - IMPORTS → `ParamProperties` - IMPORTS → `ExecutionContextHost` - IMPORTS → `HandlerMetadataStorage` - IMPORTS → `ParamsMetadata` - IMPORTS → `InterceptorsConsumer` - IMPORTS → `InterceptorsContextCreator` - IMPORTS → `PipesConsumer` - IMPORTS → `PipesContextCreator` # WsParamtype **Kind:** Enum **Source:** [`packages/websockets/enums/ws-paramtype.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/enums/ws-paramtype.enum.ts#L3) **Part of:** [Websockets](subsystem-packages-websockets) ## Values - `SOCKET` - `PAYLOAD` - `ACK` ## Relationships - IMPORTS → `RouteParamtypes` # BaseWsInstance **Kind:** Interface **Source:** [`packages/websockets/adapters/ws-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/adapters/ws-adapter.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) `BaseWsInstance` defines the minimal WebSocket-like contract required by the WS adapter. Implementations must support event subscription through `on` and expose a `close` function so the adapter can listen for lifecycle events and terminate connections consistently. ## Properties | Property | Type | |---|---| | `on` | `(event: string, callback: Function) => void` | | `close` | `Function` | ## Diagram ```mermaid graph LR Adapter[WS Adapter] --> Instance[BaseWsInstance] Instance --> On["on(event, callback)"] Instance --> Close["close()"] On --> Events[Connection and message events] Close --> Cleanup[Connection cleanup] ``` ## Usage ```ts import type { BaseWsInstance } from './ws-adapter'; function registerConnection(socket: BaseWsInstance) { socket.on('message', (data: unknown) => { console.log('Received message:', data); }); socket.on('close', () => { console.log('Connection closed'); }); // Close the connection when it is no longer needed. socket.close(); } ``` ## AI Coding Instructions - Treat `BaseWsInstance` as an adapter boundary; only rely on `on` and `close` when writing transport-agnostic WebSocket code. - Register event listeners with the expected event names supported by the underlying WebSocket implementation. - Ensure `close` is called during shutdown, error handling, or resource cleanup paths. - Avoid depending on implementation-specific socket APIs unless the adapter interface is explicitly extended. ## Relationships - IMPORTS → `INestApplicationContext` - IMPORTS → `WebSocketAdapter` - IMPORTS → `WsMessageHandler` - IMPORTS → `isFunction` - IMPORTS → `NestApplication` # WebsocketEntrypointMetadata **Kind:** Type **Source:** [`packages/websockets/interfaces/websockets-entrypoint-metadata.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/websockets-entrypoint-metadata.interface.ts#L1) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts { port: number; message: unknown; } ``` # WebSocketServerOptions **Kind:** Interface **Source:** [`packages/websockets/interfaces/web-socket-server.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/web-socket-server.interface.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) `WebSocketServerOptions` defines the configuration required to initialize a WebSocket server. It specifies the network port the server listens on and the namespace used to scope or route WebSocket connections within the application. ## Properties | Property | Type | |---|---| | `port` | `number` | | `namespace` | `string` | ## Diagram ```mermaid graph LR A[Application Configuration] --> B[WebSocketServerOptions] B --> C[port: number] B --> D[namespace: string] C --> E[WebSocket Server Listener] D --> F[Connection Namespace / Route] ``` ## Usage ```ts import type { WebSocketServerOptions } from './interfaces/web-socket-server.interface'; const websocketOptions: WebSocketServerOptions = { port: 3001, namespace: '/notifications', }; // Pass the options when creating or configuring the WebSocket server. createWebSocketServer(websocketOptions); ``` ## AI Coding Instructions - Provide a valid, available TCP port as `port`; avoid conflicting with the application's HTTP server port unless shared-server support exists. - Use a consistent `namespace` format, typically beginning with `/`, such as `/chat` or `/notifications`. - Keep namespace values aligned with the client connection URL and any server-side routing or gateway configuration. - Treat this interface as configuration-only; do not add runtime connection state or server instances to it. ## How it works `WebSocketServerOptions` is an exported TypeScript interface marked `@publicApi`. It describes an object with two required properties: [packages/websockets/interfaces/web-socket-server.interface.ts:1-7] - `port: number` — a numeric `port` property. [packages/websockets/interfaces/web-socket-server.interface.ts:4-6] - `namespace: string` — a string `namespace` property. [packages/websockets/interfaces/web-socket-server.interface.ts:4-7] The interface itself contains no runtime validation, error handling, or side effects. [packages/websockets/interfaces/web-socket-server.interface.ts:4-7] # OnGatewayConnection **Kind:** Interface **Source:** [`packages/websockets/interfaces/hooks/on-gateway-connection.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/hooks/on-gateway-connection.interface.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) # OnGatewayDisconnect **Kind:** Interface **Source:** [`packages/websockets/interfaces/hooks/on-gateway-disconnect.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/hooks/on-gateway-disconnect.interface.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) # OnGatewayInit **Kind:** Interface **Source:** [`packages/websockets/interfaces/hooks/on-gateway-init.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/interfaces/hooks/on-gateway-init.interface.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) # CLOSE_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L14) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'close' ``` ## Value ```ts 'close' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 # CONNECTION_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L12) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'connection' ``` ## Value ```ts 'connection' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 # DISCONNECT_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L13) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'disconnect' ``` ## Value ```ts 'disconnect' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IoAdapter` — `packages/platform-socket.io/adapters/io-adapter.ts`:14 # ERROR_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L15) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'error' ``` ## Value ```ts 'error' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `WsAdapter` — `packages/platform-ws/adapters/ws-adapter.ts`:39 # GATEWAY_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L6) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'websockets:is_gateway' ``` ## Value ```ts 'websockets:is_gateway' ``` # GATEWAY_OPTIONS **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L9) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'websockets:gateway_options' ``` ## Value ```ts 'websockets:gateway_options' ``` # GATEWAY_SERVER_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L5) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'websockets:is_socket' ``` ## Value ```ts 'websockets:is_socket' ``` # MESSAGE_MAPPING_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L3) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'websockets:message_mapping' ``` ## Value ```ts 'websockets:message_mapping' ``` ## Relationships - IMPORTS → `ROUTE_ARGS_METADATA` # MESSAGE_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L4) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'message' ``` ## Value ```ts 'message' ``` # NAMESPACE_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L7) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'namespace' ``` ## Value ```ts 'namespace' ``` # PARAM_ARGS_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L10) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts ROUTE_ARGS_METADATA ``` ## Value ```ts ROUTE_ARGS_METADATA ``` # PORT_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L8) **Part of:** [Websockets](subsystem-packages-websockets) ## Definition ```ts 'port' ``` ## Value ```ts 'port' ``` # MulterModule **Kind:** Module **Source:** [`packages/platform-express/multer/multer.module.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/multer.module.ts#L14) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Relationships - IMPORTS → `DynamicModule` - IMPORTS → `Module` - IMPORTS → `Provider` - IMPORTS → `randomStringGenerator` # ExpressAdapter **Kind:** Class **Source:** [`packages/platform-express/adapters/express-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/adapters/express-adapter.ts#L51) **Part of:** [Platform Express](subsystem-packages-platform-express) `ExpressAdapter` connects the platform-agnostic HTTP adapter contract to an Express application. It manages request and response hooks, response helpers, rendering and redirects, and Express-level error or not-found handlers. **Extends:** `AbstractHttpAdapter` ## Methods | Method | Signature | Returns | |---|---|---| | `setOnRequestHook` | `setOnRequestHook(onRequestHook: ( req: express.Request, res: express.Response, done: () => void, ) => Promise | void)` | `void` | | `setOnResponseHook` | `setOnResponseHook(onResponseHook: ( req: express.Request, res: express.Response, ) => Promise | void)` | `void` | | `reply` | `reply(response: any, body: any, statusCode: number)` | `void` | | `status` | `status(response: any, statusCode: number)` | `void` | | `end` | `end(response: any, message: string)` | `void` | | `render` | `render(response: any, view: string, options: any)` | `void` | | `redirect` | `redirect(response: any, statusCode: number, url: string)` | `void` | | `setErrorHandler` | `setErrorHandler(handler: Function, prefix: string)` | `void` | | `setNotFoundHandler` | `setNotFoundHandler(handler: Function, prefix: string)` | `void` | | `isHeadersSent` | `isHeadersSent(response: any)` | `boolean` | | `getHeader` | `getHeader(response: any, name: string)` | `void` | | `setHeader` | `setHeader(response: any, name: string, value: string)` | `void` | | `appendHeader` | `appendHeader(response: any, name: string, value: string)` | `void` | | `normalizePath` | `normalizePath(path: string)` | `string` | | `listen` | `listen(port: string | number, callback: () => void)` | `Server` | | `listen` | `listen(port: string | number, hostname: string, callback: () => void)` | `Server` | | `listen` | `listen(port: any, args: any[])` | `Server` | | `close` | `close()` | `void` | | `set` | `set(args: any[])` | `void` | | `enable` | `enable(args: any[])` | `void` | | `disable` | `disable(args: any[])` | `void` | | `engine` | `engine(args: any[])` | `void` | | `useStaticAssets` | `useStaticAssets(path: string, options: ServeStaticOptions)` | `void` | | `setBaseViewsDir` | `setBaseViewsDir(path: string | string[])` | `void` | | `setViewEngine` | `setViewEngine(engine: string)` | `void` | | `getRequestHostname` | `getRequestHostname(request: any)` | `string` | | `getRequestMethod` | `getRequestMethod(request: any)` | `string` | | `getRequestUrl` | `getRequestUrl(request: any)` | `string` | | `enableCors` | `enableCors(options: CorsOptions | CorsOptionsDelegate)` | `void` | | `createMiddlewareFactory` | `createMiddlewareFactory(requestMethod: RequestMethod)` | `(path: string, callback: Function) => any` | | `initHttpServer` | `initHttpServer(options: NestApplicationOptions)` | `void` | | `registerParserMiddleware` | `registerParserMiddleware(prefix: string, rawBody: boolean)` | `void` | | `useBodyParser` | `useBodyParser(type: NestExpressBodyParserType, rawBody: boolean, options: Omit)` | `this` | | `setLocal` | `setLocal(key: string, value: any)` | `void` | | `getType` | `getType()` | `string` | | `applyVersionFilter` | `applyVersionFilter(handler: Function, version: VersionValue, versioningOptions: VersioningOptions)` | `VersionedRoute` | ## Where it refuses work - `ExpressAdapter` stops the work with `InternalServerErrorException` when `!next` — “HTTP adapter does not support filtering on version”. - `ExpressAdapter` stops the work with an early return when `version.includes(VERSION_NEUTRAL)`, in 2 places. - `ExpressAdapter` stops the work with an early return when `isNil(body)`. - `ExpressAdapter` stops the work with an early return when `!this.httpServer`. - `ExpressAdapter` stops the work with an early return when `options && options.prefix`. - `ExpressAdapter` stops the work with an early return when `Array.isArray(extractedVersion) && version.filter(v => extractedVersion.includes(v as str…`. ## When something fails - `ExpressAdapter` handles failure in 2 places: it lets it reach the caller in all 2. ## Diagram ```mermaid graph LR Client[HTTP Client] --> Express[Express Application] Express --> Adapter[ExpressAdapter] Adapter --> RequestHook[Request Hook] Adapter --> Route[Route Handler] Route --> ResponseHelpers[reply / status / render / redirect / end] Adapter --> ResponseHook[Response Hook] Adapter --> ErrorHandler[Error Handler] Adapter --> NotFoundHandler[Not Found Handler] ``` ## Usage ```ts import express from 'express'; import { ExpressAdapter } from '@nestjs/platform-express'; const server = express(); const adapter = new ExpressAdapter(server); adapter.setOnRequestHook((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); adapter.setOnResponseHook((req, res, next) => { res.on('finish', () => { console.log(`Response completed with ${res.statusCode}`); }); next(); }); server.get('/health', (_req, res) => { adapter.reply(res, { status: 'ok' }, 200); }); server.get('/dashboard', (_req, res) => { adapter.render(res, 'dashboard', { title: 'Dashboard' }); }); adapter.setNotFoundHandler((req, res) => { adapter.status(res, 404); adapter.reply(res, { message: `Route not found: ${req.url}` }, 404); }); adapter.setErrorHandler((error, _req, res, _next) => { console.error(error); if (!adapter.isHeadersSent(res)) { adapter.reply(res, { message: 'Internal server error' }, 500); } }); server.listen(3000); ``` ## AI Coding Instructions - Use adapter response helpers such as `reply()`, `status()`, `redirect()`, and `end()` instead of directly coupling shared platform code to Express response APIs. - Register request and response hooks early, before routes or framework initialization, so they apply consistently to all requests. - Check `isHeadersSent(response)` before writing an error response to prevent duplicate headers or response-write errors. - Ensure custom error and not-found handlers terminate the response and preserve Express middleware signatures. - Keep Express-specific middleware and view-engine configuration at the platform boundary; application logic should remain adapter-agnostic. ## How it works `ExpressAdapter` is a public class that extends Nest’s `AbstractHttpAdapter` with an Express application instance and an HTTP or HTTPS Node server type. Its constructor accepts an optional application instance; otherwise it creates one with `express()`. [packages/platform-express/adapters/express-adapter.ts:48-53] [packages/platform-express/adapters/express-adapter.ts:67-82] ## Relationships - IMPORTS → `HttpStatus` - IMPORTS → `InternalServerErrorException` - IMPORTS → `Logger` - IMPORTS → `RequestMethod` - IMPORTS → `StreamableFile` - IMPORTS → `VERSION_NEUTRAL` - IMPORTS → `VersioningOptions` - IMPORTS → `VersioningType` - IMPORTS → `VersionValue` - IMPORTS → `CorsOptions` - IMPORTS → `CorsOptionsDelegate` - IMPORTS → `NestApplicationOptions` - IMPORTS → `isFunction` - IMPORTS → `isNil` - IMPORTS → `isObject` - IMPORTS → `isString` - IMPORTS → `isUndefined` - IMPORTS → `AbstractHttpAdapter` - IMPORTS → `RouterMethodFactory` - IMPORTS → `LegacyRouteConverter` # FileInterceptor **Kind:** Function **Source:** [`packages/platform-express/multer/interceptors/file.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interceptors/file.interceptor.ts#L25) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function FileInterceptor(fieldName: string, localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `fieldName` | `string` | | `localOptions` | `MulterOptions` | **Returns:** `Type` ## Relationships - IMPORTS → `CallHandler` - IMPORTS → `ExecutionContext` - IMPORTS → `Inject` - IMPORTS → `mixin` - IMPORTS → `NestInterceptor` - IMPORTS → `Optional` - IMPORTS → `Type` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `AppController` — `sample/29-file-upload/src/app.controller.ts`:15 # FilesInterceptor **Kind:** Function **Source:** [`packages/platform-express/multer/interceptors/files.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interceptors/files.interceptor.ts#L27) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function FilesInterceptor(fieldName: string, maxCount: number, localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `fieldName` | `string` | | `maxCount` | `number` | | `localOptions` | `MulterOptions` | **Returns:** `Type` ## Relationships - IMPORTS → `CallHandler` - IMPORTS → `ExecutionContext` - IMPORTS → `Inject` - IMPORTS → `mixin` - IMPORTS → `NestInterceptor` - IMPORTS → `Optional` - IMPORTS → `Type` # FileFieldsInterceptor **Kind:** Function **Source:** [`packages/platform-express/multer/interceptors/file-fields.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interceptors/file-fields.interceptor.ts#L27) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function FileFieldsInterceptor(uploadFields: MulterField[], localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `uploadFields` | `MulterField[]` | | `localOptions` | `MulterOptions` | **Returns:** `Type` ## Relationships - IMPORTS → `CallHandler` - IMPORTS → `ExecutionContext` - IMPORTS → `Inject` - IMPORTS → `mixin` - IMPORTS → `NestInterceptor` - IMPORTS → `Optional` - IMPORTS → `Type` # AnyFilesInterceptor **Kind:** Function **Source:** [`packages/platform-express/multer/interceptors/any-files.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interceptors/any-files.interceptor.ts#L24) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function AnyFilesInterceptor(localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `localOptions` | `MulterOptions` | **Returns:** `Type` ## Relationships - IMPORTS → `CallHandler` - IMPORTS → `ExecutionContext` - IMPORTS → `Inject` - IMPORTS → `mixin` - IMPORTS → `NestInterceptor` - IMPORTS → `Optional` - IMPORTS → `Type` # getBodyParserOptions **Kind:** Function **Source:** [`packages/platform-express/adapters/utils/get-body-parser-options.util.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/adapters/utils/get-body-parser-options.util.ts#L16) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function getBodyParserOptions(rawBody: boolean, options: Omit): Options ``` ## Parameters | Name | Type | |---|---| | `rawBody` | `boolean` | | `options` | `Omit` | **Returns:** `Options` # NoFilesInterceptor **Kind:** Function **Source:** [`packages/platform-express/multer/interceptors/no-files.interceptor.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interceptors/no-files.interceptor.ts#L24) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function NoFilesInterceptor(localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `localOptions` | `MulterOptions` | **Returns:** `Type` ## Relationships - IMPORTS → `CallHandler` - IMPORTS → `ExecutionContext` - IMPORTS → `Inject` - IMPORTS → `mixin` - IMPORTS → `NestInterceptor` - IMPORTS → `Optional` - IMPORTS → `Type` # transformException **Kind:** Function **Source:** [`packages/platform-express/multer/multer/multer.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/multer/multer.utils.ts#L10) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Signature ```ts function transformException(error: (Error & { field?: string }) | undefined) ``` ## Parameters | Name | Type | |---|---| | `error` | `(Error & { field?: string }) | undefined` | ## Relationships - IMPORTS → `BadRequestException` - IMPORTS → `HttpException` - IMPORTS → `PayloadTooLargeException` # NestExpressApplication **Kind:** Interface **Source:** [`packages/platform-express/interfaces/nest-express-application.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/interfaces/nest-express-application.interface.ts#L20) **Part of:** [Platform Express](subsystem-packages-platform-express) Interface describing methods on NestExpressApplication. `NestExpressApplication` extends Nest’s standard application contract with Express-specific configuration APIs. Use it when an application needs Express features such as template engines, static asset serving, custom body parsers, and Express locals. ## Diagram ```mermaid graph LR A[NestFactory.create] --> B[NestExpressApplication] B --> C[Configure views] B --> D[Serve static assets] B --> E[Configure body parsers] B --> F[Set Express locals] B --> G[listen()] G --> H[Express HTTP server] ``` ## Usage ```ts import { join } from 'node:path'; import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.setBaseViewsDir(join(__dirname, '..', 'views')); app.setViewEngine('hbs'); app.setStaticAssets(join(__dirname, '..', 'public')); app.setLocal('appName', 'My Nest App'); app.useBodyParser('json', { limit: '2mb' }); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Create the application with `NestFactory.create()` when Express-specific methods are required. - Configure view directories and the template engine before starting the server with `listen()`. - Use `setStaticAssets()` for public files instead of implementing static-file routes manually. - Prefer `useBodyParser()` when custom parser limits or parser options are needed; ensure the selected parser matches the incoming content type. - Keep Express-specific configuration in the bootstrap layer so application modules remain transport-agnostic. ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `INestApplication` # ServeStaticOptions **Kind:** Interface **Source:** [`packages/platform-express/interfaces/serve-static-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/interfaces/serve-static-options.interface.ts#L9) **Part of:** [Platform Express](subsystem-packages-platform-express) Interface describing options for serving static assets. `ServeStaticOptions` configures how static assets are served by the Express platform integration. It controls cache behavior, index-file resolution, redirects, dotfile access, extension handling, and custom response headers when using static file middleware. ## Properties | Property | Type | |---|---| | `dotfiles` | `string` | | `etag` | `boolean` | | `extensions` | `string[]` | | `fallthrough` | `boolean` | | `immutable` | `boolean` | | `index` | `boolean | string | string[]` | | `lastModified` | `boolean` | | `maxAge` | `number | string` | | `redirect` | `boolean` | | `setHeaders` | `(res: any, path: string, stat: any) => any` | | `prefix` | `string` | ## Diagram ```mermaid graph LR A[Static asset request] --> B[ServeStaticOptions] B --> C[File resolution] B --> D[Cache headers] B --> E[Redirect and fallthrough behavior] B --> F[Custom setHeaders callback] C --> G[HTTP response] D --> G E --> G F --> G ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import { join } from 'path'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..', 'public'), { maxAge: '1d', etag: true, lastModified: true, index: ['index.html'], extensions: ['html'], fallthrough: true, redirect: true, immutable: false, dotfiles: 'ignore', setHeaders(res, path, stat) { if (path.endsWith('.css') || path.endsWith('.js')) { res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); } }, }); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Pass `ServeStaticOptions` to `NestExpressApplication.useStaticAssets()` when configuring Express-hosted static directories. - Use `maxAge`, `etag`, `lastModified`, and `immutable` together to define a consistent browser and CDN caching strategy. - Keep `dotfiles` restrictive unless hidden files must be publicly accessible; prefer `'ignore'` or `'deny'` over serving them. - Enable `fallthrough` when unresolved static requests should continue to Nest controllers or other middleware. - Use `setHeaders` for asset-specific headers, but avoid overriding cache headers inconsistently across related file types. # MulterOptions **Kind:** Interface **Source:** [`packages/platform-express/multer/interfaces/multer-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interfaces/multer-options.interface.ts#L6) **Part of:** [Platform Express](subsystem-packages-platform-express) `MulterOptions` configures how NestJS's Express platform integrates with Multer for handling `multipart/form-data` uploads. It controls upload destinations, storage engines, upload limits, path preservation, and the default character set used when parsing form data. ## Properties | Property | Type | |---|---| | `dest` | `string | Function` | | `storage` | `any` | | `limits` | `{ fieldNameSize?: number; fieldSize?: number; fields?: number; fileSize?: number; files?: number; parts?: number; headerPairs?: number; }` | | `preservePath` | `boolean` | | `defParamCharset` | `string` | ## Diagram ```mermaid graph LR Client[Multipart Request] --> Interceptor[File Upload Interceptor] Interceptor --> Options[MulterOptions] Options --> Storage[storage or dest] Options --> Limits[limits] Options --> Parsing[preservePath and defParamCharset] Storage --> Files[Stored Uploaded Files] Limits --> Validation[Upload Constraints] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import type { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface'; const multerOptions: MulterOptions = { storage: diskStorage({ destination: './uploads', filename: (_request, file, callback) => { callback(null, `${Date.now()}-${file.originalname}`); }, }), limits: { fileSize: 5 * 1024 * 1024, // 5 MB files: 3, }, preservePath: false, defParamCharset: 'utf8', }; @Module({ imports: [MulterModule.register(multerOptions)], }) export class AppModule {} ``` ## AI Coding Instructions - Prefer `storage` with a Multer storage engine when filename generation or destination handling requires custom behavior. - Use `dest` only for simple disk-based uploads; do not configure both `dest` and a custom `storage` engine unless the underlying Multer behavior is explicitly intended. - Always define `limits`, especially `fileSize` and `files`, to prevent excessive resource consumption from upload requests. - Keep `preservePath` disabled unless preserving client-provided directory paths is required and has been reviewed for security implications. - Configure these options through `MulterModule.register()` globally or `MulterModule.registerAsync()` when settings depend on injected configuration. # NestExpressBodyParserOptions **Kind:** Interface **Source:** [`packages/platform-express/interfaces/nest-express-body-parser-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/interfaces/nest-express-body-parser-options.interface.ts#L8) **Part of:** [Platform Express](subsystem-packages-platform-express) Type alias to keep compatibility with `NestExpressBodyParserOptions` defines the supported configuration for body parsing in the NestJS Express platform. It mirrors the relevant Express/body-parser options to preserve compatibility when configuring how incoming request bodies are inflated, size-limited, and matched by content type. ## Properties | Property | Type | |---|---| | `inflate` | `boolean | undefined` | | `limit` | `number | string | undefined` | | `type` | `string | string[] | ((req: IncomingMessage) => any) | undefined` | ## Diagram ```mermaid graph LR A[NestExpressBodyParserOptions] --> B[inflate] A --> C[limit] A --> D[type] B --> B1[Enable or disable compressed body inflation] C --> C1[Maximum accepted request body size] D --> D1[Content type string, array, or request predicate] A --> E[Express body parser configuration] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import type { NestExpressBodyParserOptions } from '@nestjs/platform-express'; async function bootstrap() { const bodyParserOptions: NestExpressBodyParserOptions = { inflate: true, limit: '2mb', type: ['application/json', 'application/*+json'], }; const app = await NestFactory.create(AppModule, { bodyParser: false, }); app.useBodyParser('json', bodyParserOptions); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Use this interface when passing body-parser-compatible options to Nest's Express platform APIs, such as `app.useBodyParser()`. - Set `limit` to a conservative value (for example, `'1mb'` or `'2mb'`) to reduce the risk of oversized request payloads. - Use `type` to restrict parsing to expected content types; a predicate receives the Node.js `IncomingMessage`. - Keep `inflate` enabled unless the application explicitly needs to reject compressed request bodies. - Do not assume these options apply to every parser type; ensure the selected parser and Express integration support the configured behavior. # multerExceptions **Kind:** Constant **Source:** [`packages/platform-express/multer/multer/multer.constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/multer/multer.constants.ts#L1) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Definition ```ts { // from https://github.com/expressjs/multer/blob/master/lib/multer-error.js LIMIT_PART_COUNT: 'Too many parts', LIMIT_FILE_SIZE: 'File too large', LIMIT_FILE_COUNT: 'Too many files', LIMIT_FIELD_KEY: 'Field name too long', LIMIT_FIELD_VALUE: 'Field value too long', LIMIT_FIELD_COUNT: 'Too many fields', LIMIT_UNEXPECTED_FILE: 'Unexpected field', MISSING_FIELD_NAME: 'Field name m… ``` ## Value ```ts { // from https://github.com/expressjs/multer/blob/master/lib/multer-error.js LIMIT_PART_COUNT: 'Too many parts', LIMIT_FILE_SIZE: 'File too large', LIMIT_FILE_COUNT: 'Too many files', LIMIT_FIELD_KEY: 'Field name too long', LIMIT_FIELD_VALUE: 'Field value too long', LIMIT_FIELD_COUNT: 'Too many fields', LIMIT_UNEXPECTED_FILE: 'Unexpected field', MISSING_FIELD_NAME: 'Field name m… ``` # MulterModuleAsyncOptions **Kind:** Interface **Source:** [`packages/platform-express/multer/interfaces/files-upload-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L16) **Part of:** [Platform Express](subsystem-packages-platform-express) `MulterModuleAsyncOptions` configures Multer asynchronously when registering NestJS file upload support. It allows upload options to be provided by an existing provider, a dedicated options factory class, or an inline factory function with dependency injection. ## Properties | Property | Type | |---|---| | `useExisting` | `Type` | | `useClass` | `Type` | | `useFactory` | `( ...args: any[] ) => Promise | MulterModuleOptions` | | `inject` | `any[]` | ## Diagram ```mermaid graph LR A[MulterModuleAsyncOptions] --> B[useExisting] A --> C[useClass] A --> D[useFactory] A --> E[inject] B --> F[MulterOptionsFactory] C --> F D --> G[MulterModuleOptions] E --> D F --> G G --> H[MulterModule.registerAsync] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { MulterModule, MulterModuleAsyncOptions, MulterOptionsFactory, } from '@nestjs/platform-express'; import { ConfigService } from '@nestjs/config'; import { diskStorage } from 'multer'; const multerOptions: MulterModuleAsyncOptions = { inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ storage: diskStorage({ destination: configService.get('UPLOAD_DIRECTORY', './uploads'), filename: (_request, file, callback) => { callback(null, `${Date.now()}-${file.originalname}`); }, }), limits: { fileSize: 5 * 1024 * 1024, }, }), }; @Module({ imports: [MulterModule.registerAsync(multerOptions)], }) export class AppModule {} ``` ## AI Coding Instructions - Use exactly one configuration strategy: `useExisting`, `useClass`, or `useFactory`. - Add required dependencies to `inject` when using `useFactory`; their order must match the factory function parameters. - Return a valid `MulterModuleOptions` object from the factory, either synchronously or as a `Promise`. - Prefer `useExisting` when an existing `MulterOptionsFactory` provider should be reused; use `useClass` when Nest should create a dedicated factory provider. - Configure storage, file-size limits, and file filtering in the returned Multer options rather than directly in controllers. ## How it works `MulterModuleAsyncOptions` is the public TypeScript configuration shape accepted by `MulterModule.registerAsync()`. It extends only the `imports` member of `ModuleMetadata`; its remaining members select how the module resolves `MulterModuleOptions`. `MulterModuleOptions` is an alias for `MulterOptions`. [files-upload-module.interface.ts:4](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L4) [files-upload-module.interface.ts:16-25](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L16-L25) [multer.module.ts:30](packages/platform-express/multer/multer.module.ts#L30) - `imports` is optional through the inherited `ModuleMetadata.imports` member and is copied to the dynamic module’s `imports` field. [files-upload-module.interface.ts:16-19](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L16-L19) [multer.module.ts:31-34](packages/platform-express/multer/multer.module.ts#L31-L34) - `useFactory` may be a function with arbitrary injected arguments that returns `MulterModuleOptions` directly or as a promise. When present, it becomes the factory for the `MULTER_MODULE_OPTIONS` provider. [files-upload-module.interface.ts:22-25](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L22-L25) [multer.module.ts:63-68](packages/platform-express/multer/multer.module.ts#L63-L68) - `inject` supplies that factory’s dependency tokens. When `useFactory` is selected and `inject` is absent, the module uses an empty array. [files-upload-module.interface.ts:25](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L25) [multer.module.ts:63-68](packages/platform-express/multer/multer.module.ts#L63-L68) - `useExisting` names an existing class-type token for a `MulterOptionsFactory`. The options provider injects that token and calls its `createMulterOptions()` method. That method may return options directly or asynchronously. [files-upload-module.interface.ts:9-11](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L9-L11) [files-upload-module.interface.ts:20](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L20) [multer.module.ts:70-75](packages/platform-express/multer/multer.module.ts#L70-L75) - `useClass` names a class-type `MulterOptionsFactory`. In the absence of `useExisting` and `useFactory`, the module registers the class as a provider, injects it into the options provider, and calls `createMulterOptions()`. [files-upload-module.interface.ts:9-11](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L9-L11) [files-upload-module.interface.ts:21](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L21) [multer.module.ts:48-57](packages/platform-express/multer/multer.module.ts#L48-L57) [multer.module.ts:70-75](packages/platform-express/multer/multer.module.ts#L70-L75) `useFactory` takes precedence when it is set: the options-provider construction checks it first. A set `useExisting` also prevents registration of `useClass`; the injected factory token then selects `useExisting` before `useClass`. [multer.module.ts:48-49](packages/platform-express/multer/multer.module.ts#L48-L49) [multer.module.ts:63-75](packages/platform-express/multer/multer.module.ts#L63-L75) All members declared directly by this interface are optional, and the visible implementation contains no explicit validation or thrown error for a configuration with none of `useFactory`, `useExisting`, or `useClass`. In that case, its class branch constructs a provider whose token and injection entry are `undefined`. [files-upload-module.interface.ts:20-25](packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L20-L25) [multer.module.ts:48-57](packages/platform-express/multer/multer.module.ts#L48-L57) [multer.module.ts:70-75](packages/platform-express/multer/multer.module.ts#L70-L75) Calling `registerAsync` constructs a dynamic module that exports `MULTER_MODULE_OPTIONS` and adds a generated `MULTER_MODULE_ID` value provider. [multer.module.ts:30-42](packages/platform-express/multer/multer.module.ts#L30-L42) # busboyExceptions **Kind:** Constant **Source:** [`packages/platform-express/multer/multer/multer.constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/multer/multer.constants.ts#L14) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Definition ```ts { // from https://github.com/mscdex/busboy/blob/master/lib/types/multipart.js MULTIPART_BOUNDARY_NOT_FOUND: 'Multipart: Boundary not found', MULTIPART_MALFORMED_PART_HEADER: 'Malformed part header', MULTIPART_UNEXPECTED_END_OF_FORM: 'Unexpected end of form', MULTIPART_UNEXPECTED_END_OF_FILE: 'Unexpected end of file', } ``` ## Value ```ts { // from https://github.com/mscdex/busboy/blob/master/lib/types/multipart.js MULTIPART_BOUNDARY_NOT_FOUND: 'Multipart: Boundary not found', MULTIPART_MALFORMED_PART_HEADER: 'Malformed part header', MULTIPART_UNEXPECTED_END_OF_FORM: 'Unexpected end of form', MULTIPART_UNEXPECTED_END_OF_FILE: 'Unexpected end of file', } ``` # MulterField **Kind:** Interface **Source:** [`packages/platform-express/multer/interfaces/multer-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interfaces/multer-options.interface.ts#L66) **Part of:** [Platform Express](subsystem-packages-platform-express) `MulterField` defines a named multipart form-data field accepted by NestJS's Multer integration. It is typically used when configuring file upload interceptors that accept multiple named file fields, with `maxCount` limiting how many files each field may contain. ## Properties | Property | Type | |---|---| | `name` | `string` | | `maxCount` | `number` | ## Diagram ```mermaid graph LR Client[Multipart Request] --> Interceptor[FileFieldsInterceptor] Interceptor --> Field[MulterField] Field --> Name["name: field identifier"] Field --> MaxCount["maxCount: maximum files"] Interceptor --> Uploads[Uploaded file arrays] ``` ## Usage ```ts import { Controller, Post, UploadedFiles, UseInterceptors } from '@nestjs/common'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import type { MulterField } from '@nestjs/platform-express/multer/interfaces/multer-options.interface'; const uploadFields: MulterField[] = [ { name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: 5 }, ]; @Controller('uploads') export class UploadController { @Post() @UseInterceptors(FileFieldsInterceptor(uploadFields)) uploadFiles( @UploadedFiles() files: { avatar?: Express.Multer.File[]; documents?: Express.Multer.File[]; }, ) { return { avatar: files.avatar?.[0], documents: files.documents ?? [], }; } } ``` ## AI Coding Instructions - Use `name` values that exactly match the multipart form field names sent by clients. - Set `maxCount` to the intended per-field upload limit; use `1` for single-file fields. - Pass `MulterField[]` to `FileFieldsInterceptor` when an endpoint accepts several differently named file fields. - Remember that uploaded files are returned as arrays per field, including fields configured with `maxCount: 1`. - Configure Multer validation, storage, and file-size limits separately through interceptor options or module configuration. # MulterOptionsFactory **Kind:** Interface **Source:** [`packages/platform-express/multer/interfaces/files-upload-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L9) **Part of:** [Platform Express](subsystem-packages-platform-express) # MULTER_MODULE_ID **Kind:** Constant **Source:** [`packages/platform-express/multer/multer.constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/multer.constants.ts#L1) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Definition ```ts 'MULTER_MODULE_ID' ``` ## Value ```ts 'MULTER_MODULE_ID' ``` # MULTER_MODULE_OPTIONS **Kind:** Constant **Source:** [`packages/platform-express/multer/files.constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/files.constants.ts#L1) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Definition ```ts 'MULTER_MODULE_OPTIONS' ``` ## Value ```ts 'MULTER_MODULE_OPTIONS' ``` # MulterModuleOptions **Kind:** Type **Source:** [`packages/platform-express/multer/interfaces/files-upload-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interfaces/files-upload-module.interface.ts#L4) **Part of:** [Platform Express](subsystem-packages-platform-express) ## Definition ```ts MulterOptions ``` ## Relationships - IMPORTS → `ModuleMetadata` - IMPORTS → `Type` # NestExpressBodyParserType **Kind:** Type **Source:** [`packages/platform-express/interfaces/nest-express-body-parser.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-express/interfaces/nest-express-body-parser.interface.ts#L4) **Part of:** [Platform Express](subsystem-packages-platform-express) Interface defining possible body parser types, to be used with `NestExpressApplication.useBodyParser()`. `NestExpressBodyParserType` defines the supported body parser names accepted by `NestExpressApplication.useBodyParser()`. It lets Express-based Nest applications configure how incoming request bodies are parsed, including JSON, URL-encoded form data, raw buffers, and plain text. ## Definition ```ts 'json' | 'urlencoded' | 'text' | 'raw' ``` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[NestExpressApplication.useBodyParser] B --> C{NestExpressBodyParserType} C --> D[json] C --> E[urlencoded] C --> F[raw] C --> G[text] D --> H[Parsed request body] E --> H F --> H G --> H ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import type { NestExpressApplication } from '@nestjs/platform-express'; async function bootstrap() { const app = await NestFactory.create(AppModule); const parserType: 'json' = 'json'; app.useBodyParser(parserType, { limit: '10mb', }); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Use this type only with `NestExpressApplication.useBodyParser()` in applications running on the Express platform. - Choose `json` for JSON APIs, `urlencoded` for HTML form submissions, `raw` for buffer-based payloads such as webhook signatures, and `text` for plain-text requests. - Configure parsers before starting the application with `app.listen()` so request handling uses the intended parser configuration. - Avoid registering conflicting body parsers for the same content type, especially when validating raw webhook payload signatures. - Keep parser options compatible with Express/body-parser options, such as `limit`, `type`, and `extended` for URL-encoded payloads. # FastifyAdapter **Kind:** Class **Source:** [`packages/platform-fastify/adapters/fastify-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/adapters/fastify-adapter.ts#L124) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) `FastifyAdapter` bridges the framework’s HTTP abstractions to a Fastify server instance. It initializes the Fastify application, registers request/response lifecycle hooks, exposes common HTTP route methods, and starts the server through overloaded `listen()` methods. **Extends:** `AbstractHttpAdapter` ## Methods | Method | Signature | Returns | |---|---|---| | `setOnRequestHook` | `setOnRequestHook(hook: ( request: TRequest, reply: TReply, done: (err?: Error) => void, ) => void | Promise)` | `void` | | `setOnResponseHook` | `setOnResponseHook(hook: ( request: TRequest, reply: TReply, done: (err?: Error) => void, ) => void | Promise)` | `void` | | `init` | `init()` | `void` | | `listen` | `listen(port: string | number, callback: () => void)` | `void` | | `listen` | `listen(port: string | number, hostname: string, callback: () => void)` | `void` | | `listen` | `listen(listenOptions: string | number | FastifyListenOptions, args: any[])` | `void` | | `get` | `get(args: any[])` | `void` | | `post` | `post(args: any[])` | `void` | | `head` | `head(args: any[])` | `void` | | `delete` | `delete(args: any[])` | `void` | | `put` | `put(args: any[])` | `void` | | `patch` | `patch(args: any[])` | `void` | | `options` | `options(args: any[])` | `void` | | `search` | `search(args: any[])` | `void` | | `propfind` | `propfind(args: any[])` | `void` | | `proppatch` | `proppatch(args: any[])` | `void` | | `mkcol` | `mkcol(args: any[])` | `void` | | `copy` | `copy(args: any[])` | `void` | | `move` | `move(args: any[])` | `void` | | `lock` | `lock(args: any[])` | `void` | | `unlock` | `unlock(args: any[])` | `void` | | `applyVersionFilter` | `applyVersionFilter(handler: Function, version: VersionValue, versioningOptions: VersioningOptions)` | `VersionedRoute` | | `reply` | `reply(response: TRawResponse | TReply, body: any, statusCode: number)` | `void` | | `status` | `status(response: TRawResponse | TReply, statusCode: number)` | `void` | | `end` | `end(response: TReply, message: string)` | `void` | | `render` | `render(response: TReply & { view: Function }, view: string, options: any)` | `void` | | `redirect` | `redirect(response: TReply, statusCode: number, url: string)` | `void` | | `setErrorHandler` | `setErrorHandler(handler: Parameters[0])` | `void` | | `setNotFoundHandler` | `setNotFoundHandler(handler: Function)` | `void` | | `getHttpServer` | `getHttpServer()` | `T` | | `getInstance` | `getInstance()` | `T` | | `register` | `register(plugin: TRegister['0'], opts: TRegister['1'])` | `void` | | `inject` | `inject()` | `LightMyRequestChain` | | `inject` | `inject(opts: InjectOptions | string)` | `Promise` | | `inject` | `inject(opts: InjectOptions | string)` | `LightMyRequestChain | Promise` | | `close` | `close()` | `void` | | `initHttpServer` | `initHttpServer()` | `void` | | `useStaticAssets` | `useStaticAssets(options: FastifyStaticOptions)` | `void` | | `setViewEngine` | `setViewEngine(options: FastifyViewOptions | string)` | `void` | | `isHeadersSent` | `isHeadersSent(response: TReply)` | `boolean` | | `getHeader` | `getHeader(response: any, name: string)` | `void` | | `setHeader` | `setHeader(response: TReply, name: string, value: string)` | `void` | | `appendHeader` | `appendHeader(response: any, name: string, value: string)` | `void` | | `getRequestHostname` | `getRequestHostname(request: TRequest)` | `string` | | `getRequestMethod` | `getRequestMethod(request: TRequest)` | `string` | | `getRequestUrl` | `getRequestUrl(request: TRequest)` | `string` | | `getRequestUrl` | `getRequestUrl(request: TRawRequest)` | `string` | | `getRequestUrl` | `getRequestUrl(request: TRequest & TRawRequest)` | `string` | | `enableCors` | `enableCors(options: FastifyCorsOptions)` | `void` | | `registerParserMiddleware` | `registerParserMiddleware(prefix: string, rawBody: boolean)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `instance` | `TInstance` | | `_pathPrefix` | `string` | ## Where it refuses work - `FastifyAdapter` stops the work with `Error` when `!isString(value) && !Array.isArray(value)` — “Version constraint should be a string or an array of strings.”. - `FastifyAdapter` stops the work with an early return when `Array.isArray(version)`. - `FastifyAdapter` stops the work with an early return when `this.versioningOptions?.type === VersioningType.CUSTOM`. - `FastifyAdapter` stops the work with an early return when `this.isMiddieRegistered`. - `FastifyAdapter` stops the work with an early return when `err.code !== 'ERR_SERVER_NOT_RUNNING'`. - `FastifyAdapter` stops the work with an early return when `this._isParserRegistered`. ## When something fails - `FastifyAdapter` handles failure in 2 places: it lets it reach the caller in all 2. ## Diagram ```mermaid graph LR App[Application] --> Adapter[FastifyAdapter] Adapter --> Hooks[Request / Response Hooks] Adapter --> Routes[GET / POST / HEAD / DELETE Routes] Adapter --> Fastify[Fastify Server] Fastify --> Client[HTTP Clients] ``` ## Usage ```ts import { FastifyAdapter } from '@platform-fastify/adapters/fastify-adapter'; const adapter = new FastifyAdapter(); adapter.setOnRequestHook(async (request, reply) => { request.log.info({ url: request.url }, 'Incoming request'); // Example authentication guard if (request.headers['x-api-key'] !== process.env.API_KEY) { return reply.code(401).send({ message: 'Unauthorized' }); } }); adapter.setOnResponseHook(async (request, reply) => { request.log.info( { url: request.url, statusCode: reply.statusCode }, 'Response sent', ); }); adapter.get('/health', async () => { return { status: 'ok' }; }); adapter.post('/users', async (request, reply) => { const user = request.body; reply.code(201); return { user }; }); await adapter.init(); adapter.listen(3000); ``` ## AI Coding Instructions - Register lifecycle hooks with `setOnRequestHook()` and `setOnResponseHook()` before calling `init()` or `listen()`. - Use the adapter’s route helpers (`get`, `post`, `head`, and `delete`) instead of registering routes directly on the underlying Fastify instance when working within the abstraction. - Ensure handlers return serializable response values or explicitly send a response through Fastify’s reply object. - Call `init()` before starting the server when initialization is not handled automatically by the surrounding application bootstrap. - Preserve Fastify request/reply semantics in hooks and route handlers, including returning early after sending an error response. ## Relationships - IMPORTS → `HttpStatus` - IMPORTS → `Logger` - IMPORTS → `RawBodyRequest` - IMPORTS → `RequestMethod` - IMPORTS → `StreamableFile` - IMPORTS → `VERSION_NEUTRAL` - IMPORTS → `VersioningOptions` - IMPORTS → `VersioningType` - IMPORTS → `VersionValue` - IMPORTS → `loadPackage` - IMPORTS → `isString` - IMPORTS → `isUndefined` - IMPORTS → `AbstractHttpAdapter` - IMPORTS → `LegacyRouteConverter` # NestFastifyApplication **Kind:** Interface **Source:** [`packages/platform-fastify/interfaces/nest-fastify-application.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/interfaces/nest-fastify-application.interface.ts#L27) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `INestApplication` # FastifyStaticOptions **Kind:** Interface **Source:** [`packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L73) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) `FastifyStaticOptions` configures static asset serving for the Fastify platform adapter. It controls the asset root directory, URL prefix, reply decoration, caching headers, redirects, directory listings, and wildcard route behavior when registering static-file support. ## Properties | Property | Type | |---|---| | `root` | `string | string[] | URL | URL[]` | | `prefix` | `string` | | `prefixAvoidTrailingSlash` | `boolean` | | `serve` | `boolean` | | `decorateReply` | `boolean` | | `schemaHide` | `boolean` | | `setHeaders` | `(res: SetHeadersResponse, path: string, stat: Stats) => void` | | `redirect` | `boolean` | | `wildcard` | `boolean` | | `list` | `boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat` | | `allowedPath` | `( pathName: string, root: string, request: FastifyRequest, ) => boolean` | | `preCompressed` | `boolean` | | `acceptRanges` | `boolean` | | `cacheControl` | `boolean` | | `dotfiles` | `'allow' | 'deny' | 'ignore'` | | `etag` | `boolean` | | `extensions` | `string[]` | | `immutable` | `boolean` | | `index` | `string[] | string | false` | | `lastModified` | `boolean` | | `maxAge` | `string | number` | | `constraints` | `RouteOptions['constraints']` | ## Diagram ```mermaid graph LR A[FastifyStaticOptions] --> B[root] A --> C[prefix] A --> D[Serving behavior] A --> E[Response behavior] A --> F[Directory listing] D --> D1[serve] D --> D2[redirect] D --> D3[wildcard] E --> E1[decorateReply] E --> E2[schemaHide] E --> E3[setHeaders] F --> F1[list] ``` ## Usage ```ts import { join } from 'node:path'; import type { FastifyStaticOptions } from './interfaces/external/fastify-static-options.interface'; const staticOptions: FastifyStaticOptions = { root: join(process.cwd(), 'public'), prefix: '/assets/', prefixAvoidTrailingSlash: false, serve: true, decorateReply: true, schemaHide: true, redirect: true, wildcard: true, list: false, setHeaders(res, path, stat) { if (path.endsWith('.js') || path.endsWith('.css')) { res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); } res.setHeader('Content-Length', stat.size); }, }; // Example: pass staticOptions when configuring Fastify static serving. ``` ## AI Coding Instructions - Use an absolute filesystem path for `root`; provide an array of roots only when serving assets from multiple locations. - Keep `prefix` aligned with application routing conventions, including whether a trailing slash is expected. - Use `setHeaders` for cache and content-related headers; avoid performing asynchronous work in this callback. - Disable `decorateReply` only if application code does not need Fastify reply helpers for static files. - Enable `list` only for controlled or development environments, as directory listings can expose file names and structure. # FastifyViewOptions **Kind:** Interface **Source:** [`packages/platform-fastify/interfaces/external/fastify-view-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/interfaces/external/fastify-view-options.interface.ts#L6) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) "fastify/view" interfaces `FastifyViewOptions` defines the configuration accepted by the Fastify view integration. It selects a template engine, identifies template locations, and configures rendering behavior such as layouts, caching, default context, and production settings. ## Properties | Property | Type | |---|---| | `engine` | `{ ejs?: any; eta?: any; nunjucks?: any; pug?: any; handlebars?: any; mustache?: any; 'art-template'?: any; twig?: any; liquid?: any; dot?: any; }` | | `templates` | `string | string[]` | | `includeViewExtension` | `boolean` | | `options` | `object` | | `charset` | `string` | | `maxCache` | `number` | | `production` | `boolean` | | `defaultContext` | `object` | | `layout` | `string` | | `root` | `string` | | `viewExt` | `string` | | `propertyName` | `string` | | `asyncProperyName` | `string` | ## Diagram ```mermaid graph LR A[FastifyViewOptions] --> B[engine] A --> C[templates / root] A --> D[Rendering options] A --> E[Cache and production settings] B --> B1[EJS] B --> B2[Eta] B --> B3[Nunjucks] B --> B4[Pug] B --> B5[Handlebars] B --> B6[Other supported engines] C --> C1[Template files or directories] D --> D1[layout] D --> D2[defaultContext] D --> D3[includeViewExtension] E --> E1[maxCache] E --> E2[production] E --> E3[charset] ``` ## Usage ```ts import fastify from 'fastify'; import fastifyView from '@fastify/view'; import ejs from 'ejs'; import type { FastifyViewOptions } from './interfaces/external/fastify-view-options.interface'; const app = fastify(); const viewOptions: FastifyViewOptions = { engine: { ejs, }, root: `${process.cwd()}/views`, templates: `${process.cwd()}/views`, layout: 'layouts/main.ejs', includeViewExtension: true, production: process.env.NODE_ENV === 'production', maxCache: 100, charset: 'utf-8', defaultContext: { applicationName: 'My Fastify App', }, options: {}, }; app.register(fastifyView, viewOptions); app.get('/', async (_request, reply) => { return reply.view('index.ejs', { title: 'Home', message: 'Welcome!', }); }); ``` ## AI Coding Instructions - Configure exactly one or more compatible engines under `engine`; ensure the corresponding template package is installed and imported. - Use `root` and/or `templates` to point to valid template directories or files accessible at runtime. - Keep `production` aligned with the deployment environment so template caching and reload behavior work as expected. - Use `defaultContext` only for shared template data; pass request-specific values through `reply.view()` instead. - When enabling `includeViewExtension`, consistently include template file extensions in view names and layout paths. # RouteConstraints **Kind:** Function **Source:** [`packages/platform-fastify/decorators/route-constraints.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/decorators/route-constraints.decorator.ts#L10) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Signature ```ts function RouteConstraints(config: RouteShorthandOptions['constraints']) ``` ## Parameters | Name | Type | |---|---| | `config` | `RouteShorthandOptions['constraints']` | ## Relationships - IMPORTS → `SetMetadata` # RouteConfig **Kind:** Function **Source:** [`packages/platform-fastify/decorators/route-config.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/decorators/route-config.decorator.ts#L9) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Signature ```ts function RouteConfig(config: any) ``` ## Parameters | Name | Type | |---|---| | `config` | `any` | ## Relationships - IMPORTS → `SetMetadata` # RouteSchema **Kind:** Function **Source:** [`packages/platform-fastify/decorators/route-schema.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/decorators/route-schema.decorator.ts#L14) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Signature ```ts function RouteSchema(schema: FastifySchema) ``` ## Parameters | Name | Type | |---|---| | `schema` | `FastifySchema` | ## Relationships - IMPORTS → `SetMetadata` # ListOptionsJsonFormat **Kind:** Interface **Source:** [`packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L48) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) `ListOptionsJsonFormat` configures directory listing output for the Fastify static file integration when JSON responses are required. It fixes the `format` discriminator to `'json'` and requires a `render` function that generates the listing response. ## Properties | Property | Type | |---|---| | `format` | `'json'` | | `render` | `ListRender` | ## Diagram ```mermaid graph LR A[Fastify Static Directory Listing] --> B[ListOptionsJsonFormat] B --> C[format: 'json'] B --> D[render: ListRender] D --> E[JSON Directory Listing Response] ``` ## Usage ```ts import type { ListOptionsJsonFormat } from './interfaces/external/fastify-static-options.interface'; const listOptions: ListOptionsJsonFormat = { format: 'json', render: (request, reply, files) => { return reply.send({ files: files.map((file) => ({ name: file.name, path: file.path, })), }); }, }; // Pass listOptions to the Fastify static plugin configuration. ``` ## AI Coding Instructions - Set `format` exactly to `'json'`; it acts as the discriminator for this listing configuration. - Always provide a `render` implementation compatible with the `ListRender` type. - Return or send a JSON-serializable response from `render`. - Use this interface only for directory listing behavior in the Fastify static integration. - Avoid mixing JSON-specific options with other listing format configurations. # MiddlewareFn **Kind:** Type **Source:** [`packages/platform-fastify/adapters/middie/fastify-middie.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/adapters/middie/fastify-middie.ts#L17) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Definition ```ts (req: Req, res: Res, next: (err?: unknown) => void) => void ``` # ListOptionsHtmlFormat **Kind:** Interface **Source:** [`packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L54) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) `ListOptionsHtmlFormat` configures directory listing output in HTML format for Fastify static file serving. It requires `format` to be the literal value `'html'` and provides a `render` function responsible for generating the HTML response content. ## Properties | Property | Type | |---|---| | `format` | `'html'` | | `render` | `ListRender` | ## Diagram ```mermaid graph LR A[Fastify Static Directory Listing] --> B[ListOptionsHtmlFormat] B --> C[format: 'html'] B --> D[render: ListRender] D --> E[Generated HTML Response] ``` ## Usage ```ts import type { ListOptionsHtmlFormat } from './interfaces/external/fastify-static-options.interface'; const directoryListingOptions: ListOptionsHtmlFormat = { format: 'html', render: (directories, files) => { const directoryItems = directories .map((directory) => `
  • ${directory.name}/
  • `) .join(''); const fileItems = files .map((file) => `
  • ${file.name}
  • `) .join(''); return ` Directory listing

    Files

      ${directoryItems}${fileItems}
    `; }, }; ``` ## AI Coding Instructions - Set `format` exactly to `'html'`; other values do not satisfy `ListOptionsHtmlFormat`. - Implement `render` using the `ListRender` signature expected by the Fastify static integration. - Escape file names, paths, and other dynamic values before inserting them into generated HTML. - Return complete, valid HTML when using this format so browsers can render the directory listing correctly. - Use this interface when configuring HTML directory listings rather than JSON or plain-text listing formats. # NestFastifyBodyParserOptions **Kind:** Type **Source:** [`packages/platform-fastify/interfaces/nest-fastify-body-parser-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/interfaces/nest-fastify-body-parser-options.interface.ts#L3) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Definition ```ts Omit< Parameters[1], 'parseAs' > ``` # FASTIFY_ROUTE_CONSTRAINTS_METADATA **Kind:** Constant **Source:** [`packages/platform-fastify/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/constants.ts#L2) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Definition ```ts '__fastify_route_constraints__' ``` ## Value ```ts '__fastify_route_constraints__' ``` # FASTIFY_ROUTE_CONFIG_METADATA **Kind:** Constant **Source:** [`packages/platform-fastify/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/constants.ts#L1) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Definition ```ts '__fastify_route_config__' ``` ## Value ```ts '__fastify_route_config__' ``` # FASTIFY_ROUTE_SCHEMA_METADATA **Kind:** Constant **Source:** [`packages/platform-fastify/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-fastify/constants.ts#L4) **Part of:** [Platform Fastify](subsystem-packages-platform-fastify) ## Definition ```ts '__fastify_route_schema__' ``` ## Value ```ts '__fastify_route_schema__' ``` # TestingModuleBuilder **Kind:** Class **Source:** [`packages/testing/testing-module.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-module.builder.ts#L37) **Part of:** [Testing](subsystem-packages-testing) `TestingModuleBuilder` configures and compiles a NestJS testing module before it is used in tests. It supports overriding providers, modules, guards, pipes, filters, and interceptors, configuring a custom logger, and supplying a mocker for unresolved dependencies. Calling `compile()` produces a `TestingModule` that can resolve and exercise application components in isolation. ## Methods | Method | Signature | Returns | |---|---|---| | `setLogger` | `setLogger(testingLogger: LoggerService)` | `void` | | `overridePipe` | `overridePipe(typeOrToken: T)` | `OverrideBy` | | `useMocker` | `useMocker(mocker: MockFactory)` | `TestingModuleBuilder` | | `overrideFilter` | `overrideFilter(typeOrToken: T)` | `OverrideBy` | | `overrideGuard` | `overrideGuard(typeOrToken: T)` | `OverrideBy` | | `overrideInterceptor` | `overrideInterceptor(typeOrToken: T)` | `OverrideBy` | | `overrideProvider` | `overrideProvider(typeOrToken: T)` | `OverrideBy` | | `overrideModule` | `overrideModule(moduleToOverride: ModuleDefinition)` | `OverrideModule` | | `compile` | `compile(options: Pick)` | `Promise` | ## Diagram ```mermaid graph LR A[Test.createTestingModule metadata] --> B[TestingModuleBuilder] B --> C[Configure logger or mocker] B --> D[Override providers/modules] B --> E[Override guards/pipes/filters/interceptors] C --> F[compile()] D --> F E --> F F --> G[TestingModule] G --> H[module.get()] G --> I[Application or unit tests] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { UsersService } from './users.service'; import { UsersRepository } from './users.repository'; describe('UsersService', () => { let usersService: UsersService; beforeEach(async () => { const moduleRef = await Test.createTestingModule({ providers: [UsersService, UsersRepository], }) .overrideProvider(UsersRepository) .useValue({ findById: jest.fn().mockResolvedValue({ id: 'user-1', email: 'user@example.com', }), }) .useMocker((token) => { if (token === 'EMAIL_CLIENT') { return { send: jest.fn() }; } }) .compile(); usersService = moduleRef.get(UsersService); }); it('returns a user', async () => { await expect(usersService.findById('user-1')).resolves.toEqual({ id: 'user-1', email: 'user@example.com', }); }); }); ``` ## AI Coding Instructions - Create the builder through `Test.createTestingModule()` and call `compile()` only after all module configuration and overrides are complete. - Use `overrideProvider()`, `overrideGuard()`, `overridePipe()`, `overrideFilter()`, or `overrideInterceptor()` to replace production dependencies with deterministic test doubles. - Use `useMocker()` for automatic fallback mocks, but explicitly override dependencies whose behavior is important to the test scenario. - Keep overrides scoped to the testing module; do not modify production module metadata or global application configuration for test-specific behavior. - Retrieve compiled dependencies from `TestingModule` with `moduleRef.get()` and reset Jest mocks between tests when mock state can leak. ## How it works `TestingModuleBuilder` is the mutable builder returned by `Test.createTestingModule(metadata, options)`. It accepts module metadata and optional `moduleIdGeneratorAlgorithm` configuration, creates a `NestContainer`, and turns the metadata into a dynamically decorated `RootTestModule`. [packages/testing/test.ts:11-16](packages/testing/test.ts#L11-L16) [packages/testing/testing-module.builder.ts:29-32](packages/testing/testing-module.builder.ts#L29-L32) [packages/testing/testing-module.builder.ts:49-56](packages/testing/testing-module.builder.ts#L49-L56) [packages/testing/testing-module.builder.ts:195-199](packages/testing/testing-module.builder.ts#L195-L199) - `setLogger(logger)` stores a `LoggerService` and returns the same builder. During `compile()`, it globally overrides Nest’s logger with that service; absent an explicitly set logger, it installs `TestingLogger`. `TestingLogger` suppresses `log`, `warn`, `debug`, and `verbose`, while forwarding `error` to `ConsoleLogger`. [packages/testing/testing-module.builder.ts:58-61](packages/testing/testing-module.builder.ts#L58-L61) [packages/testing/testing-module.builder.ts:100-100](packages/testing/testing-module.builder.ts#L100-L100) [packages/testing/testing-module.builder.ts:201-203](packages/testing/testing-module.builder.ts#L201-L203) [packages/testing/services/testing-logger.service.ts:6-17](packages/testing/services/testing-logger.service.ts#L6-L17) - `overridePipe`, `overrideFilter`, `overrideGuard`, and `overrideInterceptor` register a non-provider replacement for a supplied type or token. `overrideProvider` registers a provider replacement instead. Each returns an `OverrideBy` object whose `useValue`, `useClass`, and `useFactory` methods record the replacement and return the builder; factory options accept a required `factory` callback and optional `inject` array, and the builder records the callback under `useFactory`. A later override for the same type or token replaces the earlier map entry. [packages/testing/testing-module.builder.ts:63-86](packages/testing/testing-module.builder.ts#L63-L86) [packages/testing/testing-module.builder.ts:134-153](packages/testing/testing-module.builder.ts#L134-L153) [packages/testing/interfaces/override-by.interface.ts:7-10](packages/testing/interfaces/override-by.interface.ts#L7-L10) [packages/testing/interfaces/override-by-factory-options.interface.ts:4-7](packages/testing/interfaces/override-by-factory-options.interface.ts#L4-L7) - `overrideModule(moduleToOverride).useModule(newModule)` records a module substitution and returns the builder. `compile()` passes all recorded substitutions to dependency scanning, then applies recorded type/token replacements through `container.replace`. [packages/testing/testing-module.builder.ts:88-95](packages/testing/testing-module.builder.ts#L88-L95) [packages/testing/testing-module.builder.ts:117-123](packages/testing/testing-module.builder.ts#L117-L123) [packages/testing/testing-module.builder.ts:156-169](packages/testing/testing-module.builder.ts#L156-L169) - `useMocker(mocker)` stores a callback of type `(token?: InjectionToken) => any` and returns the builder. While creating dependency instances, the testing injector first tries normal resolution; if that throws, it calls the mocker with the unresolved name/token. A falsy mock result, or no mocker, rethrows the original resolution error. For a truthy result, it creates a resolved wrapper and adds/exports a `useValue` provider from the internal core module; if that module is absent, it throws `Expected to have internal core module reference at this point.` [packages/testing/testing-module.builder.ts:67-70](packages/testing/testing-module.builder.ts#L67-L70) [packages/testing/testing-module.builder.ts:176-193](packages/testing/testing-module.builder.ts#L176-L193) [packages/testing/interfaces/mock-factory.ts:1-4](packages/testing/interfaces/mock-factory.ts#L1-L4) [packages/testing/testing-instance-loader.ts:7-14](packages/testing/testing-instance-loader.ts#L7-L14) [packages/testing/testing-injector.ts:35-55](packages/testing/testing-injector.ts#L35-L55) [packages/testing/testing-injector.ts:80-118](packages/testing/testing-injector.ts#L80-L118) - `compile({ snapshot, preview })` is asynchronous and returns a `TestingModule`. It scans the generated root module, applies overrides, creates dependency instances, and applies application providers. With `snapshot: true`, it constructs a `GraphInspector` and switches the global `UuidFactory.mode` to deterministic; otherwise it uses `NoopGraphInspector` and switches that global mode to random. It passes both `preview` and `snapshot`, defaulting each to `false`, to `TestingInjector`. [packages/testing/testing-module.builder.ts:97-132](packages/testing/testing-module.builder.ts#L97-L132) [packages/testing/testing-module.builder.ts:176-193](packages/testing/testing-module.builder.ts#L176-L193) - The returned `TestingModule` is a `NestApplicationContext` constructed with the builder’s container, graph inspector, first module in the container as context module, and application configuration. [packages/testing/testing-module.builder.ts:125-131](packages/testing/testing-module.builder.ts#L125-L131) [packages/testing/testing-module.builder.ts:171-174](packages/testing/testing-module.builder.ts#L171-L174) [packages/testing/testing-module.ts:26-40](packages/testing/testing-module.ts#L26-L40) - The builder has no explicit runtime validation for constructor metadata, override inputs, logger, mocker, or `compile` options; errors from scanning and dependency creation are not caught by `compile()`. [packages/testing/testing-module.builder.ts:49-56](packages/testing/testing-module.builder.ts#L49-L56) [packages/testing/testing-module.builder.ts:97-123](packages/testing/testing-module.builder.ts#L97-L123) # TestingInjector **Kind:** Class **Source:** [`packages/testing/testing-injector.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-injector.ts#L23) **Part of:** [Testing](subsystem-packages-testing) `TestingInjector` extends Nest’s dependency injector for testing contexts. It coordinates the test container and mock factory, resolving real providers when available and supplying mocks for unresolved dependencies during testing module compilation. **Extends:** `Injector` ## Methods | Method | Signature | Returns | |---|---|---| | `setMocker` | `setMocker(mocker: MockFactory)` | `void` | | `setContainer` | `setContainer(container: NestContainer)` | `void` | | `resolveComponentWrapper` | `resolveComponentWrapper(moduleRef: Module, name: any, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper, resolutionContext: ResolutionContext, keyOrIndex: string | number)` | `Promise` | | `resolveComponentHost` | `resolveComponentHost(moduleRef: Module, instanceWrapper: InstanceWrapper, resolutionContext: ResolutionContext)` | `Promise` | ## Properties | Property | Type | |---|---| | `mocker` | `MockFactory` | | `container` | `NestContainer` | ## Where it refuses work - `TestingInjector` stops the work with `Error` when `!internalCoreModule` — “Expected to have internal core module reference at this point.”. - `TestingInjector` stops the work with an early return when `!this.mocker`. - `TestingInjector` stops the work with an early return when `!mockedInstance`. ## When something fails - `TestingInjector` handles failure in 2 places: it turns it into a return value in all 2. ## Diagram ```mermaid graph LR Builder[TestingModuleBuilder] -->|setMocker()| Injector[TestingInjector] Builder -->|setContainer()| Injector Injector -->|resolveComponentWrapper()| CoreInjector[Nest Injector] CoreInjector -->|Provider found| RealProvider[Resolved provider] CoreInjector -->|Provider missing| Injector Injector -->|mocker(token)| MockFactory[Mock factory] MockFactory --> MockProvider[Mock provider instance] MockProvider --> Container[NestContainer] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { HttpService } from '@nestjs/axios'; import { UsersService } from './users.service'; const moduleRef = await Test.createTestingModule({ providers: [UsersService], }) // TestingInjector receives and uses this mock factory internally. .useMocker((token) => { if (token === HttpService) { return { get: jest.fn().mockResolvedValue({ data: { id: 'user-1', name: 'Ada' }, }), }; } // Return undefined for tokens that should not be mocked. return undefined; }) .compile(); const usersService = moduleRef.get(UsersService); ``` ## AI Coding Instructions - Configure mocks through `TestingModuleBuilder.useMocker()`; `TestingInjector` is an internal integration point used during test module compilation. - Ensure mock factories return an object or instance for dependencies that cannot be resolved from the testing module. - Return `undefined` only when a token should be resolved normally or intentionally left unresolved. - Call `setContainer()` before resolving providers directly so generated mock wrappers can be registered in Nest’s internal core module. - Preserve normal injector behavior by delegating to the base resolution flow before applying mock fallback logic. ## Relationships - IMPORTS → `NestContainer` - IMPORTS → `STATIC_CONTEXT` - IMPORTS → `Injector` - IMPORTS → `InjectorDependencyContext` - IMPORTS → `ContextId` - IMPORTS → `InstanceWrapper` - IMPORTS → `Module` # TestingModule **Kind:** Class **Source:** [`packages/testing/testing-module.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-module.ts#L26) **Part of:** [Testing](subsystem-packages-testing) `TestingModule` is the compiled test container returned by Nest's testing utilities. It provides access to resolved providers and exposes factory methods for creating test-specific Nest HTTP applications or microservices from the module configuration. **Extends:** `NestApplicationContext` ## Methods | Method | Signature | Returns | |---|---|---| | `createNestApplication` | `createNestApplication(httpAdapter: HttpServer | AbstractHttpAdapter, options: NestApplicationOptions)` | `T` | | `createNestApplication` | `createNestApplication(options: NestApplicationOptions)` | `T` | | `createNestApplication` | `createNestApplication(serverOrOptions: | HttpServer | AbstractHttpAdapter | NestApplicationOptions | undefined, options: NestApplicationOptions)` | `T` | | `createNestMicroservice` | `createNestMicroservice(options: NestMicroserviceOptions & T)` | `INestMicroservice` | ## Properties | Property | Type | |---|---| | `graphInspector` | `GraphInspector` | ## Where it refuses work - `TestingModule` stops the work with an early return when `!options || isUndefined(options.logger)`. - `TestingModule` stops the work with an early return when `!(prop in receiver) && prop in adapter`. ## Diagram ```mermaid graph LR A[Test.createTestingModule] --> B[TestingModuleBuilder] B --> C[TestingModule] C --> D[Resolve providers with get/resolve] C --> E[createNestApplication] C --> F[createNestMicroservice] E --> G[INestApplication] F --> H[INestMicroservice] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import { AppModule } from '../src/app.module'; describe('AppModule', () => { let app: INestApplication; beforeAll(async () => { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleRef.createNestApplication(); await app.init(); }); afterAll(async () => { await app.close(); }); it('starts the application', async () => { expect(app).toBeDefined(); }); }); ``` ## AI Coding Instructions - Build and compile a testing module with `Test.createTestingModule(...).compile()` before calling `createNestApplication()` or `createNestMicroservice()`. - Use `moduleRef.get()` or `moduleRef.resolve()` to retrieve and test providers directly when an HTTP server is unnecessary. - Always call `await app.init()` before sending requests to an application created by `createNestApplication()`. - Close created applications or microservices in teardown hooks to prevent open handles between test suites. - Override providers, guards, or modules on the testing module builder before calling `compile()` to isolate external dependencies. ## How it works `TestingModule` is the testing package’s exported application-context class. It extends `NestApplicationContext`, retaining context operations such as dependency lookup, scoped resolution, lifecycle initialization, and shutdown; it is returned by `TestingModuleBuilder.compile()` after dependency scanning, instance creation, and application-provider setup. [packages/testing/testing-module.ts:26](packages/testing/testing-module.ts#L26) [packages/testing/testing-module.builder.ts:97-131](packages/testing/testing-module.builder.ts#L97-L131) [packages/core/nest-application-context.ts:165-175](packages/core/nest-application-context.ts#L165-L175) [packages/core/nest-application-context.ts:226-245](packages/core/nest-application-context.ts#L226-L245) [packages/core/nest-application-context.ts:253-284](packages/core/nest-application-context.ts#L253-L284) Its constructor receives a Nest container, graph inspector, context module, application configuration, and optional module scope. It initializes the inherited context with empty context options, stores the supplied graph inspector, and passes the supplied context module and scope to the parent context. [packages/testing/testing-module.ts:29-40](packages/testing/testing-module.ts#L29-L40) ## Relationships - IMPORTS → `HttpServer` - IMPORTS → `INestApplication` - IMPORTS → `INestMicroservice` - IMPORTS → `Logger` - IMPORTS → `NestApplicationOptions` - IMPORTS → `Type` - IMPORTS → `NestMicroserviceOptions` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `loadPackage` - IMPORTS → `isUndefined` - IMPORTS → `AbstractHttpAdapter` - IMPORTS → `NestApplication` - IMPORTS → `NestApplicationContext` - IMPORTS → `ApplicationConfig` - IMPORTS → `NestContainer` - IMPORTS → `Module` - IMPORTS → `GraphInspector` - IMPORTS → `-nestjs-microservices` - IMPORTS → `-nestjs-platform-express` # TestingLogger **Kind:** Class **Source:** [`packages/testing/services/testing-logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/services/testing-logger.service.ts#L6) **Part of:** [Testing](subsystem-packages-testing) `TestingLogger` is a test-focused logger implementation that provides the standard logging methods used throughout the application: `log`, `warn`, `debug`, `verbose`, and `error`. It allows tests to capture, inspect, or safely handle log output without depending on the production logging infrastructure. **Extends:** `ConsoleLogger` ## Methods | Method | Signature | Returns | |---|---|---| | `log` | `log(message: string)` | `void` | | `warn` | `warn(message: string)` | `void` | | `debug` | `debug(message: string)` | `void` | | `verbose` | `verbose(message: string)` | `void` | | `error` | `error(message: string, optionalParams: any[])` | `void` | ## Diagram ```mermaid graph LR Test[Test Suite] --> Logger[TestingLogger] Logger --> Log[log()] Logger --> Warn[warn()] Logger --> Debug[debug()] Logger --> Verbose[verbose()] Logger --> Error[error()] Log --> Assertions[Test Assertions] Warn --> Assertions Debug --> Assertions Verbose --> Assertions Error --> Assertions ``` ## Usage ```ts import { TestingLogger } from '@your-package/testing'; describe('ExampleService', () => { it('logs an expected message', () => { const logger = new TestingLogger(); logger.log('Processing started'); logger.warn('Optional configuration is missing'); logger.debug('Request payload received'); logger.verbose('Additional diagnostic details'); logger.error('Processing failed'); // Use the testing logger with the service under test. // const service = new ExampleService(logger); }); }); ``` ## AI Coding Instructions - Use `TestingLogger` when unit or integration tests need a logger dependency instead of the production logger. - Call the method that matches the intended log level: `log` for normal messages, `warn` for recoverable issues, and `error` for failures. - Keep test logging deterministic; avoid relying on timestamps, environment-specific values, or external output destinations. - When adding logger-compatible services, preserve support for all standard methods exposed by `TestingLogger`. - Prefer assertions against expected logging behavior when logs represent important operational or error-handling outcomes. ## How it works ## `TestingLogger` `TestingLogger` is a public class that extends Nest’s `ConsoleLogger`. Its constructor initializes the inherited logger with the context string `"Testing"`. [packages/testing/services/testing-logger.service.ts:3-9] ## Relationships - IMPORTS → `ConsoleLogger` # Test **Kind:** Class **Source:** [`packages/testing/test.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/test.ts#L8) **Part of:** [Testing](subsystem-packages-testing) `Test` is the entry point for creating isolated NestJS testing modules. Its `createTestingModule()` method accepts module metadata and returns a builder that can configure providers, overrides, and dependencies before compiling a testable application context. ## Methods | Method | Signature | Returns | |---|---|---| | `createTestingModule` | `createTestingModule(metadata: ModuleMetadata, options: TestingModuleOptions)` | `void` | ## Diagram ```mermaid graph LR A[Test.createTestingModule] --> B[TestingModuleBuilder] B --> C[Configure imports, providers, controllers] B --> D[Override providers or guards] C --> E[compile()] D --> E E --> F[TestingModule] F --> G[Resolve and test dependencies] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { UsersService } from './users.service'; import { UsersController } from './users.controller'; describe('UsersController', () => { it('returns a user', async () => { const moduleRef = await Test.createTestingModule({ controllers: [UsersController], providers: [ { provide: UsersService, useValue: { findOne: jest.fn().mockResolvedValue({ id: '1', name: 'Ada' }), }, }, ], }).compile(); const controller = moduleRef.get(UsersController); await expect(controller.findOne('1')).resolves.toEqual({ id: '1', name: 'Ada', }); }); }); ``` ## AI Coding Instructions - Use `Test.createTestingModule()` as the starting point for unit and integration test dependency setup. - Include only the controllers, providers, and imports required by the test to keep modules isolated and fast. - Replace external dependencies, such as databases, HTTP clients, and queues, with `useValue` or `useFactory` mocks. - Call `.compile()` before retrieving dependencies with `moduleRef.get()` or creating an application instance. - Use builder override methods when testing modules that already register concrete providers or framework dependencies. ## How it works `Test` is an exported class whose role is to start construction of a testing module. It holds one private static `MetadataScanner` instance and passes that same instance to every builder it creates. [packages/testing/test.ts:8-15] - `Test.createTestingModule(metadata, options?)` is a static factory method. It accepts `ModuleMetadata` and an optional `TestingModuleOptions`, then returns a new `TestingModuleBuilder`; it does not compile the module itself. [packages/testing/test.ts:11-16] - The supplied `metadata` and optional `options` are forwarded unchanged to the builder constructor. [packages/testing/test.ts:12-15] - During builder construction, a new `ApplicationConfig` and `NestContainer` are created, and the metadata is applied with `@Module(...)` to a locally declared `RootTestModule` class. [packages/testing/testing-module.builder.ts:38-56] [packages/testing/testing-module.builder.ts:195-199] - The returned builder exposes configuration methods for logger selection, mocks, and provider/module overrides, followed by `compile()` to scan dependencies, create instances, and return a `TestingModule`. [packages/testing/testing-module.builder.ts:58-95] [packages/testing/testing-module.builder.ts:97-132] - `TestingModuleOptions` currently contains only `moduleIdGeneratorAlgorithm`, inherited as a `Pick` from application-context options. [packages/testing/testing-module.builder.ts:29-32] - `Test` itself contains no input validation and explicitly throws no errors. [packages/testing/test.ts:8-16] ## Relationships - IMPORTS → `ModuleMetadata` - IMPORTS → `MetadataScanner` # TestingInstanceLoader **Kind:** Class **Source:** [`packages/testing/testing-instance-loader.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-instance-loader.ts#L6) **Part of:** [Testing](subsystem-packages-testing) `TestingInstanceLoader` creates and initializes providers, controllers, and other dependency instances for Nest testing modules. It extends Nest’s core instance-loading flow with testing-specific injector behavior, including support for mocked dependencies during `TestingModule` compilation. **Extends:** `InstanceLoader` ## Methods | Method | Signature | Returns | |---|---|---| | `createInstancesOfDependencies` | `createInstancesOfDependencies(modules: Map, mocker: MockFactory)` | `Promise` | ## Diagram ```mermaid graph LR A[TestingModuleBuilder] --> B[TestingInstanceLoader] B --> C[TestingInjector] B --> D[NestContainer Modules] C --> E[Mock Factory / Overrides] B --> F[InstanceLoader] F --> G[Providers and Controllers Instantiated] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { UsersService } from './users.service'; import { UsersRepository } from './users.repository'; describe('UsersService', () => { it('creates service dependencies with testing overrides', async () => { const moduleRef = await Test.createTestingModule({ providers: [UsersService, UsersRepository], }) .overrideProvider(UsersRepository) .useValue({ findById: jest.fn(), }) .compile(); // TestingInstanceLoader runs internally during compile(). const usersService = moduleRef.get(UsersService); expect(usersService).toBeDefined(); }); }); ``` ## AI Coding Instructions - Preserve the delegation to Nest’s core `InstanceLoader`; testing behavior should augment instance creation rather than replace it. - Ensure the testing injector is associated with the current Nest container before resolving dependencies. - Keep mocker and provider-override behavior scoped to the testing injector so production dependency resolution is unaffected. - Prefer using `Test.createTestingModule(...).compile()` instead of constructing `TestingInstanceLoader` directly in application tests. ## How it works ## `TestingInstanceLoader` `TestingInstanceLoader` is an exported testing-specific subclass of `InstanceLoader` whose injector type is `TestingInjector`. [packages/testing/testing-instance-loader.ts:6] Its `createInstancesOfDependencies` method: - Accepts an optional module map and an optional `MockFactory`; the factory has the type `(token?: InjectionToken) => any`. [packages/testing/testing-instance-loader.ts:7-10] [packages/testing/interfaces/mock-factory.ts:1-3] - Assigns the loader’s container to the `TestingInjector` before dependency creation. [packages/testing/testing-instance-loader.ts:11] [packages/testing/testing-injector.ts:31-33] - Assigns the mocker to that injector only when the `mocker` argument is truthy. [packages/testing/testing-instance-loader.ts:12] [packages/testing/testing-injector.ts:27-29] - Calls the inherited loader with no arguments, rather than forwarding its `modules` parameter. Consequently, the parent method uses `this.container.getModules()` as its default module map. [packages/testing/testing-instance-loader.ts:8] [packages/testing/testing-instance-loader.ts:13] [packages/core/injector/instance-loader.ts:25-28] The inherited loading sequence creates provider, injectable, and controller prototypes for every module, then asynchronously loads their instances. [packages/core/injector/instance-loader.ts:28-31] [packages/core/injector/instance-loader.ts:40-45] [packages/core/injector/instance-loader.ts:62-76] [packages/core/injector/instance-loader.ts:80-113] It also inspects modules after successful loading; if instance creation fails, it inspects modules, records the partial graph with the error, and rethrows that error. [packages/core/injector/instance-loader.ts:30-38] Because this loader uses `TestingInjector`, dependency-resolution errors can be handled by the configured mocker: `TestingInjector` first delegates resolution to `Injector`, then invokes its mock path if that call throws. [packages/testing/testing-injector.ts:35-55] [packages/testing/testing-injector.ts:58-77] If no mocker is set, or if the mocker returns a falsy value, the original resolution error is rethrown. [packages/testing/testing-injector.ts:80-93] When a truthy mock is returned, the injector creates a resolved wrapper for it and registers it as a value provider and export in the container’s internal core module. [packages/testing/testing-injector.ts:94-118] If that internal core module reference is absent, it throws `Error('Expected to have internal core module reference at this point.')`. [packages/testing/testing-injector.ts:103-108] `TestingModuleBuilder` constructs this loader with its container, a newly created `TestingInjector`, and a graph inspector, then calls this method with the container’s modules and the builder’s optional mocker. [packages/testing/testing-module.builder.ts:176-192] The builder stores a mocker through `useMocker(mocker)`. [packages/testing/testing-module.builder.ts:47] [packages/testing/testing-module.builder.ts:67-70] ## Relationships - IMPORTS → `InstanceLoader` - IMPORTS → `Module` # OverrideBy **Kind:** Interface **Source:** [`packages/testing/interfaces/override-by.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/interfaces/override-by.interface.ts#L7) **Part of:** [Testing](subsystem-packages-testing) `OverrideBy` defines the strategies available when overriding a provider, guard, interceptor, pipe, or filter in a testing module. Each strategy returns a `TestingModuleBuilder`, allowing overrides to be chained before compiling the module. ## Properties | Property | Type | |---|---| | `useValue` | `(value: any) => TestingModuleBuilder` | | `useFactory` | `(options: OverrideByFactoryOptions) => TestingModuleBuilder` | | `useClass` | `(metatype: any) => TestingModuleBuilder` | ## Diagram ```mermaid graph LR A[TestingModuleBuilder
    overrideProvider / overrideGuard] --> B[OverrideBy] B --> C[useValue] B --> D[useFactory] B --> E[useClass] C --> F[TestingModuleBuilder] D --> F E --> F F --> G[compile()] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { UsersService } from './users.service'; import { UsersController } from './users.controller'; const usersServiceMock = { findAll: jest.fn().mockResolvedValue([{ id: 1, name: 'Ada' }]), }; const moduleRef = await Test.createTestingModule({ controllers: [UsersController], providers: [UsersService], }) .overrideProvider(UsersService) .useValue(usersServiceMock) .compile(); // Alternative override strategies: // .overrideProvider(UsersService).useClass(MockUsersService) // .overrideProvider(UsersService).useFactory({ // factory: () => usersServiceMock, // inject: [], // }) ``` ## AI Coding Instructions - Use `useValue` for simple mocks, stubs, and fixed test doubles that do not require dependency injection. - Use `useClass` when the replacement should be instantiated as a provider and may have its own dependencies. - Use `useFactory` for dynamically created overrides; provide required dependencies through `OverrideByFactoryOptions`. - Always call an override method such as `overrideProvider()` before calling `useValue`, `useFactory`, or `useClass`. - Preserve the returned `TestingModuleBuilder` to support chaining additional overrides before calling `compile()`. # OverrideByFactoryOptions **Kind:** Interface **Source:** [`packages/testing/interfaces/override-by-factory-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/interfaces/override-by-factory-options.interface.ts#L4) **Part of:** [Testing](subsystem-packages-testing) `OverrideByFactoryOptions` configures a testing override that creates a replacement provider through a factory function. The `inject` array declares the dependencies passed to the factory, allowing test modules to compose mocks or custom implementations from other registered providers. ## Properties | Property | Type | |---|---| | `factory` | `(...args: any[]) => any` | | `inject` | `any[]` | ## Diagram ```mermaid graph LR A[Test Module] --> B[OverrideByFactoryOptions] B --> C[factory(...args)] D[inject tokens] --> E[Resolved dependencies] E --> C C --> F[Replacement provider instance] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; const mockUsersService = { findAll: jest.fn().mockResolvedValue([]), }; const moduleRef = await Test.createTestingModule({ providers: [UsersService, ConfigService], }) .overrideProvider(UsersService) .useFactory({ inject: [ConfigService], factory: (configService: ConfigService) => ({ ...mockUsersService, findAll: jest.fn().mockResolvedValue([ { id: 1, environment: configService.get('NODE_ENV') }, ]), }), }) .compile(); ``` ## AI Coding Instructions - Use `factory` when an override needs to be built dynamically from other providers instead of returning a fixed mock. - Include every factory dependency in `inject` and keep the array order aligned with the factory function parameters. - Return the complete replacement provider implementation expected by the code under test. - Prefer stable mock behavior in factories; avoid unnecessary external state or side effects. - Ensure injected dependency tokens are available in the testing module before compiling it. # TestingModuleOptions **Kind:** Type **Source:** [`packages/testing/testing-module.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-module.builder.ts#L29) **Part of:** [Testing](subsystem-packages-testing) ## Definition ```ts Pick< NestApplicationContextOptions, 'moduleIdGeneratorAlgorithm' > ``` ## Relationships - IMPORTS → `Logger` - IMPORTS → `LoggerService` - IMPORTS → `Module` - IMPORTS → `ModuleMetadata` - IMPORTS → `NestApplicationContextOptions` - IMPORTS → `ApplicationConfig` - IMPORTS → `NestContainer` - IMPORTS → `GraphInspector` - IMPORTS → `NoopGraphInspector` - IMPORTS → `UuidFactory` - IMPORTS → `UuidFactoryMode` - IMPORTS → `ModuleDefinition` - IMPORTS → `ModuleOverride` - IMPORTS → `MetadataScanner` - IMPORTS → `DependenciesScanner` # OverrideModule **Kind:** Interface **Source:** [`packages/testing/interfaces/override-module.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/interfaces/override-module.interface.ts#L7) **Part of:** [Testing](subsystem-packages-testing) `OverrideModule` defines the fluent API used to replace an existing module definition while building a test module. Calling `useModule` supplies a new `ModuleDefinition` and returns the `TestingModuleBuilder` so additional test configuration can be chained. ## Properties | Property | Type | |---|---| | `useModule` | `(newModule: ModuleDefinition) => TestingModuleBuilder` | ## Diagram ```mermaid graph LR A[TestingModuleBuilder] -->|overrideModule(targetModule)| B[OverrideModule] B -->|useModule(newModule)| C[TestingModuleBuilder] C -->|compile()| D[TestingModule] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { AppModule } from './app.module'; import { DatabaseModule } from './database.module'; import { InMemoryDatabaseModule } from './testing/in-memory-database.module'; const testingModule = await Test.createTestingModule({ imports: [AppModule], }) .overrideModule(DatabaseModule) .useModule(InMemoryDatabaseModule) .compile(); ``` ## AI Coding Instructions - Use `overrideModule()` before calling `useModule()`; `useModule()` is available on the returned `OverrideModule` interface. - Pass a valid Nest `ModuleDefinition`, such as a module class or supported dynamic module definition. - Preserve the fluent builder chain by using the `TestingModuleBuilder` returned from `useModule()`. - Use module overrides for integration boundaries such as databases, messaging clients, or external-service modules. - Ensure replacement modules provide any providers, exports, or imports required by modules under test. ## Relationships - IMPORTS → `ModuleDefinition` # MockFactory **Kind:** Type **Source:** [`packages/testing/interfaces/mock-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/interfaces/mock-factory.ts#L3) **Part of:** [Testing](subsystem-packages-testing) ## Definition ```ts (token?: InjectionToken) => any ``` ## Relationships - IMPORTS → `InjectionToken` # WsAdapter **Kind:** Class **Source:** [`packages/platform-ws/adapters/ws-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-ws/adapters/ws-adapter.ts#L39) **Part of:** [Platform Ws](subsystem-packages-platform-ws) `WsAdapter` is Nest’s WebSocket adapter for the `ws` library. It creates and manages WebSocket servers, routes incoming messages to gateway handlers, and coordinates connection errors, client disconnects, and server cleanup. **Extends:** `AbstractWsAdapter` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(port: number, options: Record & { namespace?: string; server?: any; path?: string; })` | `void` | | `bindMessageHandlers` | `bindMessageHandlers(client: any, handlers: MessageMappingProperties[], transform: (data: any) => Observable)` | `void` | | `bindMessageHandler` | `bindMessageHandler(buffer: any, handlersMap: Map, transform: (data: any) => Observable)` | `Observable` | | `bindErrorHandler` | `bindErrorHandler(server: any)` | `void` | | `bindClientDisconnect` | `bindClientDisconnect(client: any, callback: Function)` | `void` | | `close` | `close(server: any)` | `void` | | `dispose` | `dispose()` | `void` | | `setMessageParser` | `setMessageParser(parser: WsMessageParser)` | `void` | | `ensureHttpServerExists` | `ensureHttpServerExists(port: number, httpServer: undefined)` | `void` | | `addWsServerToRegistry` | `addWsServerToRegistry(wsServer: T, port: number, path: string)` | `void` | ## Properties | Property | Type | |---|---| | `logger` | `any` | | `httpServersRegistry` | `any` | | `wsServersRegistry` | `any` | | `messageParser` | `WsMessageParser` | ## Where it refuses work - `WsAdapter` stops the work with an early return when `server`. - `WsAdapter` stops the work with an early return when `client.readyState !== READY_STATE.OPEN_STATE`. - `WsAdapter` stops the work with an early return when `!message`. - `WsAdapter` stops the work with an early return when `this.httpServersRegistry.has(port)`. ## When something fails - `WsAdapter` handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1. ## Diagram ```mermaid graph LR App[Nest Application] --> Adapter[WsAdapter] Adapter --> Http[HTTP Server] Adapter --> WsServer[ws.Server] Client[WebSocket Client] --> WsServer WsServer --> Parser[Message Parser] Parser --> Handler[Gateway Message Handler] Handler --> Response[Observable Response] Response --> Client WsServer --> Errors[Error Handler] Client --> Disconnect[Disconnect Handler] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { WsAdapter } from '@nestjs/platform-ws'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Attach the ws-based adapter to Nest's underlying HTTP server. app.useWebSocketAdapter(new WsAdapter(app.getHttpServer())); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Use `WsAdapter` when the application should use the `ws` package instead of the default Socket.IO WebSocket transport. - Pass the Nest HTTP server to the adapter so WebSocket connections can share the application’s existing server and port. - Keep message parsing compatible with gateway handler payloads; use `setMessageParser()` only when clients send a custom message format. - Ensure message handlers return values or `Observable`s that can be serialized and sent back to connected clients. - Call application shutdown hooks or adapter cleanup paths so registered WebSocket servers are closed through `close()` or `dispose()`. ## How it works `WsAdapter` is a public WebSocket adapter class in `@nestjs/platform-ws`. It extends `AbstractWsAdapter` and loads the `ws` package during construction. [packages/platform-ws/adapters/ws-adapter.ts:36-63] The parent adapter stores either the underlying HTTP server from a `NestApplication` argument or the supplied object directly. [packages/websockets/adapters/ws-adapter.ts:29-35] The constructor accepts an optional application/HTTP-server object and an optional `{ messageParser }` option. Its default parser converts incoming data to a string and runs `JSON.parse`; a supplied parser replaces that default. [packages/platform-ws/adapters/ws-adapter.ts:49-63] ## Server creation `create(port, options)` creates or returns a WebSocket server according to `port`, `server`, and `path`. [packages/platform-ws/adapters/ws-adapter.ts:65-126] - A truthy `options.namespace` is unsupported: the adapter logs an `Error` and throws it. [packages/platform-ws/adapters/ws-adapter.ts:78-84] - When called with port `0` and the adapter has an inherited HTTP server, it registers that HTTP server, creates a `ws.Server` with `noServer: true`, registers the WebSocket server under `path`, and returns it. [packages/platform-ws/adapters/ws-adapter.ts:86-96] - When `options.server` is set outside that branch, it returns that object without creating or registering another server. [packages/platform-ws/adapters/ws-adapter.ts:99-101] - When `path` is set and `port` is not `0`, it creates or reuses an internal Node HTTP server for the port, calls `listen(port)`, creates a `noServer` `ws.Server`, registers it by path, and returns it. [packages/platform-ws/adapters/ws-adapter.ts:102-116] - Otherwise, it creates and returns a `ws.Server` with `port`, `path`, and remaining options. [packages/platform-ws/adapters/ws-adapter.ts:118-125] For registered `noServer` instances, the internal HTTP server handles `upgrade` events. It parses the request pathname, finds the first registered WebSocket server whose normalized `path` exactly matches, then calls `handleUpgrade` and emits that server’s `connection` event. [packages/platform-ws/adapters/ws-adapter.ts:217-231] An unmatched pathname destroys the socket; an exception while handling the upgrade writes an HTTP `400` response with the exception message. [packages/platform-ws/adapters/ws-adapter.ts:233-238] Registration normalizes the path and stores servers in a per-port array. [packages/platform-ws/adapters/ws-adapter.ts:243-253] ## Incoming messages and responses `bindMessageHandlers(client, handlers, transform)` indexes the supplied handler metadata by each handler’s `message` value, then subscribes to the client’s `'message'` events until its first close event. [packages/platform-ws/adapters/ws-adapter.ts:128-144] Each incoming event is passed to `bindMessageHandler`; `null` and `undefined` results are filtered out. [packages/platform-ws/adapters/ws-adapter.ts:137-143] `bindMessageHandler` calls the configured parser with `buffer.data`. The parser must return an object with `event` and `data` properties for dispatch to continue. [packages/platform-ws/adapters/ws-adapter.ts:154-166] It finds the handler mapped to `event`, calls that handler’s callback with `(data, event)`, and passes the callback result to `transform`. [packages/platform-ws/adapters/ws-adapter.ts:164-166] If parsing returns no message, or if an exception occurs during this sequence, it returns the empty RxJS observable, so no response is emitted from that message. [packages/platform-ws/adapters/ws-adapter.ts:159-169] For every non-nil value emitted after transformation, the adapter sends `JSON.stringify(response)` to the client only when `client.readyState` equals `1` (`OPEN_STATE`). [packages/platform-ws/adapters/ws-adapter.ts:145-151] Handler metadata declares callbacks that may return an `Observable` or `Promise`. [packages/websockets/gateway-metadata-explorer.ts:15-20] `setMessageParser(parser)` replaces the parser used by later calls to `bindMessageHandler`. [packages/platform-ws/adapters/ws-adapter.ts:204-206] ## Connection, error, and shutdown behavior `bindErrorHandler(server)` attaches error listeners to both the server and each connected WebSocket client; both listeners log the received error. [packages/platform-ws/adapters/ws-adapter.ts:172-178] `bindClientDisconnect(client, callback)` attaches `callback` to the client’s close event. [packages/platform-ws/adapters/ws-adapter.ts:180-182] `close(server)` calls `server.close`, terminates every entry in `server.clients`, then resolves when the close callback has no error or rejects with that callback error. [packages/platform-ws/adapters/ws-adapter.ts:184-192] `dispose()` closes internally registered HTTP servers except the server registered under port `0`, waits for all close callbacks, and clears both HTTP-server and WebSocket-server registries. [packages/platform-ws/adapters/ws-adapter.ts:194-202] ## Relationships - IMPORTS → `INestApplicationContext` - IMPORTS → `Logger` - IMPORTS → `loadPackage` - IMPORTS → `isNil` - IMPORTS → `normalizePath` - IMPORTS → `AbstractWsAdapter` - IMPORTS → `CLOSE_EVENT` - IMPORTS → `CONNECTION_EVENT` - IMPORTS → `ERROR_EVENT` - IMPORTS → `MessageMappingProperties` # IoAdapter **Kind:** Class **Source:** [`packages/platform-socket.io/adapters/io-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/platform-socket.io/adapters/io-adapter.ts#L14) **Part of:** [Platform Socket.io](subsystem-packages-platform-socket-io) `IoAdapter` is NestJS's Socket.IO transport adapter, responsible for creating and configuring Socket.IO servers for WebSocket gateways. It binds gateway message handlers to connected sockets, maps incoming payloads and acknowledgement callbacks, and closes the underlying server during application shutdown. **Extends:** `AbstractWsAdapter` ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(port: number, options: ServerOptions & { namespace?: string; server?: any })` | `Server` | | `createIOServer` | `createIOServer(port: number, options: any)` | `any` | | `bindMessageHandlers` | `bindMessageHandlers(socket: Socket, handlers: MessageMappingProperties[], transform: (data: any) => Observable)` | `void` | | `mapPayload` | `mapPayload(payload: unknown)` | `{ data: any; ack?: Function }` | | `close` | `close(server: Server)` | `Promise` | ## Where it refuses work - `IoAdapter` stops the work with an early return when `!options`. - `IoAdapter` stops the work with an early return when `this.httpServer && port === 0`. - `IoAdapter` stops the work with an early return when `response.event`. - `IoAdapter` stops the work with an early return when `isFunction(payload)`. - `IoAdapter` stops the work with an early return when `this.forceCloseConnections && server.httpServer === this.httpServer`. ## Diagram ```mermaid graph LR App[Nest Application] --> Adapter[IoAdapter] Adapter --> Server[Socket.IO Server] Server --> Gateway[WebSocket Gateway] Gateway --> Handlers[Message Handlers] Client[Socket.IO Client] -->|event + payload| Server Handlers -->|response / acknowledgement| Client ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { IoAdapter } from '@nestjs/platform-socket.io'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Register the Socket.IO adapter used by @WebSocketGateway() classes. app.useWebSocketAdapter(new IoAdapter(app)); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Use `IoAdapter` through `app.useWebSocketAdapter()` when configuring Socket.IO support for NestJS gateways. - Prefer gateway decorators such as `@WebSocketGateway()` and `@SubscribeMessage()` instead of manually binding Socket.IO events. - Preserve acknowledgement callback handling when changing payload parsing; Socket.IO payloads may include a final callback function. - Ensure custom adapters or server instances implement proper shutdown behavior so `close()` can release Socket.IO resources. - Configure Socket.IO options, such as CORS or transport settings, when creating or extending the adapter rather than modifying gateway handler logic. ## Relationships - IMPORTS → `isFunction` - IMPORTS → `isNil` - IMPORTS → `AbstractWsAdapter` - IMPORTS → `MessageMappingProperties` - IMPORTS → `DISCONNECT_EVENT` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RedisIoAdapter` — `sample/02-gateways/src/adapters/redis-io.adapter.ts`:6 # containsPackageJson **Kind:** Function **Source:** [`tools/gulp/util/task-helpers.ts`](https://github.com/nestjs/nest/blob/master/tools/gulp/util/task-helpers.ts#L21) Checks if the directory contains a package.json file `containsPackageJson` checks whether a specified directory contains a `package.json` file. It is used by Gulp task helpers to identify Node.js package directories before applying package-specific build, packaging, or dependency-processing logic. ## Signature ```ts function containsPackageJson(dir: string) ``` ## Parameters | Name | Type | |---|---| | `dir` | `string` | ## Diagram ```mermaid graph LR A[Directory path] --> B[containsPackageJson] B --> C{package.json exists?} C -->|Yes| D[Return true] C -->|No| E[Return false] ``` ## Usage ```ts import { containsPackageJson } from './tools/gulp/util/task-helpers'; const packageDirectory = './extensions/my-extension'; if (containsPackageJson(packageDirectory)) { console.log('This directory is a Node.js package.'); } else { console.log('No package.json found.'); } ``` ## AI Coding Instructions - Pass a directory path, not a path to `package.json` itself; the helper performs the filename check internally. - Use this helper before running package-specific Gulp tasks or reading package metadata. - Treat a `false` result as an expected condition for non-package directories rather than an error. - Keep filesystem existence checks centralized through this utility when working in Gulp task helpers. # getDirs **Kind:** Function **Source:** [`tools/gulp/util/task-helpers.ts`](https://github.com/nestjs/nest/blob/master/tools/gulp/util/task-helpers.ts#L12) ## Signature ```ts function getDirs(base: string) ``` ## Parameters | Name | Type | |---|---| | `base` | `string` | # getFolders **Kind:** Function **Source:** [`tools/gulp/util/task-helpers.ts`](https://github.com/nestjs/nest/blob/master/tools/gulp/util/task-helpers.ts#L8) ## Signature ```ts function getFolders(dir: string) ``` ## Parameters | Name | Type | |---|---| | `dir` | `string` | # mochaHooks **Kind:** Function **Source:** [`hooks/mocha-init-hook.ts`](https://github.com/nestjs/nest/blob/master/hooks/mocha-init-hook.ts#L1) ## Signature ```ts function mochaHooks(): Mocha.RootHookObject ``` **Returns:** `Mocha.RootHookObject` # packagePaths **Kind:** Constant **Source:** [`tools/gulp/config.ts`](https://github.com/nestjs/nest/blob/master/tools/gulp/config.ts#L7) ## Definition ```ts getDirs(source) ``` ## Value ```ts getDirs(source) ``` # samplePath **Kind:** Constant **Source:** [`tools/gulp/config.ts`](https://github.com/nestjs/nest/blob/master/tools/gulp/config.ts#L5) ## Definition ```ts 'sample' ``` ## Value ```ts 'sample' ``` # source **Kind:** Constant **Source:** [`tools/gulp/config.ts`](https://github.com/nestjs/nest/blob/master/tools/gulp/config.ts#L4) ## Definition ```ts 'packages' ``` ## Value ```ts 'packages' ``` # Common ## What it is responsible for Common manages shared, framework-facing declarations and input-pipe entry points for the codebase. Its documentation says that the common package comes with decorators such as `@Controller()` and `@Injectable()`. Work enters through `DefaultValuePipe`, `ParseFilePipe`, `ParseArrayPipe`, and `ParseBoolPipe`; related named pipes cover boolean, date, enum, float, integer, UUID, and validation cases. Common also names logging, serialization, middleware, route, and configuration abstractions, placing those cross-cutting symbols under one package boundary. ## What it needs, and who needs it Common needs no dependency within this repository. Its consumers include `Core`, `Cats`, and integrations for injector, inspector, scopes, discovery, GraphQL code-first, and hello-world. Without this package, those dependents lose the listed source of common decorators, pipes, interfaces, types, constants, and classes; their references to symbols such as `ValidationPipe` or `Logger` would no longer have this declared upstream package. ## Notable members `DefaultValuePipe` is a work-entry member and signals the default-value pipe path. `ParseFilePipe` is another work-entry member, representing the file-parsing pipe path. `MiddlewareConsumer` stands out because the documentation explicitly defines an interface for applying user-defined middleware to routes; `MiddlewareConfiguration`, `MiddlewareConfigProxy`, `NestMiddleware`, and `RouteInfo` place that interface in a named middleware-and-routing group. `ConsoleLogger` and `Logger` similarly mark logging as part of Common’s shared surface. 353 entities in `packages/common`. **8 other subsystems depend on it**, which makes it the most depended-upon part of this codebase. ## What it is made of Its 353 entities sit in 161 files under `packages/common`: 92 interfaces, 85 functions, 63 constants, 32 type aliases and 81 more. `route-params.decorator.ts` holds 36 of them — more than any other file here. `HttpException` declares 12 methods, the widest surface here. ## Where work enters - [`DefaultValuePipe`](pipe-defaultvaluepipe) — `packages/common/pipes/default-value.pipe.ts`:1 - [`ParseFilePipe`](pipe-parsefilepipe) — `packages/common/pipes/file/parse-file.pipe.ts`:1 - [`ParseArrayPipe`](pipe-parsearraypipe) — `packages/common/pipes/parse-array.pipe.ts`:1 - [`ParseBoolPipe`](pipe-parseboolpipe) — `packages/common/pipes/parse-bool.pipe.ts`:1 ## How it refuses and fails 6 of its components record a refusal or a failure handler. All 6 of them refuse work outright, under a condition written into the component itself. Their `catch` blocks handle a failure that already happened in 2 places. Of those 2, 1 logs it and continues and 1 turns it into a return value. ## Boundaries **8 other subsystems depend on this one** — `Core`, `Microservices`, `Platform Express`, `Testing`, `Platform Fastify`, `Platform Socket.io`, `Platform Ws`, `Websockets`. Changing what it exposes changes them. Those 8 hold 742 edges between them, unevenly: `Core` reaches in across 471 edges, against 2 from `Platform Socket.io`. What they reach is narrower than the folder: 140 of its 353 members carry every inbound edge — `Type` (59), `Logger` (40) and `isUndefined` (29), plus 137 more. **It depends on no other subsystem in this repository** — it is a leaf. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `*.interface.ts` | across the repository | 67 | `type.interface.ts`, `file.interface.ts`, `on-init.interface.ts`, `abstract.interface.ts` | | `*.decorator.ts` | across the repository | 24 | `sse.decorator.ts`, `bind.decorator.ts`, `catch.decorator.ts`, `inject.decorator.ts` | | `*.exception.ts` | `packages/common/exceptions/` | 23 | `gone.exception.ts`, `http.exception.ts`, `conflict.exception.ts`, `forbidden.exception.ts` | | `*.util.ts` | across the repository | 16 | `cli-colors.util.ts`, `forward-ref.util.ts`, `is-log-level.util.ts`, `load-package.util.ts` | # Core ## What it is responsible for Core manages route-oriented execution through `RouterExplorer`, `RouterExecutionContext`, and `RouterProxy`. Its routing vocabulary includes `Routes`, `RouteTree`, `RouteDefinition`, `PathsExplorer`, `RoutePathFactory`, `RouteParamsFactory`, and `IRouteParamsFactory`; its exception-filter vocabulary includes `RouterExceptionFilters` and `ExceptionsFilter`. The subsystem also has `REQUEST`, `REQUEST_CONTEXT_ID`, and `requestProvider` among its named members. For SSE, its documented behavior transforms “messages” to W3C event stream content. Work enters through `moduleKey`, `moduleName`, `handler`, and `metatype`. ## What it refuses Core refuses the following stated conditions: - `ForbiddenException` when `!canActivate`. - `UnknownRequestMappingException` when `isUndefined(path)`. - `InternalServerErrorException` when `!next`. - “You must return an Observable stream to use Server-Sent Events (SSE).” when `!isObservable(value)`. - `InvalidExceptionFilterException` when `!Array.isArray(filters)`. - `InvalidClassScopeException` when `wrapperRef.scope` is `Scope.REQUEST` or `Scope.TRANSIENT`, or when `!wrapperRef…`. - `UnknownElementException` when `!instance`. ## What it needs, and who needs it Core depends on `Common`, `Websockets`, and `Microservices`. The named dependent side includes integration, integration/inspector/src/[common](subsystem-packages-common), sample/01-cats-app/src/common, sample/10-fastify/src/common, sample/19-auth-jwt/src/auth, sample/36-hmr-esm/src/common, integration/graphql-code-first/src/recipes, integration/injector/src/scoped, integration/inspector/src/core, integration/inspector/src/durable, integration/inspector/src/request-chain, and integration/scopes/src/durable. These projects and areas depend on Core itself. Core, in turn, depends on all three: `Common`, `Websockets`, and `Microservices`. Without Core, the listed dependents have an unsatisfied dependency; without those three, Core has unsatisfied dependencies. ## Notable members `RouterExplorer` carries the route-exploration side indicated by its name and sits alongside `PathsExplorer`, `Routes`, and `RouteTree`. `RouterExecutionContext` carries the execution-context side, while `RouterProxy` marks proxy work around that execution. `RouterExceptionFilters` carries exception-filter work, paired with `ExceptionsFilter`. `RouteParamsFactory` and `IRouteParamsFactory` identify parameter-factory work, and `RoutePathFactory` identifies path-factory work. `RouteDefinition`, `RoutePathMetadata`, `ExcludeRouteMetadata`, `LegacyRouteConverter`, and `RouterModule` show the related route-definition, metadata, conversion, and module surface. `RouterProxyCallback` names the callback counterpart to the proxy. `Resolver`, `ParamProperties`, `ROUTES`, and `targetModulesByContainer` extend the explicitly named routing and module-related surface of Core in this subsystem. 284 entities in `packages/core`. **5 other subsystems depend on it**, which makes it the 2nd most depended-upon part of this codebase. ## What it is made of Its 284 entities sit in 157 files under `packages/core`: 106 classes, 44 functions, 41 interfaces, 29 doc comments and 64 more. `messages.ts` holds 14 of them — more than any other file here. `AbstractHttpAdapter` declares 50 methods, the widest surface here. ## Where work enters It publishes 7 HTTP endpoints — 5 `GET` and 2 `ALL`. None of them declares a guard. - [`moduleKey`](api-endpoint-modulekey) — `packages/core/middleware/container.ts`:27 - [`moduleName`](api-endpoint-modulename) — `packages/core/middleware/container.ts`:68 - [`handler`](api-endpoint-handler-2) — `packages/core/middleware/middleware-module.ts`:94 - [`metatype`](api-endpoint-metatype) — `packages/core/middleware/middleware-module.ts`:202 - [`handler`](api-endpoint-handler-2) — `packages/core/middleware/middleware-module.ts`:287 - [`handler`](api-endpoint-handler-3) — `packages/core/middleware/resolver.ts`:18 ## How it refuses and fails 56 of its components record a refusal or a failure handler. 51 of them refuse work outright, under a condition written into the component itself. Their `catch` blocks handle a failure that already happened in 16 places. Of those 16, 7 log it and continue, 6 let it reach the caller and 3 turn it into a return value. ## Boundaries **5 other subsystems depend on this one** — `Microservices`, `Platform Express`, `Platform Fastify`, `Testing`, `Websockets`. Changing what it exposes changes them. Those 5 hold 130 edges between them, unevenly: `Microservices` reaches in across 61 edges, against 2 from `Platform Fastify`. 473 edges leave it against 130 arriving — it reads more of this repository than this repository reads of it. What they reach is narrower than the folder: 42 of its 284 members carry every inbound edge — `RuntimeException` (11), `NestContainer` (9) and `ApplicationConfig` (8), plus 39 more. Of the 473 it sends out, 471 go to `Common` — more than to any other. It depends on `Common`, `Websockets`, `Microservices`, and on nothing else in this repository. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `*.interface.ts` | across the repository | 19 | `edge.interface.ts`, `node.interface.ts`, `routes.interface.ts`, `extras.interface.ts` | | `*.exception.ts` | `core/errors/exceptions/` | 17 | `runtime.exception.ts`, `invalid-class.exception.ts`, `invalid-module.exception.ts`, `unknown-export.exception.ts` | | `*.hook.ts` | `packages/core/hooks/` | 5 | `on-module-init.hook.ts`, `on-app-shutdown.hook.ts`, `on-app-bootstrap.hook.ts`, `on-module-destroy.hook.ts` | | `call*` | exported symbols | 5 | `callModuleInitHook`, `callAppShutdownHook`, `callModuleDestroyHook`, `callModuleBootstrapHook` | # Websockets ## What it is responsible for Websockets manages WebSocket-facing package entry points and validation boundaries evidenced by `BaseWsInstance`, `AbstractWsAdapter`, and `MESSAGE_MAPPING_METADATA`. Work enters through those symbols, so the subsystem turns their named boundaries into its visible integration surface for consumers. The supplied evidence identifies no additional protocol behavior, transport mechanics, or mapping rules. `MESSAGE_MAPPING_METADATA` marks a metadata-named boundary, while `BaseWsInstance` and `AbstractWsAdapter` mark instance- and adapter-named boundaries. ## What it refuses The subsystem refuses the `!canActivate` condition by raising `WsException`. It refuses filters when `!Array.isArray(filters)` by raising `InvalidExceptionFilterException`. It refuses a socket port when `!Number.isInteger(port)` by raising `InvalidSocketPortException`. The evidence supplies these exception names and triggering expressions, but no literal exception-message text. Therefore the unsoftened developer-facing identifiers available here are `WsException`, `InvalidExceptionFilterException`, and `InvalidSocketPortException`, rather than invented prose messages. ## What it needs, and who needs it Websockets depends on [Common](subsystem-packages-common) and [Core](subsystem-packages-core). The listed dependency direction says this package needs both named subsystems; no supplied evidence describes their APIs or a more specific consequence of either absence. Conversely, integration/inspector/src/chat, integration, sample/02-gateways/src/events, sample/16-gateways-ws/src/events, Core, [Microservices](subsystem-packages-microservices), [Platform Socket.io](subsystem-packages-platform-socket-io), and [Platform Ws](subsystem-packages-platform-ws) depend on Websockets. Without Websockets, each named dependent loses that declared dependency; the evidence does not establish which calls, startup paths, or behaviors then fail. ## Notable members `BaseWsInstance` is a work-entry symbol and a class-named instance boundary. `AbstractWsAdapter` is also a work-entry symbol and an abstract adapter-named boundary. `MESSAGE_MAPPING_METADATA` is the remaining work-entry symbol, a constant whose name explicitly associates it with message mapping metadata. Together they are the only supplied work-entry points, so they carry the clearest documented responsibility within Websockets. The evidence does not state their methods, values, or internal interactions. 87 entities in `packages/websockets`. **4 other subsystems depend on it**, which makes it the 3rd most depended-upon part of this codebase. ## What it is made of Its 87 entities sit in 36 files under `packages/websockets`: 29 doc comments, 15 classes, 14 constants, 14 functions and 15 more. `constants.ts` holds 12 of them — more than any other file here. `WebSocketsController` declares 10 methods, the widest surface here. ## Where work enters - `Readme.md` — `packages/websockets/Readme.md`:1 - [`BaseWsInstance`](interface-basewsinstance) — `packages/websockets/adapters/ws-adapter.ts`:8 - [`AbstractWsAdapter`](class-abstractwsadapter) — `packages/websockets/adapters/ws-adapter.ts`:13 - [`MESSAGE_MAPPING_METADATA`](constant-message-mapping-metadata) — `packages/websockets/constants.ts`:3 ## How it refuses and fails 10 of its components record a refusal or a failure handler. 9 of them refuse work outright, under a condition written into the component itself. Their `catch` blocks handle a failure that already happened in 1 place. ## Boundaries **4 other subsystems depend on this one** — `Core`, `Microservices`, `Platform Socket.io`, `Platform Ws`. Changing what it exposes changes them. Those 4 hold 10 edges between them, unevenly: `Platform Ws` reaches in across 5 edges, while 2 of them hold one each. 79 edges leave it against 10 arriving — it reads more of this repository than this repository reads of it. What they reach is narrower than the folder: 7 of its 87 members carry every inbound edge — `SocketModule` (2), `AbstractWsAdapter` (2) and `MessageMappingProperties` (2), plus 4 more. Of the 79 it sends out, 43 go to `Common` — more than to any other. It depends on `Common`, `Core`, and on nothing else in this repository. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `*.interface.ts` | across the repository | 9 | `ws-response.interface.ts`, `nest-gateway.interface.ts`, `on-gateway-init.interface.ts`, `gateway-metadata.interface.ts` | | `*.decorator.ts` | `packages/websockets/decorators/` | 6 | `ack.decorator.ts`, `message-body.decorator.ts`, `gateway-server.decorator.ts`, `socket-gateway.decorator.ts` | # Microservices ## What it is responsible for Microservices manages work entering through `normalizedPattern`, `route`, and `ClientsModule` for the Nest framework, whose authors describe Nest as a framework for building Node.js server-side applications. It owns the subsystem boundary implied by those entry points and by its use from integration and sample code, including TCP/TLS, gRPC, Kafka, MQTT, NATS, and Redis paths. Its work depends on [Common](subsystem-packages-common), [Core](subsystem-packages-core), and [Websockets](subsystem-packages-websockets). ## What it refuses The subsystem rejects an absent gRPC client reference with `InvalidGrpcServiceException` when `!clientRef`. It rejects Kafka topic handling with `InvalidKafkaClientTopicException` when `isUndefined(minimumPartition)`. When `!this._consumer`, it says: “No consumer initialized. Please, call the "connect" method first.” When `!this._producer`, it says: “No producer initialized. Please, call the "connect" method first.” When `!this.client`, it says: “Not initialized. Please call the "connect" method first.” When `!this.mqttClient`, it says: “Not initialized. Please call the "connect" method first.” ## What it needs, and who needs it Microservices needs Common, Core, and Websockets. Without it, the named dependents—integration, the TCP/TLS microservices integration, sample math, sample hero, inspector external service, and the gRPC, Kafka, MQTT, NATS, and Redis integrations—lose their declared dependency on this subsystem. This evidence names dependency relationships; it does not state a more specific failure mode. ## Notable members `ClientsModule`, `normalizedPattern`, and `route` are notable because the supplied evidence names all three as places where work enters. They share the strongest directly stated role in this subsystem: accepting incoming work at its boundary. The evidence does not distinguish their individual internal behavior, lifecycle, or relationship to the client, consumer, producer, gRPC, Kafka, or MQTT checks. Accordingly, no member-specific implementation claim is warranted beyond their shared entry-point status. 429 entities in `packages/microservices`. **1 other subsystem depends on it**, which makes it the 4th most depended-upon part of this codebase. ## What it is made of Its 429 entities sit in 117 files under `packages/microservices`: 99 interfaces, 98 type aliases, 97 classes, 52 constants and 83 more. `kafka.interface.ts` holds 156 of them — more than any other file here. `Server` declares 24 methods, the widest surface here. ## Where work enters It publishes 2 `GET` endpoints. None of them declares a guard. - [`normalizedPattern`](api-endpoint-normalizedpattern) — `packages/microservices/server/server.ts`:150 - [`route`](api-endpoint-route) — `packages/microservices/server/server.ts`:168 - [`ClientsModule`](module-clientsmodule) — `packages/microservices/module/clients.module.ts`:17 ## How it refuses and fails 33 of its components record a refusal or a failure handler. 31 of them refuse work outright, under a condition written into the component itself. Their `catch` blocks handle a failure that already happened in 29 places. Of those 29, 13 turn it into a return value, 10 log it and continue, 5 let it reach the caller and 1 discards it without recording anything. ## Boundaries **1 other subsystem depends on this one** — `Core`. Changing what it exposes changes them. They hold 1 edge into it between them. 185 edges leave it against 1 arriving — it reads more of this repository than this repository reads of it. What they reach is narrower than the folder: 1 of its 429 members carries every inbound edge — `MicroservicesModule` (1). Of the 185 it sends out, 123 go to `Common` — more than to any other. It depends on `Common`, `Core`, `Websockets`, and on nothing else in this repository. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `*.interface.ts` | across the repository | 20 | `kafka.interface.ts`, `redis.interface.ts`, `packet.interface.ts`, `rmq-url.interface.ts` | | `*.exception.ts` | `packages/microservices/errors/` | 14 | `empty-response.exception.ts`, `invalid-message.exception.ts`, `net-socket-closed.exception.ts`, `invalid-json-format.exception.ts` | | `*.context.ts` | `packages/microservices/ctx-host/` | 7 | `rmq.context.ts`, `tcp.context.ts`, `mqtt.context.ts`, `nats.context.ts` | | `*.deserializer.ts` | `packages/microservices/deserializers/` | 7 | `identity.deserializer.ts`, `kafka-request.deserializer.ts`, `kafka-response.deserializer.ts`, `incoming-request.deserializer.ts` | # Platform Express ## What it is responsible for Platform Express manages the Express-oriented integration surface whose stated work entry is `MulterModule`. Its named members place `MulterModule` alongside `FileInterceptor`, `FilesInterceptor`, `AnyFilesInterceptor`, `FileFieldsInterceptor`, and `NoFilesInterceptor`; together, those symbols identify the subsystem’s interception-facing API. The available evidence does not state the behavior, configuration, or output of these members, so their documented responsibility should stop at that boundary. In the surrounding project material, the authors describe Nest as a framework for building Node.js server-side applications and direct readers to the guide at docs.nestjs.com. ## What it refuses Platform Express refuses work when `!next` and the HTTP adapter does not support filtering on version. The recorded refusal condition is: “HTTP adapter does not support filtering on version.” No other rejection message or condition is supplied by the evidence. ## What it needs, and who needs it Platform Express depends on [Common](subsystem-packages-common) and [Core](subsystem-packages-core). `MulterModule` is the declared work entry within that dependency context. The `sample` subsystem depends on Platform Express; without Platform Express, `sample` cannot satisfy that declared dependency. The evidence does not say which Common or Core contracts are required, nor does it identify a more specific failure mode for `sample`. ## Notable members `MulterModule` is the entry point for work in Platform Express. `FileInterceptor` and `FilesInterceptor` are named interception members; their names distinguish singular and plural forms, but the evidence gives no operational description. These three are notable because the entry point is identified and the two interceptors are named. The evidence does not rank the remaining members, specify configuration, or describe outputs. Project documentation covers questions, issues, consulting, support, sponsors, and license material; those comments do not establish responsibilities. 52 entities in `packages/platform-express`. Nothing else in this repository depends on it. ## What it is made of Its 52 entities sit in 19 files under `packages/platform-express`: 29 doc comments, 7 functions, 7 interfaces, 4 constants and 5 more. `files-upload-module.interface.ts` holds 3 of them — more than any other file here. `ExpressAdapter` declares 36 methods, the widest surface here. ## Where work enters - [`MulterModule`](module-multermodule) — `packages/platform-express/multer/multer.module.ts`:14 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. Its `catch` blocks handle a failure that already happened in 2 places. ## Boundaries It depends on `Common`, `Core`, and on nothing else in this repository. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `*.interface.ts` | across the repository | 6 | `multer-options.interface.ts`, `files-upload-module.interface.ts`, `serve-static-options.interface.ts`, `nest-express-application.interface.ts` | | `*.interceptor.ts` | `platform-express/multer/interceptors/` | 5 | `file.interceptor.ts`, `files.interceptor.ts`, `no-files.interceptor.ts`, `any-files.interceptor.ts` | # Platform Fastify ## What it is responsible for Platform Fastify manages the package-level boundary identified by `FastifyAdapter`, `MiddlewareFn`, and `FASTIFY_ROUTE_CONFIG_METADATA`. Available evidence places work into this subsystem through those symbols and `Readme.md`; it identifies [Common](subsystem-packages-common) and [Core](subsystem-packages-core) as its dependencies. Its documentation describes Nest as a Node.js server-side application framework, while this subsystem’s named entry points identify the Fastify-specific surface. The evidence does not describe request handling, route execution, metadata interpretation, or adapter behavior enough detail to state those mechanisms as facts. ## What it refuses Platform Fastify rejects a version constraint when its value is neither a string nor an array of strings. Its message is: “Version constraint should be a string or an array of strings.” In the condition, rejection occurs when `!isString(value) && !Array.isArray(value)`. No other rejection conditions or messages are supplied by the evidence. ## What it needs, and who needs it Platform Fastify depends on Common and Core. Common and Core are therefore the named upstream sides required by this subsystem; without them, the dependency relationship is unmet, although the evidence does not say which symbols or runtime paths fail. No subsystem is listed as depending on Platform Fastify, so the supplied information identifies no named downstream consumer that would break without it. Work enters through `FastifyAdapter`, `MiddlewareFn`, or `FASTIFY_ROUTE_CONFIG_METADATA`; no other named user is identified by the supplied evidence. ## Notable members `FastifyAdapter` is a work entry point and the adapter-named symbol. `MiddlewareFn` is another entry point, identifying middleware as a named concern without documenting its signature or behavior. `FASTIFY_ROUTE_CONFIG_METADATA` is a constant and entry point whose name identifies route configuration metadata; the evidence does not specify its value, format, or consumers. 44 entities in `packages/platform-fastify`. Nothing else in this repository depends on it. ## What it is made of Its 44 entities sit in 11 files under `packages/platform-fastify`: 29 doc comments, 5 interfaces, 3 constants, 3 functions and 4 more. `constants.ts` holds 3 of them — more than any other file here. `FastifyAdapter` declares 50 methods, the widest surface here. ## Where work enters - `Readme.md` — `packages/platform-fastify/Readme.md`:1 - [`FastifyAdapter`](class-fastifyadapter) — `packages/platform-fastify/adapters/fastify-adapter.ts`:124 - [`MiddlewareFn`](type-middlewarefn) — `packages/platform-fastify/adapters/middie/fastify-middie.ts`:17 - [`FASTIFY_ROUTE_CONFIG_METADATA`](constant-fastify-route-config-metadata) — `packages/platform-fastify/constants.ts`:1 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. Its `catch` blocks handle a failure that already happened in 2 places. ## Boundaries It depends on `Common`, `Core`, and on nothing else in this repository. # Testing ## What it is responsible for The Testing subsystem manages the testing package’s named work-entry surface through `TestingLogger`, `MockFactory`, and `OverrideByFactoryOptions`. Its documented material also directs developers to the Nest guide at docs.nestjs.com, the official Discord channel for questions and support, and the Issue Reporting Checklist before an issue is opened. The package’s responsibility is bounded by the available evidence: the listed symbols identify logging, mock-factory, and factory-override-option concerns, while the supplied comments do not describe their detailed behavior. ## What it refuses It refuses to continue when an internal [core](subsystem-packages-core) module reference is absent: “Expected to have internal core module reference at this point.” The stated condition is `!internalCoreModule`; this is a hard rejection, not a fallback path described by the evidence. ## What it needs, and who needs it Testing depends on the [Common](subsystem-packages-common) and Core subsystems. In particular, the refusal condition shows that the relevant path needs `internalCoreModule` at that point. No subsystem is listed as depending on Testing. Therefore the evidence names no consumer-side subsystem and identifies no specific downstream behavior that breaks without Testing; only its own path is known to reject the missing internal-core reference. ## Notable members `TestingLogger` is a work-entry symbol and carries the package’s explicitly named logger role. `MockFactory` is another work-entry symbol; its name identifies the factory as mock-oriented, but the evidence does not state creation rules, lifetime, or output. `OverrideByFactoryOptions` is the third work-entry symbol and represents factory-based override options. Together, these symbols mark the visible testing-facing path, while the source material does not establish a call sequence among them. No documented member-level dependency or implementation contract is explicitly stated here. 41 entities in `packages/testing`. Nothing else in this repository depends on it. ## What it is made of Its 41 entities sit in 11 files under `packages/testing`: 29 doc comments, 6 classes, 3 interfaces, 2 type aliases and 1 more. `testing-module.builder.ts` holds 2 of them — more than any other file here. `TestingModuleBuilder` declares 9 methods, the widest surface here. ## Where work enters - [`TestingLogger`](class-testinglogger) — `packages/testing/services/testing-logger.service.ts`:6 - `Readme.md` — `packages/testing/Readme.md`:1 - [`MockFactory`](type-mockfactory) — `packages/testing/interfaces/mock-factory.ts`:3 - [`OverrideByFactoryOptions`](interface-overridebyfactoryoptions) — `packages/testing/interfaces/override-by-factory-options.interface.ts`:4 ## How it refuses and fails 2 of its components record a refusal or a failure handler. All 2 of them refuse work outright, under a condition written into the component itself. Their `catch` blocks handle a failure that already happened in 2 places. ## Boundaries It depends on `Common`, `Core`, and on nothing else in this repository. # Platform Socket.io ## What it is responsible for Platform Socket.io manages the Socket.io-facing platform boundary represented by `IoAdapter`, connecting this package with its named `Websockets` and `Common` dependencies. Its documented entry points are `Readme.md` and `IoAdapter`, so the README supplies the package’s public orientation while the adapter is the identified code entry. The available comments describe Nest as a framework for Node.js server-side applications and direct readers to its guide and official support channels; they do not state further Socket.io-specific behavior. ## What it needs, and who needs it This package depends on `Common` and `Websockets`; both are named dependency edges rather than described APIs. `sample/02-gateways/src/adapters` depends on Platform Socket.io, making that sample the stated downstream consumer. Without this package, that dependency relationship cannot be satisfied. The evidence does not identify a specific runtime failure or an alternative adapter path. Likewise, it does not explain how `Common` or `Websockets` are used. ## Notable members `IoAdapter` is the sole identified class and a work-entry symbol; it carries the code-level responsibility visible in the evidence. `Readme.md` is the other work entry and documents the project’s guide, Discord questions-and-support route, issue-reporting checklist, consulting, sponsorship, and MIT license. No methods or protocol are named, so no behavior is characterized. 31 entities in `packages/platform-socket.io`. Nothing else in this repository depends on it. ## What it is made of Its 31 entities sit in 2 files under `packages/platform-socket.io`: 29 doc comments, 1 markdown doc and 1 class. `IoAdapter` declares 5 methods, the widest surface here. ## Where work enters - `Readme.md` — `packages/platform-socket.io/Readme.md`:1 - [`IoAdapter`](class-ioadapter) — `packages/platform-socket.io/adapters/io-adapter.ts`:14 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. ## Boundaries It depends on `Common`, `Websockets`, and on nothing else in this repository. # Platform Ws ## What it is responsible for Platform Ws manages the subsystem boundary entered through `WsAdapter`, with `Readme.md` serving as its documented entry point. The available inventory identifies `WsAdapter` as the sole class and identifies `Common` and `Websockets` as dependencies. Its accompanying documentation frames Nest as a framework for Node.js server-side applications and directs readers to the Nest guide and support channels. The evidence does not state the adapter’s methods, protocol behavior, or lifecycle responsibilities. ## What it needs, and who needs it Platform Ws needs `Common` and `Websockets`, which are recorded as its dependencies. `WsAdapter` and the documentation entry represented by `Readme.md` need those dependencies insofar as they belong to this subsystem; the supplied evidence gives no narrower dependency mapping. No other subsystem is listed as depending on Platform Ws. Therefore, a missing `Common` or `Websockets` dependency breaks the recorded dependency relationship for Platform Ws, while the supplied inventory identifies no downstream dependent that would break through it. ## Notable members `WsAdapter` carries the identifiable code-level role: it is the class through which work enters Platform Ws. `Readme.md` carries the documented orientation role, linking readers to the guide, Discord support, issue-reporting guidance, licensing, and sponsor material. Other named documentation headings describe community, support, and project-information topics rather than additional executable responsibility within supplied evidence for this package. 31 entities in `packages/platform-ws`. Nothing else in this repository depends on it. ## What it is made of Its 31 entities sit in 2 files under `packages/platform-ws`: 29 doc comments, 1 markdown doc and 1 class. `WsAdapter` declares 10 methods, the widest surface here. ## Where work enters - `Readme.md` — `packages/platform-ws/Readme.md`:1 - [`WsAdapter`](class-wsadapter) — `packages/platform-ws/adapters/ws-adapter.ts`:39 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. Its `catch` blocks handle a failure that already happened in 2 places. Of those 2, 1 logs it and continues and 1 turns it into a return value. ## Boundaries It depends on `Common`, `Websockets`, and on nothing else in this repository.