# NestJS head-to-head # addRecipe **Kind:** Graphql Mutation **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` - TYPE_OF β†’ `NewRecipeInput` ## Referenced By - `Mutation` (CALLS_API) # anonymousMiddleware **Kind:** Middleware **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L77) # AudioController **Kind:** Controller **Source:** [`sample/26-queues/src/audio/audio.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/26-queues/src/audio/audio.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AudioController client->>+p1: AudioController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `transcode` - DEPENDS_ON β†’ `queue` ## Referenced By - `AppModule` (MODULE_DECLARES) - `AudioModule` (MODULE_DECLARES) # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/disconnected.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/disconnected.controller.ts#L14) ## Endpoint `POST /` ## Referenced By - `DisconnectedClientController` (MODULE_DECLARES) # cat **Kind:** Graphql Query **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Query` (CALLS_API) # catCreated **Kind:** Graphql Subscription **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Subscription` (CALLS_API) # 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) ## Referenced By - `HeroController` (DEPENDS_ON) # ClientProxy **Kind:** Class **Source:** [`packages/microservices/client/client-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-proxy.ts#L38) `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. ## Referenced By - `AppController` (DEPENDS_ON) - `AppController` (DEPENDS_ON) - `AppController` (DEPENDS_ON) - `AppController` (DEPENDS_ON) - `AppController` (DEPENDS_ON) - `AppController` (DEPENDS_ON) - `MathController` (DEPENDS_ON) # ClientsModule **Kind:** Module **Source:** [`packages/microservices/module/clients.module.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/module/clients.module.ts#L17) # Core ### What it is responsible for Core manages Nest's core functionality, low-level services, and utilities, while routing work through symbols such as `RouterExplorer`, `RouterExecutionContext`, and `RouterProxy`. Its named routing members, `Routes`, `RouteTree`, `RouteDefinition`, `RoutePathFactory`, and `RouteParamsFactory`, indicate responsibility for route definitions, paths, parameters, exploration, and execution context. `RouterExceptionFilters` and `ExceptionsFilter` place exception filter handling alongside that route work. The subsystem also owns request symbols including `REQUEST`, `REQUEST_CONTEXT_ID`, and `requestProvider`. For SSE, its documented transformer turns β€œmessages” into W3C event stream content; the relevant path demands an Observable stream. ### What it refuses Core rejects forbidden activation with `ForbiddenException` when `!canActivate`; undefined request mappings with `UnknownRequestMappingException` when `isUndefined(path)`; and missing continuation with `InternalServerErrorException` when `!next`. It rejects non Observable SSE results with: β€œYou must return an Observable stream to use Server-Sent Events (SSE).” when `!isObservable(value)`. It rejects non array filters with `InvalidExceptionFilterException` when `!Array.isArray(filters)`, invalid class scopes with `InvalidClassScopeException` when `wrapperRef.scope === Scope.REQUEST || wrapperRef.scope === Scope.TRANSIENT || !wrapperRef…`, and absent instances with `UnknownElementException` when `!instance`. ### What it needs, and who needs it Core has no dependencies in this repository. [Integration](subsystem-integration), `integration/inspector/src/common`, `sample/01-cats-app/src/common`, `sample/10-fastify/src/common`, [Auth](subsystem-sample-19-auth-jwt-src-auth), and `sample/36-hmr-esm/src/common` depend on it. Without Core, those named dependents lack the subsystem they declare as a dependency. The recorded work entry names are `moduleKey`, `moduleName`, `handler`, and `metatype`; `handler` appears three times in that record. The available evidence identifies no further repository need. ### Notable members `RouterExplorer` is a routing member named with `PathsExplorer` and `RouterModule`; it marks route exploration. `RouterExecutionContext` is named with `RouterProxy` and `RouterProxyCallback`; it marks execution context, proxies, and callbacks. `RouterExceptionFilters` and `ExceptionsFilter` mark exception filter handling; `RouteParamsFactory` and `RoutePathFactory` mark parameter and path factory roles. 285 entities in `packages/core`. **6 other subsystems depend on it**, which makes it the most depended-upon part of this codebase. ## What it is made of Its 285 entities sit in 158 files under `packages/core`: 106 classes, 45 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` β€” `packages/core/middleware/container.ts`:27 - `moduleName` β€” `packages/core/middleware/container.ts`:68 - `handler` β€” `packages/core/middleware/middleware-module.ts`:94 - `metatype` β€” `packages/core/middleware/middleware-module.ts`:202 - `handler` β€” `packages/core/middleware/middleware-module.ts`:287 - `handler` β€” `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 17 places. Of those 17, 8 log it and continue, 6 let it reach the caller and 3 turn it into a return value. ## Boundaries **6 other subsystems depend on this one** β€” `Integration`, `Inspector`, `01 Cats App`, `10 Fastify`, `Auth`, `36 Hmr Esm`. Changing what it exposes changes them. Those 6 hold 7 edges between them, unevenly: `Integration` reaches in across 2 edges, while 5 of them hold one each. What they reach is narrower than the folder: 3 of its 285 members carry every inbound edge β€” `Reflector` (5), `DiscoveryModule` (1) and `LazyModuleLoader` (1). **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 | 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` | # 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) ## Signature ```ts function forwardRef(fn: () => any): ForwardReference ``` ## Parameters | Name | Type | |---|---| | `fn` | `() => any` | **Returns:** `ForwardReference` ## Referenced By - `CircularModule` (MODULE_IMPORTS) - `InputModule` (MODULE_IMPORTS) - `CircularPropertiesModule` (MODULE_IMPORTS) - `InputPropertiesModule` (MODULE_IMPORTS) - `CircularModule` (MODULE_IMPORTS) - `InputModule` (MODULE_IMPORTS) - `AModule` (MODULE_IMPORTS) - `BModule` (MODULE_IMPORTS) # 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) ## 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` # Logger **Kind:** Service **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L1) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ Logger client->>+p1: Logger p1-->client: return response ``` ## Referenced By - `RequestLogger` (DEPENDS_ON) - `TransientLogger` (DEPENDS_ON) - `HelloModule` (MODULE_PROVIDES) # 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) # Photo **Kind:** Database Model **Source:** [`sample/13-mongo-typeorm/src/photo/photo.entity.ts`](https://github.com/nestjs/nest/blob/master/sample/13-mongo-typeorm/src/photo/photo.entity.ts#L4) The `Photo` entity represents image metadata stored in MongoDB through TypeORM. It captures a photo’s display name, description, stored filename, and publication status for use by application services and API endpoints. ## Fields | Field | Type | Required | Key | |---|---|---|---| | `name` | `varchar` | βœ“ | | | `description` | `varchar` | βœ“ | | | `filename` | `varchar` | βœ“ | | | `isPublished` | `boolean` | βœ“ | | ## Diagram ```mermaid erDiagram PHOTO { string name string description string filename boolean isPublished } ``` ## Usage ```ts import { AppDataSource } from '../data-source'; import { Photo } from './photo.entity'; const photoRepository = AppDataSource.getMongoRepository(Photo); const photo = photoRepository.create({ name: 'Mountain sunrise', description: 'A sunrise captured from the summit trail.', filename: 'mountain-sunrise.jpg', isPublished: false, }); await photoRepository.save(photo); photo.isPublished = true; await photoRepository.save(photo); const publishedPhotos = await photoRepository.find({ where: { isPublished: true }, }); ``` ## AI Coding Instructions - Use TypeORM’s MongoDB repository APIs, such as `getMongoRepository(Photo)`, when querying or saving `Photo` records. - Populate `filename` with the storage identifier or uploaded file name; do not store binary image content directly in this entity. - Treat `isPublished` as the visibility flag and ensure unpublished photos are filtered from public-facing queries. - Keep `name` and `description` suitable for display in client applications, validating user-provided values before persistence. # Post **Kind:** Graphql Type **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) `Post` is a GraphQL object type representing a blog or content post in the application. It exposes the post identifier, title, body text, and publication status for use in queries and other GraphQL operations. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Query[GraphQL Query] Query --> Post[Post Object Type] Post --> ID[id: ID!] Post --> Title[title: String!] Post --> Text[text: String!] Post --> Published[isPublished: Boolean!] ``` ## Usage ```ts import { gql } from "@apollo/client"; const GET_POSTS = gql` query GetPosts { posts { id title text isPublished } } `; // Example response item: // { // id: "post_123", // title: "Getting Started with GraphQL", // text: "GraphQL provides a flexible API query language...", // isPublished: true // } ``` ## AI Coding Instructions - Treat all `Post` fields as required because the schema marks them with non-null (`!`) types. - Request only the fields needed by the client; GraphQL responses include exactly the selected fields. - Use `id` as the stable identifier when rendering lists, updating cached results, or performing mutations. - Filter unpublished posts in the resolver or query layer when public clients should not access drafts. - Keep TypeScript-generated GraphQL types synchronized with schema changes to preserve field nullability and names. ## Referenced By - `posts` (TYPE_OF) - `post` (TYPE_OF) - `createPost` (TYPE_OF) - `updatePost` (TYPE_OF) - `deletePost` (TYPE_OF) - `postCreated` (TYPE_OF) # superJSONProvider **Kind:** Constant **Source:** [`sample/34-using-esm-packages/src/superjson.provider.ts`](https://github.com/nestjs/nest/blob/master/sample/34-using-esm-packages/src/superjson.provider.ts#L7) ## Definition ```ts FactoryProvider ``` ## Value ```ts { provide: 'SuperJSON', useFactory: () => importEsmPackage('superjson'), } ``` ## Referenced By - `AppModule` (MODULE_PROVIDES) # NestJS head-to-head ## Overview Auto-generated technical documentation for **NestJS head-to-head** β€” 2831 entities (725 doc comments, 394 classs, 281 interfaces, 231 api endpoints). ## Architecture ```mermaid flowchart LR service_ConsoleLogger_38089336["ConsoleLogger"] service_Logger_56f71189["Logger"] service_BarService_4c69a33e["BarService"] service_FooService_2bfde624["FooService"] controller_AppController_38e3c15["AppController"] module_AppModule_698988b["AppModule"] module_AppModule_25446c3e["AppModule"] module_MyWebhookModule_1e865006["MyWebhookModule"] module_AppModule_3541c3e4["AppModule"] service_AuthGuard_5759b537["AuthGuard"] service_DataInterceptor_c8076b7["DataInterceptor"] module_RecipesModule_567dcf2["RecipesModule"] service_RecipesService_50ffcca6["RecipesService"] module_AppModule_76187e70["AppModule"] module_AsyncClassApplicationModule_75045ad4["AsyncClassApplicationModule"] module_AsyncExistingApplicationModule_65e570a["AsyncExistingApplicationModule"] module_AsyncApplicationModule_770a11f7["AsyncApplicationModule"] service_CatsRequestScopedService_4eb9ee96["CatsRequestScopedService"] service_CatsGuard_5f960eea["CatsGuard"] module_CatsModule_4a1670f4["CatsModule"] service_CatsService_3b65834a["CatsService"] module_ConfigModule_67f1f1a["ConfigModule"] service_ConfigService_5fb4643a["ConfigService"] module_AppModule_35b2a3f7["AppModule"] service_BarService_4c69a33e --> service_FooService_2bfde624 module_AppModule_25446c3e --> module_MyWebhookModule_1e865006 ``` ## Modules - **AppModule** - **AppModule** - **MyWebhookModule** - **AppModule** - **RecipesModule** - **AppModule** - **AsyncClassApplicationModule** - **AsyncExistingApplicationModule** - **AsyncApplicationModule** - **CatsModule** - **ConfigModule** - **AppModule** - **HelloModule** - **HostModule** - **HostArrayModule** - **ApplicationModule** - **CircularModule** - **CircularModule** - **InputModule** - **CircularPropertiesModule** - **InputPropertiesModule** - **CoreInjectablesModule** - **DefaultsModule** - **NestDynamicModule** - **ExportsModule** - **InjectSameNameModule** - **InjectModule** - **AModule** - **BModule** - **CModule** - **MultipleProvidersModule** - **PropertiesModule** - **ScopedModule** - **SelfInjectionProviderModule** - **SelfInjectionForwardProviderModule** - **SelfInjectionProviderCustomTokenModule** - **AppModule** - **CatsModule** - **ChatModule** - **HelloModule** - **CircularModule** - **InputModule** - **CoreModule** - **DatabaseModule** - **DefaultsModule** - **DogsModule** - **DurableModule** - **ExternalSvcModule** - **PropertiesModule** - **HelperModule** - **RequestChainModule** - **UsersModule** - **AppModule** - **EagerModule** - **GlobalModule** - **LazyModule** - **RequestLazyModule** - **TransientLazyModule** - **ConfigModule** - **AppModule** - **ConfigModule** - **ApplicationModule** - **IntegrationModule** - **ApplicationModule** - **AsyncOptionsClassModule** - **ConfigModule** - **AsyncOptionsExistingModule** - **AsyncOptionsFactoryModule** - **CatsModule** - **AppModule** - **AppModule** - **AppModule** - **AppModule** - **ExpressModule** - **FastifyModule** - **AppModule** - **AppModule** - **AppModule** - **DatabaseModule** - **LongLivingAppModule** - **UsersModule** - **ApplicationModule** - **HelloModule** - **HelloModule** - **DurableModule** - **HelloModule** - **HelloModule** - **HelloModule** - **NestedTransientModule** - **HelperModule** - **RequestChainModule** - **HelloModule** - **AppModule** - **AModule** - **BModule** - **AsyncApplicationModule** - **AppModule** - **AsyncOptionsClassModule** - **ConfigModule** - **AsyncOptionsExistingModule** - **AsyncOptionsFactoryModule** - **DatabaseModule** - **PhotoModule** - **AppModule** - **ApplicationModule** - **ClientsModule** - **MulterModule** - **AppModule** - **CatsModule** - **CoreModule** - **AppModule** - **EventsModule** - **AppModule** - **MathModule** - **AppModule** - **HeroModule** - **AppModule** - **UsersModule** - **AppModule** - **CatsModule** - **AppModule** - **UsersModule** - **AppModule** - **AppModule** - **CatsModule** - **CoreModule** - **AppModule** - **CatsModule** - **AppModule** - **CatsModule** - **OwnersModule** - **AppModule** - **PhotoModule** - **AppModule** - **CatsModule** - **DatabaseModule** - **AppModule** - **AppModule** - **EventsModule** - **AppModule** - **AppModule** - **MyDynamicModule** - **AppModule** - **AuthModule** - **UsersModule** - **AppModule** - **AppModule** - **AppModule** - **PostsModule** - **PrismaModule** - **AppModule** - **RecipesModule** - **AppModule** - **AppModule** - **ConfigModule** - **AppModule** - **AudioModule** - **AppModule** - **TasksModule** - **AppModule** - **AppModule** - **AppModule** - **OrdersModule** - **AppModule** - **AppModule** - **PostsModule** - **AppModule** - **UsersModule** - **AppModule** - **AppModule** - **PostsModule** - **AppModule** - **UsersModule** - **AppModule** - **RecipesModule** - **AppModule** - **AppModule** - **AppModule** - **CatsModule** - **CoreModule** - **AppModule** ## Entry Points - Controller: **AppController** (`integration/cors/src/app.controller.ts`) - Controller: **ErrorsController** (`integration/hello-world/src/errors/errors.controller.ts`) - Controller: **HelloController** (`integration/hello-world/src/hello/hello.controller.ts`) - Controller: **HostController** (`integration/hello-world/src/host/host.controller.ts`) - Controller: **HostArrayController** (`integration/hello-world/src/host-array/host-array.controller.ts`) - Controller: **ScopedController** (`integration/injector/src/scoped/scoped.controller.ts`) - Controller: **AppV1Controller** (`integration/inspector/src/app-v1.controller.ts`) - Controller: **AppV2Controller** (`integration/inspector/src/app-v2.controller.ts`) - Controller: **CatsController** (`integration/inspector/src/cats/cats.controller.ts`) - Controller: **HelloController** (`integration/inspector/src/circular-hello/hello.controller.ts`) - Controller: **DatabaseController** (`integration/inspector/src/database/database.controller.ts`) - Controller: **DogsController** (`integration/inspector/src/dogs/dogs.controller.ts`) - Controller: **DurableController** (`integration/inspector/src/durable/durable.controller.ts`) - Controller: **ExternalSvcController** (`integration/inspector/src/external-svc/external-svc.controller.ts`) - Controller: **RequestChainController** (`integration/inspector/src/request-chain/request-chain.controller.ts`) - Controller: **UsersController** (`integration/inspector/src/users/users.controller.ts`) - Controller: **LazyController** (`integration/lazy-modules/src/lazy.controller.ts`) - Controller: **AppController** (`integration/microservices/src/app.controller.ts`) - Controller: **DisconnectedClientController** (`integration/microservices/src/disconnected.controller.ts`) - Controller: **GrpcController** (`integration/microservices/src/grpc/grpc.controller.ts`) - `GET /` β†’ getGlobals - `GET /sync` β†’ synchronous - `GET /async` β†’ asynchronous - `GET /unexpected-error` β†’ unexpectedError - `GET /hello` β†’ greeting - `GET /hello/async` β†’ asyncGreeting - `GET /hello/stream` β†’ streamGreeting - `GET /hello/local-pipe/:id` β†’ localPipe - `GET /` β†’ greeting - `GET /async` β†’ asyncGreeting - `GET /stream` β†’ streamGreeting - `GET /local-pipe/:id` β†’ localPipe - `GET /` β†’ greeting - `GET /async` β†’ asyncGreeting - `GET /stream` β†’ streamGreeting - `GET /local-pipe/:id` β†’ localPipe - `GET /` β†’ helloWorldV1 - `GET /:param/hello` β†’ paramV1 - `GET /` β†’ helloWorldV2 - `GET /:param/hello` β†’ paramV1 - `POST /cats` β†’ create - `GET /cats` β†’ findAll - `GET /cats/:id` β†’ findOne - `GET /hello` β†’ greeting - `POST /database` β†’ create - `GET /database` β†’ findAll - `GET /database/:id` β†’ findOne - `PATCH /database/:id` β†’ update - `DELETE /database/:id` β†’ remove - `POST /dogs` β†’ create ## Key Components _The most-referenced entities β€” start here._ - **forwardRef** (function) β€” referenced 8Γ— - **ClientProxy** (class) β€” referenced 7Γ— - **GlobalService** (service) β€” referenced 6Γ— - **Post** (graphql type) β€” referenced 6Γ— - **Reflector** (class) β€” referenced 5Γ— - **EagerService** (service) β€” referenced 5Γ— - **Cat** (graphql type) β€” referenced 5Γ— - **Recipe** (graphql type) β€” referenced 4Γ— - **Cat** (graphql type) β€” referenced 4Γ— - **Recipe** (graphql type) β€” referenced 4Γ— ## 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 | |---|---|---|---| | **Core** | 6 | 285 | `moduleKey`, `moduleName` | | **Common** | 5 | 353 | `DefaultValuePipe`, `ParseFilePipe` | | **Microservices** | 4 | 435 | `normalizedPattern`, `route` | | **Dogs** | 1 | 11 | `DogsController`, `create` | | **Host** | 1 | 10 | `HostController`, `greeting` | | **Host Array** | 1 | 10 | `HostArrayController`, `greeting` | | **Auth** | 1 | 9 | `AuthController`, `signIn` | | **Orders** | 1 | 8 | `OrdersController`, `create` | | **Integration** | 0 | 188 | `AppController`, `getGlobals` | | **Sample** | 0 | 449 | `AppController`, `getHello` | `Core`, `Common`, `Microservices`, `Dogs`, `Host`, `Host Array`, `Orders` 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 | |---|---|---|---| | `*.module.ts` | across the repository | 176 | `a.module.ts`, `b.module.ts`, `c.module.ts`, `app.module.ts` | | `*.interface.ts` | across the repository | 140 | `cat.interface.ts`, `type.interface.ts`, `file.interface.ts`, `edge.interface.ts` | | `*.service.ts` | across the repository | 114 | `bar.service.ts`, `foo.service.ts`, `app.service.ts`, `cats.service.ts` | | `*.controller.ts` | across the repository | 97 | `app.controller.ts`, `rmq.controller.ts`, `host.controller.ts`, `cats.controller.ts` | | `*.exception.ts` | across the repository | 55 | `gone.exception.ts`, `http.exception.ts`, `runtime.exception.ts`, `conflict.exception.ts` | | `*.decorator.ts` | across the repository | 44 | `sse.decorator.ts`, `ctx.decorator.ts`, `ack.decorator.ts`, `bind.decorator.ts` | # TenantContext **Kind:** Type **Source:** [`integration/scopes/src/durable/durable-context-id.strategy.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable-context-id.strategy.ts#L4) ## Definition ```ts { tenantId: string; forceError?: boolean; } ``` ## Referenced By - `DurableService` (DEPENDS_ON) - `NonDurableService` (DEPENDS_ON) # UpperCase **Kind:** Decorator **Source:** [`sample/12-graphql-schema-first/src/common/directives/upper-case.directive.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/common/directives/upper-case.directive.ts#L1) # addRecipe **Kind:** Graphql Mutation **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` - TYPE_OF β†’ `NewRecipeInput` ## Referenced By - `Mutation` (CALLS_API) # Admin **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L502) ## Definition ```ts { connect(): Promise; disconnect(): Promise; listTopics(): Promise; createTopics(options: { validateOnly?: boolean; waitForLeaders?: boolean; timeout?: number; topics: ITopicConfig[]; }): Promise; deleteTopics(options: { topics: string[]; ti… ``` # 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) ## 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)[]` | # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L27) ## Endpoint `POST /` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `MqttController` (MODULE_DECLARES) # cat **Kind:** Graphql Query **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Query` (CALLS_API) # Cat **Kind:** Graphql Type **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) `Cat` is a GraphQL object type representing a cat in the application domain. It exposes identifying details (`id`), profile data (`name`, `age`), and an `owner` relationship that connects each cat to an `Owner` object. ## Diagram ```mermaid graph LR Cat["Cat"] Owner["Owner"] Cat -->|"id: Int"| Cat Cat -->|"name: String"| Cat Cat -->|"age: Int"| Cat Cat -->|"owner: Owner"| Owner ``` ## Usage ```graphql query GetCat($id: Int!) { cat(id: $id) { id name age owner { id name } } } ``` ```ts const result = await client.query({ query: GET_CAT, variables: { id: 1 }, }); console.log(result.data.cat.name); ``` ## AI Coding Instructions - Request only the `Cat` fields required by the UI or service to avoid unnecessary nested data. - Treat `owner` as a nested GraphQL object and select its fields explicitly in queries. - Keep `id` values aligned with the schema's `Int` type when passing query variables. - Update this type and related resolvers consistently when adding new cat attributes or relationships. ## Relationships - TYPE_OF β†’ `Owner` ## Referenced By - `cats` (TYPE_OF) - `cat` (TYPE_OF) - `createCat` (TYPE_OF) - `catCreated` (TYPE_OF) - `Owner` (TYPE_OF) # catCreated **Kind:** Graphql Subscription **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Subscription` (CALLS_API) # 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) `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. ## Referenced By - `ClassSerializerInterceptor` (DEPENDS_ON) # Common ### What it is responsible for Common manages shared framework contracts and input-oriented transformations for Nest applications. Its documented scope includes decorators such as `@Controller()` and `@Injectable()`, while named pipes turn supplied values into parsed or validated forms. `DefaultValuePipe`, `ParseFilePipe`, `ParseArrayPipe`, and `ParseBoolPipe` identify entry points for that work; `ValidationPipe` marks validation as part of the same surface. The subsystem also defines the middleware-application contract: `MiddlewareConsumer` applies user-defined middleware to routes, alongside `MiddlewareConfiguration`, `RouteInfo`, and `NestMiddleware`. The named `ConsoleLogger` and `Logger` place logging within this shared surface. ### What it needs, and who needs it Common needs no dependencies from this repository. The listed consumersβ€”`integration/injector/src/circular-modules`, `integration/injector/src/circular-properties`, `integration/inspector/src/circular-modules`, `integration/scopes/src/inject-inquirer`, and `Integration`β€”need Common’s contracts and pipe symbols. Without Common, those consumers cannot resolve the subsystem they depend on; references to its decorators, middleware types, logging symbols, serializers, or pipes would be unavailable. No repository dependency is named for Common. ### Notable members `DefaultValuePipe` is an identified entry point and, by its name, handles default values. `ParseArrayPipe` is another entry point and names array parsing directly. `MiddlewareConsumer` carries the explicitly documented responsibility: it defines a method for applying user-defined middleware to routes. 353 entities in `packages/common`. **5 other subsystems depend on it**, which makes it the 2nd 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` β€” `packages/common/pipes/default-value.pipe.ts`:1 - `ParseFilePipe` β€” `packages/common/pipes/file/parse-file.pipe.ts`:1 - `ParseArrayPipe` β€” `packages/common/pipes/parse-array.pipe.ts`:1 - `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 **5 other subsystems depend on this one** β€” `Circular Modules`, `Circular Properties`, `Circular Modules`, `Inject Inquirer`, `Integration`. Changing what it exposes changes them. Those 5 hold 11 edges between them, unevenly: `Inject Inquirer` reaches in across 3 edges, against 2 from `Integration`. What they reach is narrower than the folder: 2 of its 353 members carry every inbound edge β€” `forwardRef` (8) and `Logger` (3). **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` | # 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) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ ConsoleLogger client->>+p1: ConsoleLogger p1-->client: return response ``` # DatabaseController **Kind:** Controller **Source:** [`integration/inspector/src/database/database.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ DatabaseController participant p2 as βš™οΈ DatabaseService client->>+p1: DatabaseController p1->>+p2: DatabaseService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `update` - MODULE_DECLARES β†’ `remove` - DEPENDS_ON β†’ `DatabaseService` ## Referenced By - `DatabaseModule` (MODULE_DECLARES) # dynamicModule **Kind:** Constant **Source:** [`sample/18-context/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/18-context/src/app.module.ts#L5) ## Definition ```ts MyDynamicModule.register('foobar') ``` ## Value ```ts MyDynamicModule.register('foobar') ``` ## Referenced By - `AppModule` (MODULE_IMPORTS) # 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) ## 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` # 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) # Photo **Kind:** Database Model **Source:** [`integration/typeorm/src/photo/photo.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/photo/photo.entity.ts#L3) The `Photo` entity represents persisted photo metadata in the TypeORM integration. It stores descriptive content, the associated filename, publication state, and a view counter for each photo record. ## Fields | Field | Type | Required | Key | |---|---|---|---| | `id` | `int` | βœ“ | PK | | `name` | `varchar` | βœ“ | | | `description` | `text` | βœ“ | | | `filename` | `varchar` | βœ“ | | | `views` | `int` | βœ“ | | | `isPublished` | `boolean` | βœ“ | | ## Diagram ```mermaid erDiagram PHOTO { int id PK varchar name text description varchar filename int views boolean isPublished } ``` ## Usage ```ts import { AppDataSource } from '../data-source'; import { Photo } from './photo.entity'; const photoRepository = AppDataSource.getRepository(Photo); const photo = photoRepository.create({ name: 'Sunset at the lake', description: 'A sunset reflected over calm water.', filename: 'sunset-lake.jpg', views: 0, isPublished: false, }); await photoRepository.save(photo); const publishedPhotos = await photoRepository.find({ where: { isPublished: true }, }); ``` ## AI Coding Instructions - Use the TypeORM repository for `create`, `save`, `find`, and update operations rather than manually constructing database queries. - Treat `id` as the entity identifier; do not assign or modify it unless the schema explicitly requires manual IDs. - Initialize `views` to `0` when creating photos and increment it safely when recording page views. - Store only the file reference in `filename`; keep uploaded binary content in the configured storage system. - Filter by `isPublished: true` when serving photos to public-facing endpoints. # Reflector **Kind:** Class **Source:** [`packages/core/services/reflector.service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/services/reflector.service.ts#L44) Helper class providing Nest reflection capabilities. `Reflector` is a Nest core service for creating metadata decorators and retrieving metadata attached to classes or handlers. It provides typed helpers for reading metadata from one target, multiple targets, or merged target hierarchies, making it useful for guards, interceptors, and custom framework integrations. ## 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 A[Custom Decorator] --> B[Metadata on Class or Handler] C[Reflector] --> D[get] C --> E[getAll] C --> F[getAllAndMerge] B --> D B --> E B --> F D --> G[Single Metadata Value] E --> H[Metadata Values by Target] F --> I[Merged Metadata Result] ``` ## Usage ```ts import { Controller, Get, SetMetadata } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; // Create a metadata decorator with a stable metadata key. export const Roles = Reflector.createDecorator(); @Controller('reports') @Roles(['admin']) export class ReportsController { @Get() @Roles(['admin', 'analyst']) findAll() { return []; } } // Example guard or interceptor usage. function getRequiredRoles( reflector: Reflector, handler: Function, controller: Function, ): string[] { return reflector.getAllAndOverride(Roles, [handler, controller]) ?? []; } // Equivalent metadata lookup using a string key. const IS_PUBLIC_KEY = 'isPublic'; const Public = () => SetMetadata(IS_PUBLIC_KEY, true); function isPublicRoute( reflector: Reflector, handler: Function, controller: Function, ): boolean { return reflector.getAllAndOverride(IS_PUBLIC_KEY, [ handler, controller, ]) ?? false; } ``` ## AI Coding Instructions - Prefer `Reflector.createDecorator()` for new metadata decorators to preserve type safety and avoid manually managing metadata keys. - Use `getAllAndOverride()` when method-level metadata should take precedence over controller-level metadata. - Use `getAllAndMerge()` when metadata from handlers and parent classes should be combined, such as role lists or configuration objects. - Pass targets in precedence order, typically `[context.getHandler(), context.getClass()]` inside guards and interceptors. - Handle missing metadata with defaults (`?? []`, `?? false`) rather than assuming every route has decorator metadata. ## Referenced By - `RolesGuard` (DEPENDS_ON) - `RolesGuard` (DEPENDS_ON) - `RolesGuard` (DEPENDS_ON) - `AuthGuard` (DEPENDS_ON) - `RolesGuard` (DEPENDS_ON) # UpperCase **Kind:** Decorator **Source:** [`sample/23-graphql-code-first/src/common/directives/upper-case.directive.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/common/directives/upper-case.directive.ts#L1) # ValidationPipe **Kind:** Pipe **Source:** [`packages/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/validation.pipe.ts#L1) # addRecipe **Kind:** Graphql Mutation **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` - TYPE_OF β†’ `NewRecipeInput` ## Referenced By - `Mutation` (CALLS_API) # AuthModule **Kind:** Module **Source:** [`sample/19-auth-jwt/src/auth/auth.module.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/auth.module.ts#L10) ## Relationships - MODULE_IMPORTS β†’ `usersmodule` - MODULE_DECLARES β†’ `AuthController` - MODULE_PROVIDES β†’ `AuthService` - MODULE_EXPORTS β†’ `AuthService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L33) ## Endpoint `POST /` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `NatsController` (MODULE_DECLARES) # Cat **Kind:** Graphql Type **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) `Cat` is a GraphQL object type representing a cat entity in the schema-first GraphQL integration. It exposes a cat's unique identifier, name, and age for use in queries and resolver responses. ## Diagram ```mermaid graph LR Query[GraphQL Query] --> Cat[Cat Object Type] Cat --> ID[id: Int] Cat --> Name[name: String] Cat --> Age[age: Int] ``` ## Usage ```ts const query = ` query GetCat($id: Int!) { cat(id: $id) { id name age } } `; const result = await graphqlClient.request(query, { id: 1 }); console.log(`${result.cat.name} is ${result.cat.age} years old.`); ``` ## AI Coding Instructions - Keep the `Cat` schema definition synchronized with the corresponding resolver return shape. - Request only the fields needed by the client; GraphQL responses include only selected fields. - Preserve the existing scalar types: `id` and `age` are `Int`, while `name` is `String`. - Add new `Cat` fields to the `.graphql` schema first, then update resolvers and generated client types as needed. ## Referenced By - `getCats` (TYPE_OF) - `cat` (TYPE_OF) - `createCat` (TYPE_OF) - `catCreated` (TYPE_OF) # cats **Kind:** Graphql Query **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Query` (CALLS_API) # 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) `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` # Consumer **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1043) ## Definition ```ts { connect(): Promise; disconnect(): Promise; subscribe(subscription: ConsumerSubscribeTopics): Promise; stop(): Promise; run(config?: ConsumerRunConfig): Promise; commitOffsets( topicPartitions: Array, ): Promise;… ``` # DogsController **Kind:** Controller **Source:** [`integration/inspector/src/dogs/dogs.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ DogsController participant p2 as βš™οΈ DogsService client->>+p1: DogsController p1->>+p2: DogsService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `update` - MODULE_DECLARES β†’ `remove` - DEPENDS_ON β†’ `DogsService` ## Referenced By - `DogsModule` (MODULE_DECLARES) # 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) ## 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… ``` # IORedisOptions **Kind:** Interface **Source:** [`packages/microservices/external/redis.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/redis.interface.ts#L8) `IORedisOptions` defines connection and behavior settings for an ioredis-compatible Redis client used by the microservices layer. It centralizes authentication, database selection, socket behavior, client identification, and retry/timeout configuration passed to Redis integrations. ## 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 --> Auth[username / password] Options --> Connection[Connector / connectionName] Options --> Socket[keepAlive / noDelay] Options --> Reliability[retryStrategy / commandTimeout] Options --> Redis[Redis Server] Auth --> Redis Connection --> Redis Socket --> Redis Reliability --> Redis ``` ## Usage ```ts import type { IORedisOptions } from './redis.interface'; const redisOptions: IORedisOptions = { Connector: undefined, username: 'default', password: process.env.REDIS_PASSWORD ?? '', db: 0, connectionName: 'orders-service', clientInfoTag: 'orders-worker', keepAlive: 30_000, noDelay: true, commandTimeout: 5_000, retryStrategy: (times) => { if (times > 10) { return null; // Stop reconnecting after 10 attempts. } return Math.min(times * 200, 2_000); }, }; // Pass redisOptions to the Redis/ioredis client factory used by the service. ``` ## AI Coding Instructions - Provide `username`, `password`, and `db` from environment-specific configuration; do not hardcode production credentials. - Use `retryStrategy` to return a delay in milliseconds, or return `null`/`void` when reconnection attempts should stop. - Set a meaningful `connectionName` and `clientInfoTag` so Redis connections can be identified during debugging and monitoring. - Keep `commandTimeout` aligned with service-level timeout and retry policies to avoid requests waiting indefinitely. - Use `noDelay: true` for latency-sensitive workloads, and configure `keepAlive` to prevent idle network connections from being dropped. # 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) `LazyModuleLoader` loads NestJS modules on demand instead of during application bootstrap. It integrates with the Nest dependency injection container and returns a `ModuleRef` that can be used to resolve providers from the newly loaded module. ## Methods | Method | Signature | Returns | |---|---|---| | `load` | `load(loaderFn: () => | Promise | DynamicModule> | Type | DynamicModule, loadOpts: LazyModuleLoaderLoadOptions)` | `Promise` | ## Diagram ```mermaid graph LR A[Service or Controller] --> B[LazyModuleLoader] B --> C[Dynamic import / Module factory] C --> D[Nest Injector] D --> E[Loaded Module] E --> F[ModuleRef] F --> G[Resolve module providers] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { LazyModuleLoader, ModuleRef } from '@nestjs/core'; @Injectable() export class ReportsService { constructor(private readonly lazyModuleLoader: LazyModuleLoader) {} async generateReport() { const moduleRef: ModuleRef = await this.lazyModuleLoader.load(() => import('./reports.module').then(({ ReportsModule }) => ReportsModule), ); const reportsClient = moduleRef.get(ReportsClient, { strict: false }); return reportsClient.generate(); } } ``` ## AI Coding Instructions - Inject `LazyModuleLoader` through Nest's dependency injection system; do not instantiate it manually. - Pass a loader callback to `load()` so the module is imported only when it is needed. - Use the returned `ModuleRef` to retrieve providers exposed by the lazy-loaded module. - Handle import and module initialization failures around `load()` when loading optional or external features. - Prefer lazy loading for infrequently used, expensive, or feature-specific modules rather than core application dependencies. ## Referenced By - `LazyController` (DEPENDS_ON) # Microservices ### What it is responsible for Microservices manages the package-level entry surface for microservice-related work: `normalizedPattern`, `route`, and `ClientsModule` are identified as paths through which work enters. Its documented project context calls Nest a framework for building Node.js server-side applications. The subsystem also draws boundaries around client, consumer, and producer initialization and around a topic check. With no repository-local dependencies listed, its documented responsibility is bounded by these entries and rejection paths. ### What it refuses The subsystem rejects these conditions: - `InvalidGrpcServiceException` when `!clientRef`. - `No consumer initialized. Please, call the "connect" method first.` when `!this._consumer`. - `No producer initialized. Please, call the "connect" method first.` when `!this._producer`. - `Not initialized. Please call the "connect" method first.` when `!this.client`. - `InvalidKafkaClientTopicException` when `isUndefined(minimumPartition)`. - `Not initialized. Please call the "connect" method first.` when `!this.mqttClient`. ### What it needs, and who needs it Microservices has no dependencies listed within this repository. It is depended on by `Integration`, `integration/microservices/src/tcp-tls`, `sample/03-microservices/src/math`, and `sample/04-grpc/src/hero`. Without this subsystem, those named dependents lose their stated dependency on `packages/microservices`; the evidence does not identify a more specific failure. That limitation matters: the dependency listing establishes direction from those consumers toward this package but it does not explicitly state which calls, initialization sequence, or runtime result each consumer requires. ### Notable members `ClientsModule` is a named entry point for work and a listed member. `normalizedPattern` is also a named entry point, marking a boundary at which work arrives. `route` completes the listed entry trio; the evidence names it as an entry point but does not state its transformation or dispatch behavior. No further behavior for these symbols is stated in the supplied evidence for this subsystem. 435 entities in `packages/microservices`. **4 other subsystems depend on it**, which makes it the 3rd most depended-upon part of this codebase. ## What it is made of Its 435 entities sit in 120 files under `packages/microservices`: 99 interfaces, 98 type aliases, 97 classes, 53 constants and 88 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` β€” `packages/microservices/server/server.ts`:150 - `route` β€” `packages/microservices/server/server.ts`:168 - `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 30 places. Of those 30, 13 turn it into a return value, 11 log it and continue, 5 let it reach the caller and 1 discards it without recording anything. ## Boundaries **4 other subsystems depend on this one** β€” `Integration`, `Tcp Tls`, `Math`, `Hero`. Changing what it exposes changes them. Those 4 hold 8 edges between them, unevenly: `Integration` reaches in across 3 edges, while 2 of them hold one each. What they reach is narrower than the folder: 2 of its 435 members carry every inbound edge β€” `ClientProxy` (7) and `ClientGrpc` (1). **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 | 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` | # 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) # Post **Kind:** Database Model **Source:** [`sample/22-graphql-prisma/prisma/schema.prisma`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/prisma/schema.prisma#L13) `Post` is a Prisma database model representing a publishable content entry. It stores a unique identifier, title, body text, and publication status for use by the GraphQL/API layer and application queries. ## Fields | Field | Type | Required | Key | |---|---|---|---| | `id` | `String` | βœ“ | PK | | `title` | `String` | βœ“ | | | `text` | `String` | βœ“ | | | `isPublished` | `Boolean` | βœ“ | | ## Diagram ```mermaid erDiagram POST { String id PK String title String text Boolean isPublished } ``` ## Usage ```ts import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() async function createPublishedPost() { const post = await prisma.post.create({ data: { id: crypto.randomUUID(), title: 'Getting Started with Prisma', text: 'Prisma provides a type-safe database client for TypeScript.', isPublished: true, }, }) return post } async function getPublishedPosts() { return prisma.post.findMany({ where: { isPublished: true }, orderBy: { title: 'asc' }, }) } ``` ## AI Coding Instructions - Use the generated Prisma client (`prisma.post`) for all `Post` reads and writes rather than querying the database directly. - Filter public-facing post queries with `where: { isPublished: true }` to avoid exposing drafts. - Provide a unique string value for `id` when creating records unless the Prisma schema is updated to define a default ID generator. - Validate that `title` and `text` are non-empty before persisting a post through GraphQL mutations or API handlers. - Keep publication changes explicit by updating `isPublished` through a dedicated update or publish workflow. # postCreated **Kind:** Graphql Subscription **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - TYPE_OF β†’ `Post` ## Referenced By - `Subscription` (CALLS_API) # 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) ## Values - `GET` - `POST` - `PUT` - `DELETE` - `PATCH` - `ALL` - `OPTIONS` - `HEAD` - `SEARCH` - `PROPFIND` - `PROPPATCH` - `MKCOL` - `COPY` - `MOVE` - `LOCK` - `UNLOCK` # 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) 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. # AclOperationTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L319) ## Values - `UNKNOWN` - `ANY` - `ALL` - `READ` - `WRITE` - `CREATE` - `DELETE` - `ALTER` - `DESCRIBE` - `CLUSTER_ACTION` - `DESCRIBE_CONFIGS` - `ALTER_CONFIGS` - `IDEMPOTENT_WRITE` # callWithClientUseClass **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L47) ## Endpoint `POST /useClass` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # CModule **Kind:** Module **Source:** [`integration/injector/src/multiple-providers/c.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/multiple-providers/c.module.ts#L3) ## Referenced By - `MultipleProvidersModule` (MODULE_IMPORTS) # createCat **Kind:** Graphql Mutation **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Mutation` (CALLS_API) # Date **Kind:** Type **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) Date custom scalar type `Date` is a custom GraphQL scalar used to represent date values in the code-first GraphQL schema. It provides a dedicated schema type for fields and arguments that accept or return dates, ensuring clients use a consistent date representation. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|Date value| Schema[GraphQL Schema] Schema --> DateScalar[Date Custom Scalar] DateScalar --> Resolver[Resolver / Application Logic] Resolver -->|Date value| DateScalar DateScalar --> Client ``` ## Usage ```ts import { Field, ObjectType } from '@nestjs/graphql'; @ObjectType() export class Event { @Field(() => Date) startsAt!: Date; } // GraphQL query result: // { // "data": { // "event": { // "startsAt": "2025-03-08T10:00:00.000Z" // } // } // } ``` ## AI Coding Instructions - Use the `Date` scalar for GraphQL fields, arguments, and inputs that represent date/time values rather than plain `String`. - Ensure resolver values are valid JavaScript `Date` instances or match the scalar's expected serialized format. - Keep client-side date values in a consistent ISO-8601 format when sending GraphQL variables. - Do not use this scalar for duration, timezone-only, or arbitrary timestamp-string fields unless its serialization rules explicitly support them. ## Referenced By - `Recipe` (TYPE_OF) # DiscoveryModule **Kind:** Class **Source:** [`packages/core/discovery/discovery-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-module.ts#L8) ## Referenced By - `AppModule` (MODULE_IMPORTS) # Dogs ### What it is responsible for The Dogs subsystem manages dog API work through `DogsController` and its entry points: `create`, `findAll`, `findOne`, `update`, and `remove`. The named `DogsService` participates in the subsystem, alongside `Dog`, `CreateDogDto`, and `UpdateDogDto`. `DogsModule` identifies its module boundary. The available evidence does not specify behavior beyond these named operations and types. `Dog`, `CreateDogDto`, and `UpdateDogDto` are named classes associated with the subsystem, while the evidence names no further responsibilities for these classes themselves. ### What it needs, and who needs it Dogs has no recorded dependencies within this repository. `Integration` depends on Dogs, making it the recorded consumer of this subsystem. Without Dogs, that dependency cannot be satisfied, so [Integration](subsystem-integration) would lose its recorded Dogs relationship. This evidence does not identify any additional internal or external dependency requirements. 11 entities in `integration/inspector/src/dogs`. **1 other subsystem depends on it**, which makes it the 4th most depended-upon part of this codebase. ## What it is made of Its 11 entities sit in 6 files under `integration/inspector/src/dogs`: 5 HTTP endpoints, 3 classes, 1 controller, 1 module and 1 more. `dogs.controller.ts` holds 6 of them β€” more than any other file here. `DogsService` declares 5 methods, the widest surface here. ## Where work enters 1 controller publishes 5 HTTP endpoints β€” 2 `GET`, 1 `POST`, 1 `PATCH` and 1 `DELETE`. They answer under `/dogs`. None of them declares a guard. - `DogsController` β€” `integration/inspector/src/dogs/dogs.controller.ts`:14 - `create` β€” `integration/inspector/src/dogs/dogs.controller.ts`:18 - `findAll` β€” `integration/inspector/src/dogs/dogs.controller.ts`:23 - `findOne` β€” `integration/inspector/src/dogs/dogs.controller.ts`:28 - `update` β€” `integration/inspector/src/dogs/dogs.controller.ts`:33 - `remove` β€” `integration/inspector/src/dogs/dogs.controller.ts`:38 ## Boundaries **1 other subsystem depends on this one** β€” `Integration`. Changing what it exposes changes them. They hold 1 edge into it between them. What they reach is narrower than the folder: 1 of its 11 members carries every inbound edge β€” `DogsModule` (1). **It depends on no other subsystem in this repository** β€” it is a leaf. # ExternalSvcController **Kind:** Controller **Source:** [`integration/inspector/src/external-svc/external-svc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/external-svc/external-svc.controller.ts#L7) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ ExternalSvcController participant p2 as βš™οΈ ExternalSvcService client->>+p1: ExternalSvcController p1->>+p2: ExternalSvcService p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `ExternalSvcService` ## Referenced By - `ExternalSvcModule` (MODULE_DECLARES) # getCats **Kind:** Graphql Query **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Query` (CALLS_API) # GlobalService **Kind:** Service **Source:** [`integration/lazy-modules/src/global.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/global.module.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ GlobalService client->>+p1: GlobalService p1-->client: return response ``` ## Referenced By - `EagerService` (DEPENDS_ON) - `GlobalModule` (MODULE_PROVIDES) - `GlobalModule` (MODULE_EXPORTS) - `LazyService` (DEPENDS_ON) - `RequestLazyModule` (MODULE_PROVIDES) - `TransientLazyModule` (MODULE_PROVIDES) # 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) 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. # 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) # Recipe **Kind:** Graphql Type **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) `Recipe` is a GraphQL object type representing a recipe record exposed by the code-first schema. It provides required identity, title, creation date, and ingredient data, with an optional textual description for additional recipe details. Clients can query this type wherever the API returns recipe-related data. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Query[Recipe Query or Resolver] Query --> Recipe[Recipe Object] Recipe --> ID[id: ID!] Recipe --> Title[title: String!] Recipe --> Description[description: String] Recipe --> CreationDate[creationDate: Date!] Recipe --> Ingredients[ingredients: String[]!] ``` ## Usage ```ts import { gql } from '@apollo/client'; const GET_RECIPE = gql` query GetRecipe($id: ID!) { recipe(id: $id) { id title description creationDate ingredients } } `; // Example response shape type Recipe = { id: string; title: string; description?: string | null; creationDate: string; ingredients: string[]; }; ``` ## AI Coding Instructions - Treat `id`, `title`, `creationDate`, and `ingredients` as required fields; only `description` may be `null`. - Request only the fields needed by the UI or consuming service to keep GraphQL queries focused. - Handle `creationDate` according to the API's `Date` scalar serialization format, typically as an ISO-8601 string in clients. - Preserve ingredient ordering when displaying or transforming the `ingredients` array. - Update GraphQL queries and generated client types together when the `Recipe` schema changes. ## Relationships - TYPE_OF β†’ `Date` ## Referenced By - `recipe` (TYPE_OF) - `recipes` (TYPE_OF) - `addRecipe` (TYPE_OF) - `recipeAdded` (TYPE_OF) # recipeAdded **Kind:** Graphql Subscription **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Subscription` (CALLS_API) # 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) ## 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… ``` # UNKNOWN_DEPENDENCIES_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L63) ## 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` | # User **Kind:** Database Model **Source:** [`sample/05-sql-typeorm/src/users/user.entity.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/user.entity.ts#L3) `User` is a TypeORM database entity that represents an application user record. It stores identity fields (`firstName`, `lastName`), an active-status flag, and an integer primary identifier used to query and manage users throughout the system. ## Fields | Field | Type | Required | Key | |---|---|---|---| | `id` | `int` | βœ“ | PK | | `firstName` | `varchar` | βœ“ | | | `lastName` | `varchar` | βœ“ | | | `isActive` | `boolean` | βœ“ | | ## Diagram ```mermaid erDiagram USER { int id PK varchar firstName varchar lastName boolean isActive } ``` ## Usage ```ts import { AppDataSource } from '../data-source'; import { User } from './users/user.entity'; const userRepository = AppDataSource.getRepository(User); const user = userRepository.create({ firstName: 'Ada', lastName: 'Lovelace', isActive: true, }); await userRepository.save(user); const activeUsers = await userRepository.find({ where: { isActive: true }, }); ``` ## AI Coding Instructions - Use the TypeORM repository obtained through `AppDataSource.getRepository(User)` for persistence and queries. - Create new records with `repository.create()` and persist them with `repository.save()`. - Treat `id` as the entity's primary identifier; do not manually assign it unless the entity configuration explicitly requires it. - Filter inactive users with `where: { isActive: true }` when implementing active-user-only behavior. - Keep database column names and TypeScript property names aligned with the entity decorators in `user.entity.ts`. # AbstractHttpAdapter **Kind:** Class **Source:** [`packages/core/adapters/http-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/adapters/http-adapter.ts#L8) `AbstractHttpAdapter` is the base abstraction that lets the core framework interact with different HTTP server implementations through a consistent API. It delegates common routing and middleware operations such as `use()`, `get()`, `post()`, and `head()` to the underlying HTTP platform instance. Concrete adapters implement platform-specific response handling, server lifecycle, and integration behavior. **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 Core[Nest Core] --> Adapter[AbstractHttpAdapter] Adapter --> Middleware[use()] Adapter --> Routes[get() / post() / head()] Adapter --> Instance[Underlying HTTP Server Instance] Instance --> Server[Express, Fastify, or Custom Server] ``` ## Usage ```ts import { ExpressAdapter } from '@nestjs/platform-express'; const adapter = new ExpressAdapter(); // Register middleware on the underlying HTTP server. adapter.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); // Register routes through the adapter's delegated methods. adapter.get('/health', (_req, res) => { res.status(200).json({ status: 'ok' }); }); adapter.post('/messages', (req, res) => { res.status(201).json({ received: req.body }); }); await adapter.listen(3000); console.log('HTTP server listening on http://localhost:3000'); ``` ## AI Coding Instructions - Treat `AbstractHttpAdapter` as a platform boundary: keep shared framework behavior adapter-agnostic and place server-specific logic in concrete adapters. - Use `use()`, `get()`, `post()`, and `head()` to delegate directly to the configured HTTP server instance rather than duplicating routing behavior. - Do not instantiate `AbstractHttpAdapter` directly; use or implement a concrete adapter such as `ExpressAdapter` or a custom platform adapter. - Ensure the underlying server instance is configured before registering middleware or routes, since these methods forward calls to that instance. - Preserve the underlying platform's handler signatures and routing semantics when adding or modifying adapter integrations. # callWithClientUseClass **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L60) ## Endpoint `POST /useClass` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # createCat **Kind:** Graphql Mutation **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - TYPE_OF β†’ `Cat` - TYPE_OF β†’ `CreateCatInput` ## Referenced By - `Mutation` (CALLS_API) # 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) ## 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` | # Date **Kind:** Type **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) Date custom scalar type `Date` is a custom GraphQL scalar type used to represent date values in the schema. It provides a typed contract for fields and arguments that accept or return dates, allowing the API layer to serialize and validate date values consistently. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|Date input/output| Schema[GraphQL Schema] Schema --> DateScalar[Date Custom Scalar] DateScalar --> Resolver[Resolver Logic] Resolver --> Application[Application Data] ``` ## Usage ```ts import { GraphQLScalarType, Kind } from 'graphql'; export const DateScalar = new GraphQLScalarType({ name: 'Date', description: 'Custom scalar for ISO-8601 date values.', serialize(value: Date): string { return value.toISOString(); }, parseValue(value: string): Date { return new Date(value); }, parseLiteral(ast): Date | null { if (ast.kind !== Kind.STRING) { return null; } return new Date(ast.value); }, }); ``` ```graphql type Event { id: ID! startsAt: Date! } type Query { event(id: ID!): Event } ``` ## AI Coding Instructions - Use `Date` for GraphQL fields and arguments that represent date values rather than plain `String`. - Serialize date outputs to a stable ISO-8601 string format, such as `Date.prototype.toISOString()`. - Validate incoming values in both `parseValue` and `parseLiteral`; reject invalid date strings instead of silently accepting them. - Keep scalar behavior consistent with resolver and database date handling, especially regarding UTC and timezone conversion. - Register the custom scalar with the GraphQL schema before using `Date` in object types, queries, or mutations. ## Referenced By - `Recipe` (TYPE_OF) # DogsModule **Kind:** Module **Source:** [`integration/inspector/src/dogs/dogs.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `DogsController` - MODULE_PROVIDES β†’ `DogsService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # EagerService **Kind:** Service **Source:** [`integration/lazy-modules/src/eager.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/eager.module.ts#L4) `EagerService` is a NestJS service defined in the eager module of the lazy-modules integration area. It provides a `sayHello()` method that can be injected into controllers or other providers to verify that the eager-loaded module is available during application startup. ## Methods | Method | Signature | Returns | |---|---|---| | `sayHello` | `sayHello()` | `unknown` | ## Dependencies - `GlobalService` ## Diagram ```mermaid sequenceDiagram participant App as Nest Application participant Module as EagerModule participant Service as EagerService participant Consumer as Controller/Provider App->>Module: Initialize eager module Module->>Service: Create provider instance Consumer->>Service: Inject EagerService Consumer->>Service: sayHello() Service-->>Consumer: Return greeting result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { EagerService } from './eager.module'; @Injectable() export class GreetingConsumer { constructor(private readonly eagerService: EagerService) {} greet() { return this.eagerService.sayHello(); } } ``` ## AI Coding Instructions - Inject `EagerService` through NestJS constructor injection rather than creating it with `new`. - Ensure the module that provides `EagerService` is imported by the consuming NestJS module. - Keep `sayHello()` lightweight, since eager providers may be instantiated during application startup. - Preserve the service's provider/export configuration when refactoring module boundaries or lazy-module integration tests. ## Relationships - DEPENDS_ON β†’ `GlobalService` ## Referenced By - `EagerModule` (MODULE_PROVIDES) - `RequestLazyModule` (MODULE_PROVIDES) - `RequestService` (DEPENDS_ON) - `TransientLazyModule` (MODULE_PROVIDES) - `TransientService` (DEPENDS_ON) # ENHANCER_TOKEN_TO_SUBTYPE_MAP **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L17) ## 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 ``` # HeroController **Kind:** Controller **Source:** [`sample/04-grpc/src/hero/hero.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/hero/hero.controller.ts#L17) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HeroController participant p2 as πŸ“¦ ClientGrpc client->>+p1: HeroController p1->>+p2: ClientGrpc p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getMany` - MODULE_DECLARES β†’ `getById` - DEPENDS_ON β†’ `ClientGrpc` ## Referenced By - `HeroModule` (MODULE_DECLARES) # Host ### What it is responsible for Host manages the entry points represented by `HostController` and `HostModule`, including `greeting`, `asyncGreeting`, `streamGreeting`, and `localPipe`. It also owns named services and classes including `HostService`, `UsersService`, `UserByIdPipe`, and `TestDto`. The evidence does not identify endpoint-to-service links, configuration, inputs, outputs, or execution order explicitly here. ### What it needs, and who needs it Host needs no dependencies from elsewhere in this repository. `Integration` needs Host: it is listed as depending on this subsystem. Without Host, [Integration](subsystem-integration) would lack that declared dependency, and `HostController`, `HostModule`, and `HostService` would not be available from it. 10 entities in `integration/hello-world/src/host`. **1 other subsystem depends on it**, which makes it the 5th most depended-upon part of this codebase. ## What it is made of Its 10 entities sit in 6 files under `integration/hello-world/src/host`: 4 HTTP endpoints, 3 services, 1 controller, 1 module and 1 more. `host.controller.ts` holds 5 of them β€” more than any other file here. ## Where work enters 1 controller publishes 4 `GET` endpoints. None of them declares a guard. - `HostController` β€” `integration/hello-world/src/host/host.controller.ts`:6 - `greeting` β€” `integration/hello-world/src/host/host.controller.ts`:13 - `asyncGreeting` β€” `integration/hello-world/src/host/host.controller.ts`:19 - `streamGreeting` β€” `integration/hello-world/src/host/host.controller.ts`:24 - `localPipe` β€” `integration/hello-world/src/host/host.controller.ts`:29 - `HostModule` β€” `integration/hello-world/src/host/host.module.ts`:6 ## Boundaries **1 other subsystem depends on this one** β€” `Integration`. Changing what it exposes changes them. They hold 1 edge into it between them. What they reach is narrower than the folder: 1 of its 10 members carries every inbound edge β€” `HostModule` (1). **It depends on no other subsystem in this repository** β€” it is a leaf. # 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) 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. # 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) # post **Kind:** Graphql Query **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - TYPE_OF β†’ `Post` ## Referenced By - `Query` (CALLS_API) # Recipe **Kind:** Graphql Type **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) recipe `Recipe` represents a recipe record in the GraphQL schema. It provides the recipe's unique identifier, title, optional description, creation date, and required list of ingredients for use in queries and API responses. ## Diagram ```mermaid graph LR Recipe["Recipe"] Recipe --> ID["id: ID!"] Recipe --> Title["title: String!"] Recipe --> Description["description: String"] Recipe --> CreationDate["creationDate: Date!"] Recipe --> Ingredients["ingredients: [String!]!"] ``` ## Usage ```ts import { gql } from "@apollo/client"; export const GET_RECIPE = gql` query GetRecipe($id: ID!) { recipe(id: $id) { id title description creationDate ingredients } } `; // Example response shape: // { // id: "recipe-123", // title: "Vegetable Pasta", // description: "A quick weeknight pasta recipe.", // creationDate: "2024-01-15T10:30:00.000Z", // ingredients: ["pasta", "tomatoes", "garlic"] // } ``` ## AI Coding Instructions - Always request `id`, `title`, `creationDate`, and `ingredients` when the client needs a complete recipe; these fields are non-null. - Handle `description` as optional because it may be `null` in GraphQL responses. - Treat `ingredients` as a required array of non-null strings; do not add null checks for individual ingredient values. - Serialize and parse `creationDate` using the schema's `Date` scalar conventions. - Keep GraphQL fragments for `Recipe` aligned with the schema fields and nullability constraints. ## Relationships - TYPE_OF β†’ `Date` ## Referenced By - `recipe` (TYPE_OF) - `recipes` (TYPE_OF) - `addRecipe` (TYPE_OF) - `recipeAdded` (TYPE_OF) # recipeAdded **Kind:** Graphql Subscription **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Subscription` (CALLS_API) # 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) ## Values - `REQUEST` - `RESPONSE` - `NEXT` - `BODY` - `QUERY` - `PARAM` - `HEADERS` - `SESSION` - `FILE` - `FILES` - `HOST` - `IP` - `RAW_BODY` - `ACK` # User **Kind:** Database Model **Source:** [`sample/07-sequelize/src/users/models/user.model.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/models/user.model.ts#L3) `User` is a Sequelize database model representing application users. It stores each user’s first name, last name, and active status, and provides the persistence layer for creating, querying, and updating user records. ## Fields | Field | Type | Required | Key | |---|---|---|---| | `firstName` | `varchar` | - | | | `lastName` | `varchar` | - | | | `isActive` | `boolean` | - | | ## Diagram ```mermaid erDiagram USER { varchar firstName varchar lastName boolean isActive } ``` ## Usage ```ts import { User } from './users/models/user.model'; // Create an active user const user = await User.create({ firstName: 'Ada', lastName: 'Lovelace', isActive: true, }); // Query active users const activeUsers = await User.findAll({ where: { isActive: true }, }); console.log(user.firstName); console.log(activeUsers); ``` ## AI Coding Instructions - Use Sequelize model methods such as `create`, `findAll`, `findOne`, and `update` instead of writing raw SQL for standard user operations. - Provide all expected user fields when creating records: `firstName`, `lastName`, and `isActive`. - Filter by `isActive: true` when retrieving users intended for active application workflows. - Keep database-specific logic in this model or related repository/service layers rather than spreading Sequelize queries across controllers. # AuthService **Kind:** Service **Source:** [`sample/19-auth-jwt/src/auth/auth.service.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/auth.service.ts#L5) `AuthService` encapsulates authentication-related business logic for the NestJS application. Its `signIn()` method is responsible for validating sign-in input and producing the authentication result, typically including a JWT access token consumed by protected backend endpoints. ## Methods | Method | Signature | Returns | |---|---|---| | `signIn` | `signIn(username: string, pass: string)` | `unknown` | ## Dependencies - `UsersService` - `JwtService` ## Where it refuses work - `AuthService` stops the work with `UnauthorizedException` when `user?.password !== pass`. ## Diagram ```mermaid sequenceDiagram participant Client participant AuthController participant AuthService participant JwtService Client->>AuthController: POST /auth/signin AuthController->>AuthService: signIn() AuthService->>JwtService: sign(payload) JwtService-->>AuthService: access token AuthService-->>AuthController: authentication result AuthController-->>Client: token response ``` ## Usage ```ts import { AuthService } from './auth.service'; async function authenticate(authService: AuthService) { const result = await authService.signIn(); console.log('Authentication result:', result); return result; } // In NestJS, AuthService is normally injected into a controller: constructor(private readonly authService: AuthService) {} async signIn() { return this.authService.signIn(); } ``` ## AI Coding Instructions - Keep authentication business logic in `AuthService`; controllers should only handle request parsing and HTTP responses. - Preserve NestJS dependency injection patterns when adding dependencies such as `JwtService`, user repositories, or password hash utilities. - Ensure `signIn()` does not expose sensitive fields, including password hashes, in its returned result. - Validate credentials before generating JWTs, and use configuration-driven secrets and expiration settings. - Update auth guards, strategies, and controller response contracts when changing the token payload or sign-in result shape. ## Relationships - DEPENDS_ON β†’ `usersservice` - DEPENDS_ON β†’ `jwtservice` ## Referenced By - `AuthController` (DEPENDS_ON) - `AuthModule` (MODULE_PROVIDES) - `AuthModule` (MODULE_EXPORTS) # callWithClientUseFactory **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L38) ## Endpoint `POST /useFactory` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # ClientGrpcProxy **Kind:** Class **Source:** [`packages/microservices/client/client-grpc.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-grpc.ts#L31) `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()`. # createPost **Kind:** Graphql Mutation **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - TYPE_OF β†’ `Post` - TYPE_OF β†’ `NewPost` ## Referenced By - `Mutation` (CALLS_API) # Date **Kind:** Type **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) Date custom scalar type `Date` is a custom GraphQL scalar that represents date values in the Mercurius schema. It provides a dedicated type for fields that need date serialization and parsing instead of using plain strings. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|Query variables / literals| DateScalar[Date Scalar] DateScalar -->|parseValue / parseLiteral| Resolver[Resolver] Resolver -->|Date value| DateScalar DateScalar -->|serialize| Client ``` ## Usage ```ts import { GraphQLScalarType, Kind } from 'graphql' const DateScalar = new GraphQLScalarType({ name: 'Date', description: 'Custom scalar for date values', serialize(value) { const date = new Date(value as string | number | Date) if (Number.isNaN(date.getTime())) { throw new TypeError('Date cannot represent an invalid date value') } return date.toISOString() }, parseValue(value) { const date = new Date(value as string) if (Number.isNaN(date.getTime())) { throw new TypeError('Date cannot represent an invalid date value') } return date }, parseLiteral(ast) { if (ast.kind !== Kind.STRING) { throw new TypeError('Date must be provided as a string literal') } return new Date(ast.value) } }) // schema.gql // scalar Date // type Event { startsAt: Date! } const resolvers = { Date: DateScalar, Query: { event: () => ({ startsAt: new Date('2024-01-01T10:00:00.000Z') }) } } ``` ## AI Coding Instructions - Register the `Date` scalar implementation in Mercurius resolvers using the same scalar name declared in `schema.gql`. - Validate all incoming values in both `parseValue` and `parseLiteral`; reject invalid dates rather than silently accepting them. - Return a consistent serialized format, preferably ISO 8601 strings via `toISOString()`. - Handle GraphQL variable input and inline literals separately, since variables use `parseValue` and query literals use `parseLiteral`. - Keep resolver return values compatible with the scalar serializer, such as JavaScript `Date` instances or valid ISO date strings. ## Referenced By - `Recipe` (TYPE_OF) # 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) 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. # ExternalSvcModule **Kind:** Module **Source:** [`integration/inspector/src/external-svc/external-svc.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/external-svc/external-svc.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `ExternalSvcController` - MODULE_PROVIDES β†’ `ExternalSvcService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # 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) External interface `GatewayMetadata` defines configuration options for a WebSocket gateway, including its namespace, connection path, transport behavior, and timeout settings. It is used by the gateway layer to configure the underlying Socket.IO server when a gateway is initialized. These options control how clients connect, exchange data, and are managed over time. ## 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 Gateway["WebSocket Gateway"] Metadata["GatewayMetadata"] SocketServer["Socket.IO Server"] Clients["WebSocket Clients"] Gateway -->|uses| Metadata Metadata -->|configures namespace, path, timeouts, parser, adapter| SocketServer Clients -->|connect through path / namespace| SocketServer ``` ## Usage ```ts import { WebSocketGateway } from '@nestjs/websockets'; import type { GatewayMetadata } from '@nestjs/websockets/interfaces/gateway-metadata.interface'; const gatewayOptions: GatewayMetadata = { namespace: '/notifications', path: '/socket.io', serveClient: false, adapter: undefined, parser: undefined, connectTimeout: 10_000, pingTimeout: 20_000, pingInterval: 25_000, upgradeTimeout: 10_000, maxHttpBufferSize: 1_000_000, }; @WebSocketGateway(gatewayOptions) export class NotificationsGateway { // Gateway event handlers } ``` ## AI Coding Instructions - Use `namespace` to isolate gateway traffic, such as `/chat` or `/notifications`, instead of mixing unrelated events on one endpoint. - Keep `path` consistent between the gateway configuration and all Socket.IO client connection settings. - Configure `pingTimeout` and `pingInterval` together; overly aggressive values can disconnect clients on unstable networks. - Set `maxHttpBufferSize` to a safe value when clients may send large payloads, and validate incoming message content separately. - Provide custom `adapter` or `parser` implementations only when the underlying Socket.IO integration requires them. # Host Array ### What it is responsible for Host Array manages the subsystem's named entry points, including `HostArrayController` and `HostArrayModule`. Its identified work enters through `greeting`, `asyncGreeting`, `streamGreeting`, and `localPipe`, alongside the controller and module. The subsystem also names `HostArrayService`, `UsersService`, `UserByIdPipe`, and `TestDto`. Available evidence does not describe the behavior, relationships, or responsibilities of those symbols beyond their membership in this area. Symbols are recorded as part of Host Array, but their interfaces and invocation details are not specified in the supplied evidence here. ### What it needs, and who needs it Host Array needs no dependencies in this repository, according to the supplied dependency record. `Integration` needs Host Array as a recorded dependent subsystem. Without Host Array, `Integration` loses that recorded dependency target; the evidence does not identify a more specific failure. 10 entities in `integration/hello-world/src/host-array`. **1 other subsystem depends on it**, which makes it the 6th most depended-upon part of this codebase. ## What it is made of Its 10 entities sit in 6 files under `integration/hello-world/src/host-array`: 4 HTTP endpoints, 3 services, 1 controller, 1 module and 1 more. `host-array.controller.ts` holds 5 of them β€” more than any other file here. ## Where work enters 1 controller publishes 4 `GET` endpoints. None of them declares a guard. - `HostArrayController` β€” `integration/hello-world/src/host-array/host-array.controller.ts`:6 - `greeting` β€” `integration/hello-world/src/host-array/host-array.controller.ts`:13 - `asyncGreeting` β€” `integration/hello-world/src/host-array/host-array.controller.ts`:19 - `streamGreeting` β€” `integration/hello-world/src/host-array/host-array.controller.ts`:24 - `localPipe` β€” `integration/hello-world/src/host-array/host-array.controller.ts`:29 - `HostArrayModule` β€” `integration/hello-world/src/host-array/host-array.module.ts`:6 ## Boundaries **1 other subsystem depends on this one** β€” `Integration`. Changing what it exposes changes them. They hold 1 edge into it between them. What they reach is narrower than the folder: 1 of its 10 members carries every inbound edge β€” `HostArrayModule` (1). **It depends on no other subsystem in this repository** β€” it is a leaf. # HostArrayController **Kind:** Controller **Source:** [`integration/hello-world/src/host-array/host-array.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HostArrayController participant p2 as βš™οΈ HostArrayService client->>+p1: HostArrayController p1->>+p2: HostArrayService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - MODULE_DECLARES β†’ `asyncGreeting` - MODULE_DECLARES β†’ `streamGreeting` - MODULE_DECLARES β†’ `localPipe` - DEPENDS_ON β†’ `HostArrayService` ## Referenced By - `HostArrayModule` (MODULE_DECLARES) # 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) ## 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… ``` # 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) # posts **Kind:** Graphql Query **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - TYPE_OF β†’ `Post` ## Referenced By - `Query` (CALLS_API) # Recipe **Kind:** Graphql Type **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) recipe `Recipe` is a GraphQL object type that represents a recipe returned by the API. It provides core recipe metadata, including its identifier, title, optional description, creation date, and a required list of ingredients. ## Diagram ```mermaid graph LR Query[GraphQL Query] --> Recipe Recipe --> ID[id: ID!] Recipe --> Title[title: String!] Recipe --> Description[description: String] Recipe --> CreationDate[creationDate: Date!] Recipe --> Ingredients[ingredients: String[]!] ``` ## Usage ```ts import { gql } from 'graphql-tag'; const GET_RECIPE = gql` query GetRecipe($id: ID!) { recipe(id: $id) { id title description creationDate ingredients } } `; const result = await client.query({ query: GET_RECIPE, variables: { id: 'recipe-123' }, }); const recipe = result.data.recipe; console.log(`${recipe.title}: ${recipe.ingredients.join(', ')}`); ``` ## AI Coding Instructions - Request `id`, `title`, `creationDate`, and `ingredients` as required fields; only `description` may be `null`. - Treat `ingredients` as a required array whose individual string entries cannot be `null`. - Serialize and parse `creationDate` using the schema's `Date` scalar conventions rather than assuming it is a JavaScript `Date` object. - Keep GraphQL selection sets explicit so clients only request recipe fields needed by the current view or operation. ## Relationships - TYPE_OF β†’ `Date` ## Referenced By - `recipe` (TYPE_OF) - `recipes` (TYPE_OF) - `addRecipe` (TYPE_OF) - `recipeAdded` (TYPE_OF) # recipeAdded **Kind:** Graphql Subscription **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Subscription` (CALLS_API) # 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) ## Values - `DEFAULT` - `TRANSIENT` - `REQUEST` # Auth ### What it is responsible for The Auth subsystem manages entry through `AuthModule` and `AuthController`, where `signIn` and `getProfile` are named work paths. `AuthService`, `AuthGuard`, `Public`, `jwtConstants`, and `IS_PUBLIC_KEY` mark the stated authentication-facing surface. The evidence links refusal decisions to a token check and a comparison of `user?.password` with `pass`; it does not state output formats, successful-call results, or further policy. It names no relationship among those members beyond their presence in Auth as stated here alone. ### What it refuses The subsystem rejects work with `UnauthorizedException` when `!token`. It rejects work with `UnauthorizedException` when `user?.password !== pass`. These are the stated refusal conditions. No other rejection cases or exception messages are evidenced. The evidence does not attach a different message to either exception case. ### What it needs, and who needs it Auth depends on [Core](subsystem-packages-core). Without Core, Auth lacks its declared dependency; the evidence does not name the Core members involved. [Sample](subsystem-sample) depends on Auth. Without Auth, Sample lacks the subsystem it declares as a dependency, including `AuthModule`, `AuthController`, `signIn`, and `getProfile`. The evidence does not identify Sample callers, the exact Core use, or effects beyond those declared dependency relationships. `AuthService`, `AuthGuard`, `Public`, `jwtConstants`, and `IS_PUBLIC_KEY` are named Auth members, without stated dependency direction here. 9 entities in `sample/19-auth-jwt/src/auth`. **1 other subsystem depends on it**, which makes it the 7th most depended-upon part of this codebase. ## What it is made of Its 9 entities sit in 6 files under `sample/19-auth-jwt/src/auth`: 2 HTTP endpoints, 2 services, 2 constants, 1 controller and 2 more. `auth.controller.ts` holds 3 of them β€” more than any other file here. ## Where work enters 1 controller publishes 2 HTTP endpoints β€” 1 `POST` and 1 `GET`. They answer under `/auth`. None of them declares a guard. - `AuthController` β€” `sample/19-auth-jwt/src/auth/auth.controller.ts`:13 - `signIn` β€” `sample/19-auth-jwt/src/auth/auth.controller.ts`:17 - `getProfile` β€” `sample/19-auth-jwt/src/auth/auth.controller.ts`:24 - `AuthModule` β€” `sample/19-auth-jwt/src/auth/auth.module.ts`:10 ## 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 1 place. ## Boundaries **1 other subsystem depends on this one** β€” `Sample`. Changing what it exposes changes them. They hold 1 edge into it between them. 1 edge arrives and 1 leaves. What they reach is narrower than the folder: 1 of its 9 members carries every inbound edge β€” `AuthModule` (1). It depends on `Core`, and on nothing else in this repository. # Broker **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L667) ## Definition ```ts { isConnected(): boolean; connect(): Promise; disconnect(): Promise; apiVersions(): Promise; metadata(topics: string[]): Promise; describeGroups: (options: { groupIds: string[] }) => Promise; offsetCommit(request: { groupId: string; … ``` # callWithClientUseFactory **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L51) ## Endpoint `POST /useFactory` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # ClientKafka **Kind:** Class **Source:** [`packages/microservices/client/client-kafka.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-kafka.ts#L58) `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 2 places: it logs it and continues in 1, and turns it into a return value in 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. # CreateCatInput **Kind:** Graphql Type **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) Test comment `CreateCatInput` is a GraphQL input type used to provide the data required when creating a cat. It accepts an optional `name` and `age`, and is typically supplied as an argument to a mutation resolver in the cats module. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[createCat Mutation] Mutation --> Input[CreateCatInput] Input --> Name[name: String] Input --> Age[age: Int] Mutation --> Resolver[Cat Resolver] Resolver --> Service[Cat Service] ``` ## Usage ```graphql mutation CreateCat($input: CreateCatInput!) { createCat(createCatInput: $input) { id name age } } ``` ```ts const result = await client.mutate({ mutation: CREATE_CAT_MUTATION, variables: { input: { name: 'Milo', age: 3, }, }, }); ``` ## AI Coding Instructions - Use `CreateCatInput` as the mutation argument type for cat-creation operations rather than passing individual scalar arguments. - Keep field names aligned with the schema: use `name` as a string and `age` as an integer. - Validate business rules, such as non-empty names or valid age ranges, in the resolver or service layer. - Update this input type and the corresponding generated GraphQL types together when adding creation fields. ## Referenced By - `createCat` (TYPE_OF) # deletePost **Kind:** Graphql Mutation **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - TYPE_OF β†’ `Post` ## Referenced By - `Mutation` (CALLS_API) # GlobalModule **Kind:** Module **Source:** [`integration/lazy-modules/src/global.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/global.module.ts#L8) ## Relationships - MODULE_PROVIDES β†’ `GlobalService` - MODULE_EXPORTS β†’ `GlobalService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # HostController **Kind:** Controller **Source:** [`integration/hello-world/src/host/host.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HostController participant p2 as βš™οΈ HostService client->>+p1: HostController p1->>+p2: HostService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - MODULE_DECLARES β†’ `asyncGreeting` - MODULE_DECLARES β†’ `streamGreeting` - MODULE_DECLARES β†’ `localPipe` - DEPENDS_ON β†’ `HostService` ## Referenced By - `HostModule` (MODULE_DECLARES) # 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) 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. # 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) `MqttClientOptions` defines connection and protocol settings for an MQTT client used by the microservices transport layer. It supports standard MQTT TCP/TLS connections as well as WebSocket-based MQTT connections, including client identity, keepalive behavior, and protocol version configuration. ## 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` | `{ /** * representing the Session Expiry Interval in seconds */ sessionExpiryInterval?: number; /** * representing the Receive Maximum */ receiveMaximum?: number; /** * representing the Maximum Packet Size the Client is willing to accept */ maximumPacketSize?: number; /** * representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server */ topicAliasMaximum?: number; /** * The Client uses this value to request the Server to return Response Information in the CONNACK */ requestResponseInformation?: boolean; /** * The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures */ requestProblemInformation?: boolean; /** * The User Property is allowed to appear multiple times to represent multiple name, value pairs */ userProperties?: object; /** * the name of the authentication method used for extended authentication */ authenticationMethod?: string; /** * * Binary Data containing authentication data (binary type) * */ authenticationData?: any; }` | | `reschedulePings` | `boolean` | | `servers` | `Array<{ host: string; port: number; }>` | | `resubscribe` | `boolean` | | `will` | `{ /** * the topic to publish */ topic: string; /** * the message to publish */ payload: string; /** * the QoS */ qos: QoS; /** * the retain flag */ retain: boolean; }` | | `transformWsUrl` | `(url: string, options: any, client: any) => string` | ## Diagram ```mermaid graph LR A[Microservice MQTT Transport] --> B[MqttClientOptions] B --> C[Connection Settings] B --> D[Protocol Settings] B --> E[WebSocket Settings] C --> C1[host / hostname] C --> C2[port] C --> C3[path] D --> D1[protocol] D --> D2[protocolId] D --> D3[protocolVersion] D --> D4[clientId] D --> D5[keepalive] E --> E1[wsOptions] D1 --> F[MQTT Broker] E1 --> F ``` ## 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', keepalive: 60, protocolId: 'MQTT', protocolVersion: 4, wsOptions: {}, }; // Pass mqttOptions to the MQTT transport/client configuration. ``` ## AI Coding Instructions - Use `protocol` values compatible with the target broker and transport, such as `mqtt`, `mqtts`, `ws`, or `wss`. - Configure `host`/`hostname` and `port` together; use the broker’s TLS port when selecting `mqtts` or `wss`. - Provide a stable, unique `clientId` for each running service instance to avoid broker-side client collisions. - Use `wsOptions` only for WebSocket protocols (`ws` and `wss`), such as when custom headers or WebSocket settings are required. - Match `protocolVersion` and `protocolId` to broker compatibility; MQTT 3.1.1 commonly uses `protocolId: 'MQTT'` and `protocolVersion: 4`. # 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) # Partitioners **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L139) ## Definition ```ts { DefaultPartitioner: DefaultPartitioner; LegacyPartitioner: LegacyPartitioner; /** * @deprecated Use DefaultPartitioner instead * * The JavaCompatiblePartitioner was renamed DefaultPartitioner * and made to be the default in 2.0.0. */ JavaCompatiblePartitioner: DefaultPartiti… ``` # recipe **Kind:** Graphql Query **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Query` (CALLS_API) # 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) 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. # TransientLoggerService **Kind:** Service **Source:** [`integration/scopes/src/nested-transient/transient-logger.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/transient-logger.service.ts#L4) `TransientLoggerService` is a NestJS transient-scoped service used to capture context information for nested dependency-injection flows. Each resolved instance maintains its own instance identifier and can expose context inherited or assigned during nested resolution. ## Methods | Method | Signature | Returns | |---|---|---| | `setContext` | `setContext(ctx: string)` | `unknown` | | `getNestedContext` | `getNestedContext()` | `string | undefined` | | `getNestedInstanceId` | `getNestedInstanceId()` | `number` | ## Dependencies - `NestedTransientService` ## Diagram ```mermaid sequenceDiagram participant Consumer as Requesting Service participant Container as Nest DI Container participant Logger as TransientLoggerService Consumer->>Container: Resolve TransientLoggerService Container->>Logger: Create transient instance Consumer->>Logger: setContext(context) Consumer->>Logger: getNestedContext() Logger-->>Consumer: context | undefined Consumer->>Logger: getNestedInstanceId() Logger-->>Consumer: instance ID ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { TransientLoggerService } from './transient-logger.service'; @Injectable() export class NestedWorkerService { constructor( private readonly transientLogger: TransientLoggerService, ) {} process(context: string) { this.transientLogger.setContext(context); const nestedContext = this.transientLogger.getNestedContext(); const instanceId = this.transientLogger.getNestedInstanceId(); console.log(`[${instanceId}] Processing context: ${nestedContext}`); } } ``` ## AI Coding Instructions - Treat `TransientLoggerService` as a transient-scoped dependency; do not assume its state is shared across consumers or resolutions. - Call `setContext()` before reading nested context when the current operation requires explicit context propagation. - Handle `getNestedContext()` returning `undefined`, especially when a context has not yet been assigned. - Use `getNestedInstanceId()` when validating or debugging NestJS transient-provider resolution behavior. - Keep context values operation-specific to avoid confusing logs between nested service instances. ## Relationships - DEPENDS_ON β†’ `NestedTransientService` ## Referenced By - `FirstRequestService` (DEPENDS_ON) - `NestedTransientModule` (MODULE_PROVIDES) - `SecondRequestService` (DEPENDS_ON) # 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) ## 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)[]` | # 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) 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. # AuthController **Kind:** Controller **Source:** [`sample/19-auth-jwt/src/auth/auth.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/auth.controller.ts#L13) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AuthController participant p2 as βš™οΈ AuthService client->>+p1: AuthController p1->>+p2: AuthService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `signIn` - MODULE_DECLARES β†’ `getProfile` - DEPENDS_ON β†’ `AuthService` ## Referenced By - `AuthModule` (MODULE_DECLARES) # ClientMqtt **Kind:** Class **Source:** [`packages/microservices/client/client-mqtt.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-mqtt.ts#L28) `ClientMqtt` is an MQTT-based microservice client that manages the connection lifecycle and request/response messaging patterns for MQTT transport. It creates and monitors an underlying MQTT client, handling connection errors, offline status, reconnects, disconnects, and graceful shutdown events. **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 A[Application Service] --> B[ClientMqtt] B --> C[createClient] C --> D[MQTT Broker] B --> E[connect] E --> D D --> F[Request Topic] F --> B B --> G[Response Topic] B --> H[Lifecycle Listeners] H --> I[Error / Offline / Reconnect / Disconnect] B --> J[mergeCloseEvent] ``` ## AI Coding Instructions - Call `connect()` before publishing requests when the client has not already been initialized by the application lifecycle. - Use `send()` for request/response communication; `ClientMqtt` derives request and response topics through `getRequestPattern()` and `getResponsePattern()`. - Preserve the lifecycle listener registration flow when changing connection behavior: error, offline, reconnect, and disconnect events must remain observable. - Use `close()` during shutdown to release the underlying MQTT connection and complete close-related observables. - Keep MQTT connection options compatible with the configured broker, including URL, credentials, client ID, TLS, and reconnect settings. # concurrent **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L64) ## Endpoint `POST /concurrent` ## Referenced By - `AppController` (MODULE_DECLARES) # ConfigService **Kind:** Service **Source:** [`integration/microservices/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.module.ts#L18) `ConfigService` provides access to application configuration values within the NestJS microservices integration. Its `get()` method is used by other services and modules to retrieve configuration at runtime, keeping environment-specific settings centralized. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(key: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as NestJS Service/Module participant Config as ConfigService participant Source as Configuration Source Consumer->>Config: get("DATABASE_URL") Config->>Source: Read configuration value Source-->>Config: Configuration value Config-->>Consumer: Return value ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; @Injectable() export class DatabaseService { constructor(private readonly configService: ConfigService) {} getConnectionUrl(): string { const connectionUrl = this.configService.get('DATABASE_URL'); if (!connectionUrl) { throw new Error('DATABASE_URL must be configured'); } return connectionUrl; } } ``` ## AI Coding Instructions - Inject `ConfigService` through NestJS constructor injection rather than creating instances manually. - Use typed calls such as `get('KEY')` to make expected configuration values explicit. - Validate required values before using them, since `get()` can return `undefined`. - Keep configuration keys centralized and consistent across modules, environment files, and deployment settings. - Use `ConfigService` at integration boundaries for values such as service URLs, ports, credentials, and feature flags. ## Referenced By - `ConfigModule` (MODULE_PROVIDES) - `ConfigModule` (MODULE_EXPORTS) - `ClientOptionService` (DEPENDS_ON) # 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) ## Definition ```ts { /** * Expected file type(s) for validation. Can be a string (MIME type) * or a regular expression to match multiple types. * * @example * // Match a single MIME type * fileType: 'image/png' * * @example * // Match multiple types using RegExp * fileType: /^image\/(pn… ``` # HeroModule **Kind:** Module **Source:** [`sample/04-grpc/src/hero/hero.module.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/hero/hero.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `HeroController` ## Referenced By - `AppModule` (MODULE_IMPORTS) # MqttEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/mqtt.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/mqtt.events.ts#L12) ## Values - `CONNECT` - `RECONNECT` - `DISCONNECT` - `CLOSE` - `OFFLINE` - `END` - `ERROR` - `PACKETRECEIVE` - `PACKETSEND` # 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) 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. # NewPost **Kind:** Graphql Type **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) `NewPost` is a GraphQL input type used to provide the required data for creating a post. It requires a non-null `title` and `text`, allowing post-creation mutations to receive structured, validated input. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[Create Post Mutation] Mutation --> Input[NewPost Input] Input --> Title[title: String!] Input --> Text[text: String!] Mutation --> PostService[Post Resolver / Prisma] ``` ## Usage ```ts import { gql } from '@apollo/client' const CREATE_POST = gql` mutation CreatePost($input: NewPost!) { createPost(input: $input) { id title text } } ` await client.mutate({ mutation: CREATE_POST, variables: { input: { title: 'Introducing GraphQL', text: 'This post was created using the NewPost input type.', }, }, }) ``` ## AI Coding Instructions - Pass `NewPost` values through a GraphQL variable such as `$input: NewPost!` rather than interpolating user content into mutation strings. - Always provide both `title` and `text`; both fields are required and cannot be `null`. - Keep this input type focused on creation data only; do not include server-generated fields such as `id`, timestamps, or author metadata. - Ensure the corresponding mutation resolver maps `title` and `text` to the Prisma create payload. ## Referenced By - `createPost` (TYPE_OF) # Orders ### What it is responsible for Orders manages order-related creation flow through `OrdersController` and its `create` member, with `OrdersModule` serving as an entry point. The subsystem names `Order` and `CreateOrderDto` alongside `OrdersService`, indicating that creation work is associated with those symbols. `OrderCreatedEvent` and `OrderCreatedListener` identify an event and listener within the same area, while the supplied evidence does not state their runtime behavior. ### What it needs, and who needs it The repository evidence names no dependencies for Orders. `Sample` depends on this subsystem; without Orders, that dependent side loses its declared dependency. Work can enter through `OrdersController`, `create`, and `OrdersModule`, so removal also leaves those named entry points unavailable. The available evidence does not specify any external system, library, or subsystem that Orders requires, nor behavior its absence would directly break. 8 entities in `sample/30-event-emitter/src/orders`. **1 other subsystem depends on it**, which makes it the 8th most depended-upon part of this codebase. ## What it is made of Its 8 entities sit in 7 files under `sample/30-event-emitter/src/orders`: 4 classes, 1 controller, 1 HTTP endpoint, 1 module and 1 more. `orders.controller.ts` holds 2 of them β€” more than any other file here. ## Where work enters 1 controller publishes 1 `POST` endpoint. It answers under `/orders`. None of them declares a guard. - `OrdersController` β€” `sample/30-event-emitter/src/orders/orders.controller.ts`:5 - `create` β€” `sample/30-event-emitter/src/orders/orders.controller.ts`:9 - `OrdersModule` β€” `sample/30-event-emitter/src/orders/orders.module.ts`:6 ## Boundaries **1 other subsystem depends on this one** β€” `Sample`. Changing what it exposes changes them. They hold 1 edge into it between them. What they reach is narrower than the folder: 1 of its 8 members carries every inbound edge β€” `OrdersModule` (1). **It depends on no other subsystem in this repository** β€” it is a leaf. # 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) # recipe **Kind:** Graphql Query **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Query` (CALLS_API) # removeRecipe **Kind:** Graphql Mutation **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Referenced By - `Mutation` (CALLS_API) # 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) ## 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; … ``` # ClientRedis **Kind:** Class **Source:** [`packages/microservices/client/client-redis.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-redis.ts#L28) `ClientRedis` is a Redis-based microservice client that publishes request messages and listens for corresponding reply messages over Redis channels. It manages the Redis connection lifecycle, including connection, reconnection, readiness, errors, and clean shutdown handling. The class integrates with the microservices client transport layer by deriving request and reply channel patterns for message exchange. **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 --> RequestPattern[getRequestPattern()] ClientRedis --> ReplyPattern[getReplyPattern()] RequestPattern --> Redis[(Redis)] Redis --> ReplyPattern ReplyPattern --> App ClientRedis --> Lifecycle[Connection Lifecycle] Lifecycle --> Connect[connect / createClient] Lifecycle --> Events[error / reconnect / ready / end listeners] Lifecycle --> Close[close / handleClose] ``` ## Usage ```ts import { ClientRedis } from '@nestjs/microservices'; const client = new ClientRedis({ host: 'localhost', port: 6379, }); // Establish Redis publisher/subscriber connections. await client.connect(); // Send a request and receive the handler response. client.send('users.findOne', { id: '42' }).subscribe({ next: (user) => console.log('User:', user), error: (error) => console.error('Request failed:', error), }); // Close Redis connections during application shutdown. await client.close(); ``` ## AI Coding Instructions - Use `getRequestPattern()` and `getReplyPattern()` consistently when changing Redis channel naming; request and response channel formats must remain compatible with server-side Redis transport handling. - Call `connect()` before sending messages when using the client outside Nest’s managed application lifecycle. - Register lifecycle listeners on every Redis client created by `createClient()` so connection errors, reconnections, readiness, and shutdown events are handled consistently. - Ensure `close()` and `handleClose()` clean up all Redis connections and pending request state to prevent hanging observables or process shutdown issues. - Avoid treating Redis connection errors as request responses; transport failures should propagate through the client error-handling path. # concurrent **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L48) ## Endpoint `POST /concurrent` ## Referenced By - `MqttController` (MODULE_DECLARES) # ConfigOptions **Kind:** Interface **Source:** [`sample/25-dynamic-modules/src/config/interfaces/config-options.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/config/interfaces/config-options.interface.ts#L1) `ConfigOptions` defines the configuration accepted by the dynamic configuration module. Its `folder` property identifies the directory containing configuration files or resources that should be loaded by the application. ## Properties | Property | Type | |---|---| | `folder` | `string` | ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[ConfigOptions] B --> C[folder: string] C --> D[Configuration Directory] D --> E[Loaded Configuration] ``` ## Usage ```ts import type { ConfigOptions } from './config/interfaces/config-options.interface'; const configOptions: ConfigOptions = { folder: './config', }; // Example: pass options when initializing a dynamic config module ConfigModule.forRoot(configOptions); ``` ## AI Coding Instructions - Provide `folder` as a valid string path to the directory containing configuration resources. - Keep this interface focused on module initialization options; avoid adding runtime configuration values directly to it. - Validate or normalize the folder path in the module implementation before reading files from disk. - When adding new options, update module factory methods and all configuration-loading call sites accordingly. ## Referenced By - `ConfigService` (DEPENDS_ON) # ConfigService **Kind:** Service **Source:** [`integration/microservices/src/tcp-tls/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.module.ts#L29) `ConfigService` provides configuration values for the TCP/TLS microservice application. It is registered within the NestJS application module and exposes a `get()` method for retrieving configuration used by other providers and bootstrap code. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(key: string, defaultValue: any)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant AppModule as AppModule participant Consumer as Service/Provider participant Config as ConfigService AppModule->>Config: Register provider Consumer->>Config: get() Config-->>Consumer: Configuration value ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ConfigService } from './app.module'; @Injectable() export class TcpClientService { constructor(private readonly configService: ConfigService) {} getConnectionOptions() { const config = this.configService.get(); return { host: config.host, port: config.port, }; } } ``` ## AI Coding Instructions - Inject `ConfigService` through NestJS constructor injection instead of creating it manually. - Use `get()` as the single access point for service configuration values. - Keep configuration consumers independent of environment-variable parsing logic. - Ensure `ConfigService` remains registered in the module providers before injecting it elsewhere. ## Referenced By - `ConfigModule` (MODULE_PROVIDES) - `ConfigModule` (MODULE_EXPORTS) - `ClientOptionService` (DEPENDS_ON) # ExpressController **Kind:** Controller **Source:** [`integration/nest-application/raw-body/src/express.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/raw-body/src/express.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ ExpressController client->>+p1: ExpressController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getRawBody` ## Referenced By - `ExpressModule` (MODULE_DECLARES) # 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) ## Signature ```ts function FilesInterceptor(fieldName: string, maxCount: number, localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `fieldName` | `string` | | `maxCount` | `number` | | `localOptions` | `MulterOptions` | **Returns:** `Type` # HostArrayModule **Kind:** Module **Source:** [`integration/hello-world/src/host-array/host-array.module.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `HostArrayController` - MODULE_PROVIDES β†’ `HostArrayService` - MODULE_PROVIDES β†’ `usersservice` ## Referenced By - `AppModule` (MODULE_IMPORTS) # Integration ### What it is responsible for Integration manages entry handling through `AppController`, `getGlobals`, `AppV1Controller`, `helloWorldV1`, `paramV1`, and `AppV2Controller`, and it turns incoming work into controller, module, service, class, and API-endpoint activity. Its named members indicate responsibility spans application setup and request-facing behavior: `AppModule` and `AppController` sit alongside `RecipesModule`, `RecipesResolver`, `RecipesService`, `AuthGuard`, and `DataInterceptor`. The authors explicitly identify HTTP Proxy entries supporting non-stream find methods and client-side stream find methods, define a β€œDate custom scalar type,” and mark one decorator with: β€œThis decorator must not be used anywhere!” These statements bound documented behavior without assigning unstated behavior to every listed member. ### What it refuses Integration rejects a `gqlContext` with `UnauthorizedException`. It rejects a missing recipe (`!recipe`) with `NotFoundException`. It rejects `isNaN(val)` with β€œValidation failed.” It rejects a missing `this.helperSvc.request` with `error`, an undefined durable service with β€œDurable service is undefined,” and `requestPayload.forceError` with β€œForced error.” These are explicit refusal conditions; callers reaching the relevant paths receive the stated failures rather than continued processing. ### What it needs, and who needs it Integration depends on `integration/discovery/src/my-webhook`, [Core](subsystem-packages-core), [Host](subsystem-integration-hello-world-src-host), [Host Array](subsystem-integration-hello-world-src-host-array), `integration/injector/src/exports`, [Dogs](subsystem-integration-inspector-src-dogs), `integration/inspector/src/external-svc`, `integration/inspector/src/chat`, [Microservices](subsystem-packages-microservices), and [Common](subsystem-packages-common). The supplied dependency record names no subsystem that depends on Integration. Therefore, the evidence identifies Integration as the needing side, but does not identify an external consuming side or establish which external component breaks without it. Within Integration, the record names entry symbols and modules, but does not assign any dependency to an individual work path. ### Notable members `AppController` is a named work entry. `RecipesService` appears with `RecipesResolver` and `RecipesModule`; absent recipes are rejected with `NotFoundException`. `AuthGuard` is named alongside a `gqlContext` rejection: `UnauthorizedException` in the evidence. 188 entities in `integration`. Nothing else in this repository depends on it. ## What it is made of Its 188 entities sit in 95 files under `integration`: 54 HTTP endpoints, 48 modules, 25 controllers, 17 services and 44 more. `utils.ts` holds 13 of them β€” more than any other file here. `AppService` declares 7 methods, the widest surface here. ## Where work enters 25 controllers publish 54 HTTP endpoints β€” 40 `GET` and 14 `POST`. They answer under `/foo` and `/lazy`. `AppController` carries 30 of them; the remaining 24 are split across 14 other controllers. None of them declares a guard. - `AppController` β€” `integration/cors/src/app.controller.ts`:3 - `getGlobals` β€” `integration/cors/src/app.controller.ts`:5 - `AppV1Controller` β€” `integration/inspector/src/app-v1.controller.ts`:3 - `helloWorldV1` β€” `integration/inspector/src/app-v1.controller.ts`:7 - `paramV1` β€” `integration/inspector/src/app-v1.controller.ts`:12 - `AppV2Controller` β€” `integration/inspector/src/app-v2.controller.ts`:3 ## Boundaries It depends on `My Webhook`, `Core`, `Host`, `Host Array`, `Exports`, `Dogs`, `External Svc`, `Chat`, `Microservices`, `Common`, 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 | |---|---|---|---| | `*.module.ts` | across the repository | 100 | `a.module.ts`, `b.module.ts`, `c.module.ts`, `app.module.ts` | | `*.service.ts` | across the repository | 80 | `bar.service.ts`, `foo.service.ts`, `app.service.ts`, `cats.service.ts` | | `*.controller.ts` | across the repository | 71 | `app.controller.ts`, `rmq.controller.ts`, `host.controller.ts`, `cats.controller.ts` | | `*.dto.ts` | across the repository | 26 | `sum.dto.ts`, `test.dto.ts`, `user.dto.ts`, `business.dto.ts` | # 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) ## Definition ```ts [ 'verbose', 'debug', 'log', 'warn', 'error', 'fatal', ] as const satisfies string[] ``` ## Value ```ts [ 'verbose', 'debug', 'log', 'warn', 'error', 'fatal', ] as const satisfies string[] ``` # NewRecipeInput **Kind:** Graphql Type **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) `NewRecipeInput` is a GraphQL input type used to provide the data required to create a new recipe. It requires a recipe title and at least one ingredient value, while the description is optional. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[createRecipe Mutation] Mutation --> Input[NewRecipeInput] Input --> Title[title: String!] Input --> Description[description: String] Input --> Ingredients[ingredients: String[]!] Mutation --> RecipeService[Recipe Service] ``` ## Usage ```ts import { gql } from "@apollo/client"; const CREATE_RECIPE = gql` mutation CreateRecipe($input: NewRecipeInput!) { createRecipe(input: $input) { id title description ingredients } } `; await client.mutate({ mutation: CREATE_RECIPE, variables: { input: { title: "Tomato Pasta", description: "A quick pasta recipe with tomatoes and basil.", ingredients: ["spaghetti", "tomatoes", "garlic", "basil"], }, }, }); ``` ## AI Coding Instructions - Pass `NewRecipeInput` as the mutation input variable when creating recipes; do not send its fields as unrelated top-level variables. - Always provide a non-empty `title` and an `ingredients` array, since both fields are non-nullable in the GraphQL schema. - Ensure every item in `ingredients` is a string; `null` values are not valid within the list. - Treat `description` as optional and omit it when no description is available rather than supplying invalid placeholder values. - Keep client-side input types synchronized with `integration/graphql-code-first/schema.gql` when schema fields change. ## Referenced By - `addRecipe` (TYPE_OF) # 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) # recipe **Kind:** Graphql Query **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Query` (CALLS_API) # removeRecipe **Kind:** Graphql Mutation **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Referenced By - `Mutation` (CALLS_API) # TcpEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/tcp.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/tcp.events.ts#L15) ## Values - `ERROR` - `CONNECT` - `END` - `CLOSE` - `TIMEOUT` - `DRAIN` - `LOOKUP` - `LISTENING` # AclResourceTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L285) ## Values - `UNKNOWN` - `ANY` - `TOPIC` - `GROUP` - `CLUSTER` - `TRANSACTIONAL_ID` - `DELEGATION_TOKEN` # ClientRMQ **Kind:** Class **Source:** [`packages/microservices/client/client-rmq.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-rmq.ts#L57) `ClientRMQ` is a RabbitMQ client transport that manages AMQP connections, channels, and lifecycle events for microservice communication. It creates and configures a connection through `AmqpConnectionManager`, registers error/disconnect listeners, and exposes connection handling through the standard client proxy workflow. **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 App[Application Service] --> Client[ClientRMQ] Client --> Connection[AmqpConnectionManager] Connection --> RabbitMQ[(RabbitMQ Broker)] Client --> Channel[Confirm Channel] Channel --> RabbitMQ Connection --> Errors[Error Listener] Connection --> Disconnect[Disconnect Listener] Disconnect --> Reconnect[Reconnect / Connection Promise] ``` ## AI Coding Instructions - Call `connect()` before relying on the client for request-response or event publishing, especially in custom bootstrap code. - Configure valid RabbitMQ URLs, queue names, and durable queue options; queue configuration must match the corresponding consumer setup. - Preserve connection error and disconnect listener behavior when modifying connection setup, since these listeners support reconnect and failure handling. - Use `close()` during graceful shutdown to release AMQP channels and connection-manager resources. - Avoid directly managing channels outside `ClientRMQ` unless necessary; use its connection and channel setup flow to retain lifecycle handling. # Cluster **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L199) ## Definition ```ts { getNodeIds(): number[]; metadata(): Promise; removeBroker(options: { host: string; port: number }): void; addMultipleTargetTopics(topics: string[]): Promise; isConnected(): boolean; connect(): Promise; disconnect(): Promise; refreshMetadata(): Prom… ``` # concurrent **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L51) ## Endpoint `POST /concurrent` ## Referenced By - `NatsController` (MODULE_DECLARES) # 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) `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. # 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) # FastifyController **Kind:** Controller **Source:** [`integration/nest-application/raw-body/src/fastify.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/raw-body/src/fastify.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ FastifyController client->>+p1: FastifyController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getRawBody` ## Referenced By - `FastifyModule` (MODULE_DECLARES) # HostModule **Kind:** Module **Source:** [`integration/hello-world/src/host/host.module.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `HostController` - MODULE_PROVIDES β†’ `HostService` - MODULE_PROVIDES β†’ `usersservice` ## Referenced By - `AppModule` (MODULE_IMPORTS) # INVALID_MODULE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L156) ## 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` | # MESSAGES **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L3) ## 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()', } ``` # NewRecipeInput **Kind:** Graphql Type **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) `NewRecipeInput` is a GraphQL input type used to provide the data required when creating a new recipe. It requires a recipe title and at least a list of non-null ingredient strings, while allowing an optional description. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[Create Recipe Mutation] Mutation --> Input[NewRecipeInput] Input --> Title["title: String!"] Input --> Description["description: String"] Input --> Ingredients["ingredients: [String!]!"] Mutation --> RecipeService[Recipe Creation Logic] ``` ## Usage ```ts import { gql } from "@apollo/client"; const CREATE_RECIPE = gql` mutation CreateRecipe($input: NewRecipeInput!) { createRecipe(input: $input) { id title description ingredients } } `; const variables = { input: { title: "Tomato Pasta", description: "A quick and simple pasta recipe.", ingredients: ["pasta", "tomatoes", "garlic", "olive oil"], }, }; // Example Apollo Client usage: // await client.mutate({ mutation: CREATE_RECIPE, variables }); ``` ## AI Coding Instructions - Pass `NewRecipeInput` as a mutation variable rather than constructing recipe data from separate arguments. - Always provide a non-empty `title` value and an `ingredients` array; both fields are required by the schema. - Ensure every value in `ingredients` is a string, since `[String!]!` does not allow `null` entries or a `null` list. - Treat `description` as optional and omit it when no meaningful description is available. - Keep client mutation field names aligned with the schema definition in `schema.gql`. ## Referenced By - `addRecipe` (TYPE_OF) # PrismaService **Kind:** Service **Source:** [`sample/22-graphql-prisma/src/prisma/prisma.service.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/prisma/prisma.service.ts#L9) `PrismaService` is a NestJS provider that manages the Prisma database client lifecycle for the GraphQL Prisma sample application. It initializes the Prisma connection when the NestJS module starts, making database access available to resolvers and other services through dependency injection. ## Methods | Method | Signature | Returns | |---|---|---| | `onModuleInit` | `onModuleInit()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Nest as NestJS Application participant PrismaService as PrismaService participant Prisma as Prisma Client participant DB as Database Nest->>PrismaService: Create provider Nest->>PrismaService: onModuleInit() PrismaService->>Prisma: $connect() Prisma->>DB: Open database connection DB-->>Prisma: Connection established Prisma-->>PrismaService: Ready PrismaService-->>Nest: Provider initialized ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class UsersService { constructor(private readonly prisma: PrismaService) {} async findAll() { return this.prisma.user.findMany({ orderBy: { id: 'asc' }, }); } async findById(id: number) { return this.prisma.user.findUnique({ where: { id }, }); } } ``` ## AI Coding Instructions - Inject `PrismaService` through NestJS constructor injection instead of creating `PrismaClient` instances directly. - Keep database connection initialization in `onModuleInit()` so Prisma is ready before application requests are handled. - Use generated Prisma model delegates such as `prisma.user`, `prisma.post`, or equivalent schema-defined models for queries. - Register and export `PrismaService` from `PrismaModule` before injecting it into feature modules. - Prefer Prisma query options (`select`, `include`, `where`, and `orderBy`) to control returned data and avoid unnecessary database reads. ## Referenced By - `PostsService` (DEPENDS_ON) - `PrismaModule` (MODULE_PROVIDES) - `PrismaModule` (MODULE_EXPORTS) # recipes **Kind:** Graphql Query **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Query` (CALLS_API) # removeRecipe **Kind:** Graphql Mutation **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Referenced By - `Mutation` (CALLS_API) # Sample ### What it is responsible for Sample manages application entry paths and example-facing interfaces, with `AppController`/`getHello` and `AppController`/`root` identified as work-entry points. Its named pieces span controller actions such as `create`, `findAll`, and `findOne`; GraphQL access at `/graphql`; and a Swagger interface at `/api`. The documented startup paths include examples requiring Docker or local MySQL, and others requiring Docker or local mongodb; after their required service is available, Nest runs with `npm run start`. The authors also flag a remote-machine listen-address change under the documented adapter instructions. ### What it refuses Sample rejects input when validation reports `Validation failed` because `isNaN(val)` or because `errors.length > 0`. It rejects authentication attempts with `UnauthorizedException` when `!token` and when `user?.password !== pass`. It rejects missing recipes with `NotFoundException` when `!recipe`, and GraphQL requests with `GraphQLError` when `complexity >= 20`. ### What it needs, and who needs it Sample depends on `sample/03-microservices/src/math`, `sample/04-grpc/src/hero`, `Auth`, `sample/26-queues/src/audio`, `sample/27-scheduling/src/tasks`, and `Orders`. Those named dependencies are the external sides Sample needs; without any one, the supplied evidence does not state a specific failure mode. No subsystem is listed as depending on Sample, so the evidence names no consumer that would break without it. ### Notable members `AppController` carries listed entry work through `getHello` and `root`, making it the clearest ingress symbol. `ValidationPipe` and `ParseIntPipe` carry the displayed validation boundary: the refusal conditions explicitly cover invalid numeric input and nonempty validation errors. `RolesGuard` is the named authorization boundary most closely aligned with the two displayed `UnauthorizedException` conditions, while `CatsController` is the named controller alongside the `create`, `findAll`, and `findOne` operations. Their exact internal control flow is not documented here. 449 entities in `sample`. Nothing else in this repository depends on it. ## What it is made of Its 449 entities sit in 92 files under `sample`: 312 doc comments, 40 modules, 25 markdown docs, 14 HTTP endpoints and 58 more. `schema.gql` holds 11 of them β€” more than any other file here. ## Where work enters 11 controllers publish 14 HTTP endpoints β€” 11 `GET` and 3 `POST`. None of them declares a guard. - `AppController` β€” `sample/08-webpack/src/app.controller.ts`:4 - `getHello` β€” `sample/08-webpack/src/app.controller.ts`:8 - `AppController` β€” `sample/15-mvc/src/app.controller.ts`:3 - `root` β€” `sample/15-mvc/src/app.controller.ts`:5 - `AppController` β€” `sample/17-mvc-fastify/src/app.controller.ts`:3 - `root` β€” `sample/17-mvc-fastify/src/app.controller.ts`:5 ## Boundaries It depends on `Math`, `Hero`, `Auth`, `Audio`, `Tasks`, `Orders`, 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 | |---|---|---|---| | `*.module.ts` | across the repository | 73 | `app.module.ts`, `cats.module.ts`, `core.module.ts`, `math.module.ts` | | `*.service.ts` | across the repository | 30 | `app.service.ts`, `cats.service.ts`, `auth.service.ts`, `users.service.ts` | | `*.controller.ts` | across the repository | 25 | `app.controller.ts`, `cats.controller.ts`, `math.controller.ts`, `hero.controller.ts` | | `find*` | exported symbols | 17 | `findAll`, `findOne` | # 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) ## 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', } ``` # ClientTCP **Kind:** Class **Source:** [`packages/microservices/client/client-tcp.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-tcp.ts#L16) `ClientTCP` is a TCP-based microservice client that manages a socket connection to a remote NestJS microservice. It creates and monitors the socket, handles connection/error/close events, and routes incoming responses back to pending request handlers. **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 A[Application Service] --> B[ClientTCP] B --> C[createSocket] C --> D[TCP Socket] D --> E[Remote TCP Microservice] E --> D D --> F[handleResponse] F --> G[Pending Request Observer] D -. connect .-> H[registerConnectListener] D -. error .-> I[registerErrorListener] D -. close .-> J[registerCloseListener] I --> K[handleError] J --> L[handleClose] ``` ## AI Coding Instructions - Call `connect()` before issuing requests when manually managing a `ClientTCP` instance; ensure `close()` is called during shutdown or cleanup. - Keep TCP host and port configuration externalized through environment variables or application configuration rather than hardcoding production values. - Use `send()` for request-response messaging and ensure the remote microservice handles the same message pattern (for example, `{ cmd: 'get_user' }`). - Do not bypass socket lifecycle handlers; `registerConnectListener()`, `registerErrorListener()`, and `registerCloseListener()` coordinate connection state and pending request cleanup. - Handle connection failures and socket closures gracefully, since `handleError()` and `handleClose()` can reject active or queued requests. # concurrent **Kind:** API Endpoint **Source:** [`integration/microservices/src/redis/redis.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis.controller.ts#L33) ## Endpoint `POST /concurrent` ## Referenced By - `RedisController` (MODULE_DECLARES) # ConfigSource **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L302) ## Values - `UNKNOWN` - `TOPIC_CONFIG` - `DYNAMIC_BROKER_CONFIG` - `DYNAMIC_DEFAULT_BROKER_CONFIG` - `STATIC_BROKER_CONFIG` - `DEFAULT_CONFIG` - `DYNAMIC_BROKER_LOGGER_CONFIG` # HttpController **Kind:** Controller **Source:** [`integration/scopes/src/msvc/http.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/http.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HttpController client->>+p1: HttpController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `testMsvc` ## Referenced By - `HelloModule` (MODULE_DECLARES) # 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) # mapToClass **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L57) ## Signature ```ts function mapToClass(middleware: T, excludedRoutes: ExcludeRouteMetadata[], httpAdapter: HttpServer) ``` ## Parameters | Name | Type | |---|---| | `middleware` | `T` | | `excludedRoutes` | `ExcludeRouteMetadata[]` | | `httpAdapter` | `HttpServer` | # MathModule **Kind:** Module **Source:** [`sample/03-microservices/src/math/math.module.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/math/math.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `MathController` ## Referenced By - `AppModule` (MODULE_IMPORTS) # 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) ## Definition ```ts { /** * Maximum allowed file size in bytes. */ maxSize: number; /** * @deprecated Use `errorMessage` instead. */ message?: string | ((maxSize: number) => string); /** * Custom error message returned when file size validation fails. * Can be provided as a static string, … ``` # NewRecipeInput **Kind:** Graphql Type **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) `NewRecipeInput` defines the required and optional data for creating a new recipe through the GraphQL API. It requires a recipe title and at least an array of non-null ingredient strings, while allowing an optional description. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[Create Recipe Mutation] Mutation --> Input[NewRecipeInput] Input --> Title["title: String!"] Input --> Description["description: String"] Input --> Ingredients["ingredients: [String!]!"] Mutation --> RecipeService[Recipe Service] ``` ## Usage ```ts const mutation = ` mutation CreateRecipe($input: NewRecipeInput!) { createRecipe(input: $input) { id title description ingredients } } `; const variables = { input: { title: "Tomato Pasta", description: "A quick and simple pasta dish.", ingredients: ["pasta", "tomatoes", "garlic", "olive oil"], }, }; const response = await fetch("http://localhost:3000/graphql", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query: mutation, variables }), }); const { data, errors } = await response.json(); ``` ## AI Coding Instructions - Pass `NewRecipeInput` as a mutation variable rather than interpolating user-provided values directly into GraphQL query strings. - Always provide a non-empty `title` value and an `ingredients` array; both fields are required by the schema. - Ensure every item in `ingredients` is a string, since `[String!]!` disallows both a null array and null entries. - Treat `description` as optional and omit it or send `null` when no recipe description is available. - Keep client-side input validation aligned with the GraphQL schema to provide clearer errors before mutation execution. ## Referenced By - `addRecipe` (TYPE_OF) # recipes **Kind:** Graphql Query **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Query` (CALLS_API) # ServiceInjectingItself **Kind:** Service **Source:** [`integration/injector/src/self-injection/self-injection-provider.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/self-injection/self-injection-provider.module.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ ServiceInjectingItself client->>+p1: ServiceInjectingItself p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `ServiceInjectingItself` ## Referenced By - `ServiceInjectingItself` (DEPENDS_ON) - `ServiceInjectingItselfForward` (DEPENDS_ON) - `SelfInjectionProviderModule` (MODULE_PROVIDES) # updatePost **Kind:** Graphql Mutation **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - TYPE_OF β†’ `Post` - TYPE_OF β†’ `UpdatePost` ## Referenced By - `Mutation` (CALLS_API) # Websockets ### What it is responsible for The Websockets subsystem manages websocket-oriented work entering through `BaseWsInstance`, `AbstractWsAdapter`, and `MESSAGE_MAPPING_METADATA`. Its documented repository context describes Nest as a framework for building Node.js server-side applications; within that context, this subsystem owns the named websocket entry points rather than an independently documented external dependency. `MESSAGE_MAPPING_METADATA` marks a metadata-based boundary for work entering the subsystem, while the two class-level entry points establish the visible instance and adapter sides of that boundary. The available evidence does not describe transport behavior, connection lifecycle rules, message formats, routing semantics, or external integration details, so those should not be assumed from these names alone. ### What it refuses It rejects activation when `!canActivate`, with `WsException`. It rejects exception-filter input when `!Array.isArray(filters)`, with `InvalidExceptionFilterException`. It rejects a socket port when `!Number.isInteger(port)`, with `InvalidSocketPortException`. No literal exception text is present in the supplied evidence; the exception symbols and predicate conditions are the developers’ stated rejection information. ### Notable members - `BaseWsInstance` is a work-entry symbol and carries the instance-facing side of the subsystem’s visible boundary. - `AbstractWsAdapter` is a work-entry symbol and identifies the abstract adapter-facing side of that boundary. - `MESSAGE_MAPPING_METADATA` is a work-entry constant that identifies the metadata boundary associated with incoming mapped work in this named subsystem. 87 entities in `packages/websockets`. Nothing else in this repository depends on it. ## 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` β€” `packages/websockets/adapters/ws-adapter.ts`:8 - `AbstractWsAdapter` β€” `packages/websockets/adapters/ws-adapter.ts`:13 - `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. ## 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` | # CompressionCodecs **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1137) ## Definition ```ts { [CompressionTypes.GZIP]: () => any; [CompressionTypes.Snappy]: () => any; [CompressionTypes.LZ4]: () => any; [CompressionTypes.ZSTD]: () => any; } ``` # concurrent **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L48) ## Endpoint `POST /concurrent` ## Referenced By - `RMQController` (MODULE_DECLARES) # DependenciesScanner **Kind:** Class **Source:** [`packages/core/scanner.ts`](https://github.com/nestjs/nest/blob/master/packages/core/scanner.ts#L75) `DependenciesScanner` discovers an application's module graph and registers modules, providers, controllers, imports, exports, and dynamic metadata in the Nest container. It is part of Nest's bootstrap pipeline, translating decorator metadata into the runtime dependency-injection structure used to create the application. ## 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 RootModule[Root Module] --> Scan[DependenciesScanner.scan] Scan --> ModuleDiscovery[scanForModules] ModuleDiscovery --> Insert[insertModule] Insert --> Container[NestContainer] Container --> Imports[reflectImports] Container --> Providers[reflectProviders] Container --> Controllers[reflectControllers] Container --> Exports[reflectExports] Container --> Dynamic[reflectDynamicMetadata] Providers --> Injectables[reflectInjectables] Imports --> DependencyGraph[Module Dependency Graph] Providers --> DependencyGraph Controllers --> DependencyGraph Exports --> DependencyGraph ``` ## 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'; // Typically created internally by NestFactory during application bootstrap. const container = new NestContainer(); const metadataScanner = new MetadataScanner(); const applicationConfig = new ApplicationConfig(); const graphInspector = new GraphInspector(container); const scanner = new DependenciesScanner( container, metadataScanner, graphInspector, applicationConfig, ); await scanner.scan(AppModule); // The container now contains discovered modules, providers, and controllers. const appModule = container.getModules().get(AppModule.name); ``` ## AI Coding Instructions - Treat `DependenciesScanner` as bootstrap infrastructure; application code should normally use `NestFactory` rather than instantiate it directly. - Ensure modules expose valid Nest metadata (`imports`, `providers`, `controllers`, and `exports`) before scanning, since reflection methods depend on that metadata. - Preserve scanning order: modules must be discovered and inserted before provider, controller, export, and injectable metadata is reflected. - When adding new metadata handling, update the relevant `reflect*` method and ensure the resulting definitions are registered through `NestContainer`. - Handle dynamic modules and module overrides consistently with `scanForModules()` and `reflectDynamicMetadata()` to avoid incomplete dependency graphs. # 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) 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. # MathController **Kind:** Controller **Source:** [`sample/03-microservices/src/math/math.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/math/math.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ MathController participant p2 as βš™οΈ ClientProxy client->>+p1: MathController p1->>+p2: ClientProxy p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `execute` - DEPENDS_ON β†’ `ClientProxy` ## Referenced By - `MathModule` (MODULE_DECLARES) # OrdersModule **Kind:** Module **Source:** [`sample/30-event-emitter/src/orders/orders.module.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/orders.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `OrdersController` - MODULE_PROVIDES β†’ `OrdersService` - MODULE_PROVIDES β†’ `OrderCreatedListener` ## Referenced By - `AppModule` (MODULE_IMPORTS) # OrdersService **Kind:** Service **Source:** [`sample/30-event-emitter/src/orders/orders.service.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/orders.service.ts#L7) `OrdersService` encapsulates order creation logic in the NestJS event-emitter sample. Its `create()` method is responsible for creating an order and publishing the associated domain event so other parts of the application can react without tightly coupling to the order workflow. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createOrderDto: CreateOrderDto)` | `unknown` | ## Dependencies - `EventEmitter2` ## Diagram ```mermaid sequenceDiagram participant Client participant OrdersController participant OrdersService participant EventEmitter participant Listener as Order Event Listener Client->>OrdersController: POST /orders OrdersController->>OrdersService: create() OrdersService->>OrdersService: Create order OrdersService->>EventEmitter: emit("order.created", order) EventEmitter-->>Listener: Handle order-created event OrdersService-->>OrdersController: Return created order OrdersController-->>Client: Order response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { OrdersService } from './orders/orders.service'; @Injectable() export class CheckoutService { constructor(private readonly ordersService: OrdersService) {} async checkout() { const order = await this.ordersService.create(); return { message: 'Order created successfully', order, }; } } ``` ## AI Coding Instructions - Keep order-creation behavior inside `OrdersService`; controllers should delegate to the service rather than implementing business logic. - Preserve event-driven integration by emitting the expected order-created event after a successful order creation. - Avoid placing slow or nonessential follow-up work directly in `create()`; handle notifications, analytics, or side effects through event listeners. - Ensure event payloads remain stable and include the data required by downstream listeners. - Update dependent listeners and tests when changing the event name or the value returned by `create()`. ## Relationships - DEPENDS_ON β†’ `eventemitter2` ## Referenced By - `OrdersController` (DEPENDS_ON) - `OrdersModule` (MODULE_PROVIDES) # Owner **Kind:** Graphql Type **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) `Owner` is a GraphQL object type representing a cat owner in the schema-first Cats domain. It exposes required identity and name fields, an optional age, and an optional list of associated `Cat` records for querying owner-to-cat relationships. ## Diagram ```mermaid graph LR Owner["Owner"] Owner --> ID["id: Int!"] Owner --> Name["name: String!"] Owner --> Age["age: Int"] Owner --> Cats["cats: [Cat!]"] Cats --> Cat["Cat"] ``` ## Usage ```graphql query GetOwnerWithCats($ownerId: Int!) { owner(id: $ownerId) { id name age cats { id name age } } } ``` ```ts const result = await client.query({ query: GET_OWNER_WITH_CATS, variables: { ownerId: 1 }, }); const owner = result.data.owner; console.log(`${owner.name} owns ${owner.cats?.length ?? 0} cats.`); ``` ## AI Coding Instructions - Keep `id` and `name` populated in all `Owner` resolver responses because both fields are non-nullable. - Return `null` for unknown owner ages rather than substituting a placeholder value, since `age` is optional. - Resolve `cats` as an array of valid `Cat` objects when present; individual list items cannot be `null`. - Update the corresponding GraphQL resolvers and generated TypeScript types when adding or changing `Owner` fields. ## Relationships - TYPE_OF β†’ `Cat` ## Referenced By - `Cat` (TYPE_OF) # Platform Express ### What it is responsible for Platform Express manages work that enters through `MulterModule`, with the supplied evidence identifying this module as the subsystem’s entry point. Its named surface also includes `FileInterceptor`, `FilesInterceptor`, `AnyFilesInterceptor`, `FileFieldsInterceptor`, and `NoFilesInterceptor`. Beyond those names and the entry point, the evidence does not state the processing rules, lifecycle, inputs, outputs, or coordination performed by these members. The accompanying comments describe Nest as a framework for building Node.js server-side applications and direct readers to the guide at docs.nestjs.com, but they do not assign a more specific responsibility to Platform Express. Therefore this subsystem should be documented only with its `MulterModule` entry point and listed interceptor names, rather than as claiming unshown behavior. ### What it refuses When `!next`, it refuses work if the HTTP adapter does not support filtering on version. The stated condition is: β€œHTTP adapter does not support filtering on version.” No other rejection condition is supplied. ### Notable members - `MulterModule` is where work enters the subsystem. - `FileInterceptor` is a named member; its specific action is not described in the supplied evidence. - `FilesInterceptor` is another named member; its specific action is likewise not described. This limitation prevents a more evidence-based account of either interceptor in the record. 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` β€” `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. ## 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` | # Producer **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L798) ## Definition ```ts Sender & { connect(): Promise; disconnect(): Promise; isIdempotent(): boolean; readonly events: ProducerEvents; on( eventName: ProducerEvents['CONNECT'], listener: (event: ConnectEvent) => void, ): RemoveInstrumentationEventListener; on( eventN… ``` # recipes **Kind:** Graphql Query **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - TYPE_OF β†’ `Recipe` ## Referenced By - `Query` (CALLS_API) # RedisEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/redis.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/redis.events.ts#L11) ## Values - `CONNECT` - `READY` - `ERROR` - `CLOSE` - `RECONNECTING` - `END` - `WARNING` # 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) ## 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` # concurrent **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L77) ## Endpoint `POST /concurrent` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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 > & … ``` ## 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. # DatabaseService **Kind:** Service **Source:** [`integration/inspector/src/database/database.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.service.ts#L5) `DatabaseService` is a NestJS service responsible for encapsulating database-related operations in the Inspector integration. It provides a standard CRUD-style interface for creating, retrieving, updating, and removing database records, keeping persistence concerns separate from controllers and other application services. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createDatabaseDto: CreateDatabaseDto)` | `unknown` | | `findAll` | `findAll()` | `unknown` | | `findOne` | `findOne(id: number)` | `unknown` | | `update` | `update(id: number, updateDatabaseDto: UpdateDatabaseDto)` | `unknown` | | `remove` | `remove(id: number)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Controller participant DatabaseService participant Database Controller->>DatabaseService: create(data) DatabaseService->>Database: Insert record Database-->>DatabaseService: Created record DatabaseService-->>Controller: Return result Controller->>DatabaseService: findAll() DatabaseService->>Database: Query records Database-->>DatabaseService: Record list DatabaseService-->>Controller: Return results ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { DatabaseService } from './database/database.service'; @Injectable() export class InspectorService { constructor(private readonly databaseService: DatabaseService) {} async getDatabaseRecords() { return this.databaseService.findAll(); } async createDatabaseRecord() { return this.databaseService.create(); } async updateDatabaseRecord() { return this.databaseService.update(); } async deleteDatabaseRecord() { return this.databaseService.remove(); } } ``` ## AI Coding Instructions - Keep database access logic inside `DatabaseService`; controllers should delegate CRUD operations rather than interact with persistence code directly. - Preserve the existing CRUD method contract: `create`, `findAll`, `findOne`, `update`, and `remove`. - Add explicit DTOs, identifiers, and return types when implementing or extending currently untyped methods. - Handle missing records consistently in `findOne`, `update`, and `remove`, typically by throwing an appropriate NestJS HTTP exception. - Update dependent modules, controllers, and tests when changing method signatures or database integration behavior. ## Referenced By - `DatabaseController` (DEPENDS_ON) - `DatabaseModule` (MODULE_PROVIDES) # ENHANCER_KEY_TO_SUBTYPE_MAP **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L26) ## 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 ``` # 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) `ExpressAdapter` connects the framework’s platform-agnostic HTTP operations to an Express application and its request/response objects. It provides response helpers, lifecycle hooks, rendering and redirect support, plus centralized error and not-found handler integration. **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 --> Hooks[Request / Response Hooks] Adapter --> Handlers[Route Handlers] Handlers --> ResponseMethods[reply / status / render / redirect / end] ResponseMethods --> ExpressResponse[Express Response] Express --> ErrorHandlers[Error and Not Found Handlers] ``` ## Usage ```ts import express from 'express'; import { ExpressAdapter } from '@nestjs/platform-express'; const app = express(); const adapter = new ExpressAdapter(app); app.get('/health', (_req, res) => { adapter.reply(res, { status: 'ok' }, 200); }); app.get('/redirect', (_req, res) => { adapter.redirect(res, 302, '/health'); }); app.get('/empty', (_req, res) => { adapter.status(res, 204); adapter.end(res); }); app.listen(3000, () => { console.log('Listening on http://localhost:3000'); }); ``` ## AI Coding Instructions - Use adapter response methods such as `reply()`, `status()`, `redirect()`, and `end()` instead of coupling shared platform code directly to Express response APIs. - Check `isHeadersSent()` before attempting to write an error response or send additional content. - Register request/response hooks early during application setup with `setOnRequestHook()` and `setOnResponseHook()`. - Configure `setErrorHandler()` and `setNotFoundHandler()` centrally so unhandled errors and missing routes produce consistent responses. - Keep Express-specific request and response handling inside this adapter boundary; avoid leaking Express types into platform-independent application logic. # 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) `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. # MiddlewareController **Kind:** Controller **Source:** [`integration/versioning/src/middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/middleware.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ MiddlewareController client->>+p1: MiddlewareController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `hello` - MODULE_DECLARES β†’ `hellov2` ## Referenced By - `AppModule` (MODULE_DECLARES) # 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) # OwnersModule **Kind:** Module **Source:** [`sample/12-graphql-schema-first/src/owners/owners.module.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/owners/owners.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `OwnersService` - MODULE_EXPORTS β†’ `OwnersService` ## Referenced By - `CatsModule` (MODULE_IMPORTS) # Transport **Kind:** Enum **Source:** [`packages/microservices/enums/transport.enum.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/enums/transport.enum.ts#L1) ## Values - `TCP` - `REDIS` - `NATS` - `MQTT` - `GRPC` - `RMQ` - `KAFKA` # UpdatePost **Kind:** Graphql Type **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) `UpdatePost` is a GraphQL input type used to provide editable fields when updating an existing post. The `id` field identifies the target post, while `title`, `text`, and `isPublished` are optional so clients can update only the values that changed. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[updatePost Mutation] Mutation --> Input[UpdatePost Input] Input --> ID[id: ID!] Input --> Title[title: String] Input --> Text[text: String] Input --> Published[isPublished: Boolean] Mutation --> Resolver[Post Resolver] Resolver --> Database[(Post Database)] ``` ## Usage ```ts import { gql } from '@apollo/client' const UPDATE_POST = gql` mutation UpdatePost($input: UpdatePost!) { updatePost(data: $input) { id title text isPublished } } ` await client.mutate({ mutation: UPDATE_POST, variables: { input: { id: 'post_123', title: 'Updated post title', isPublished: true, }, }, }) ``` ## AI Coding Instructions - Always provide a valid `id`; it is required to identify the post being updated. - Treat `title`, `text`, and `isPublished` as partial-update fields and omit values that should remain unchanged. - Ensure the mutation resolver validates that the post exists before applying updates. - Keep GraphQL field names aligned with the Prisma post model and resolver input mapping. - Return the updated post from the mutation so clients can refresh local cache state. ## Referenced By - `updatePost` (TYPE_OF) # AclPermissionTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L312) ## Values - `UNKNOWN` - `ANY` - `DENY` - `ALLOW` # createBusiness **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L152) ## Endpoint `POST /business` ## Referenced By - `KafkaController` (MODULE_DECLARES) # DogsService **Kind:** Service **Source:** [`integration/inspector/src/dogs/dogs.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.service.ts#L5) `DogsService` encapsulates the backend business logic for managing dog records in the inspector integration. It provides the standard CRUD-style operationsβ€”creating, listing, retrieving, updating, and removing dogsβ€”for use by controllers or other NestJS providers. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createDogDto: CreateDogDto)` | `unknown` | | `findAll` | `findAll()` | `unknown` | | `findOne` | `findOne(id: number)` | `unknown` | | `update` | `update(id: number, updateDogDto: UpdateDogDto)` | `unknown` | | `remove` | `remove(id: number)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant DogsController participant DogsService participant DataStore Client->>DogsController: Request dog operation DogsController->>DogsService: create/findAll/findOne/update/remove DogsService->>DataStore: Read or modify dog data DataStore-->>DogsService: Result DogsService-->>DogsController: Return result DogsController-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { DogsService } from './dogs/dogs.service'; @Injectable() export class DogImportService { constructor(private readonly dogsService: DogsService) {} async importDog() { const createdDog = await this.dogsService.create({ name: 'Milo', breed: 'Labrador Retriever', }); const dogs = await this.dogsService.findAll(); return { createdDog, totalDogs: dogs.length, }; } } ``` ## AI Coding Instructions - Keep dog-related business logic in `DogsService`; controllers should focus on request parsing and HTTP responses. - Follow the existing CRUD method structure: use `create`, `findAll`, `findOne`, `update`, and `remove` consistently. - Define explicit DTO and return types when implementing methods currently typed as `unknown`. - Handle missing records in `findOne`, `update`, and `remove` with appropriate NestJS exceptions, such as `NotFoundException`. - Update dependent controllers, modules, and tests when changing service method signatures or persistence behavior. ## Referenced By - `DogsController` (DEPENDS_ON) - `DogsModule` (MODULE_PROVIDES) # 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) ## 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 | Ht… ``` # 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) `FastifyAdapter` bridges the application’s HTTP abstraction to a Fastify server instance. It configures request and response lifecycle hooks, initializes Fastify, registers route handlers, and starts the HTTP listener. **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[onRequest / onResponse Hooks] Adapter --> Routes[GET / POST / HEAD / DELETE Routes] Adapter --> Fastify[Fastify Server] Fastify --> Client[HTTP Client] ``` ## 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'); }); adapter.setOnResponseHook(async (request, reply) => { request.log.info( { statusCode: reply.statusCode }, 'Response completed', ); }); adapter.get('/health', async () => { return { status: 'ok' }; }); adapter.post('/users', async (request, reply) => { const user = request.body; return reply.code(201).send({ id: 'user_123', ...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 route helpers (`get`, `post`, `head`, and `delete`) rather than registering routes directly when working within the platform abstraction. - Preserve Fastify request/reply semantics in handlers; return response payloads or explicitly send responses through `reply`. - Ensure `init()` completes before the server begins accepting traffic, especially when hooks or routes depend on asynchronous setup. - Treat `listen()` overloads consistently and pass the appropriate port, host, or listen options for the deployment environment. # 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) `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. # MODULE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L1) ## Definition ```ts { IMPORTS: 'imports', PROVIDERS: 'providers', CONTROLLERS: 'controllers', EXPORTS: 'exports', } ``` ## Value ```ts { IMPORTS: 'imports', PROVIDERS: 'providers', CONTROLLERS: 'controllers', EXPORTS: 'exports', } ``` # MultipleMiddlewareVersionController **Kind:** Controller **Source:** [`integration/versioning/src/multiple-middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/multiple-middleware.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ MultipleMiddlewareVersionController client->>+p1: MultipleMiddlewareVersionController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `multiple` ## Referenced By - `AppModule` (MODULE_DECLARES) # Mutation **Kind:** Graphql Type **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - CALLS_API β†’ `addRecipe` - CALLS_API β†’ `removeRecipe` # PrismaModule **Kind:** Module **Source:** [`sample/22-graphql-prisma/src/prisma/prisma.module.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/prisma/prisma.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `PrismaService` - MODULE_EXPORTS β†’ `PrismaService` ## Referenced By - `PostsModule` (MODULE_IMPORTS) # 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) `RmqOptions` configures a NestJS microservice or client that uses the RabbitMQ (`Transport.RMQ`) transport. It defines connection endpoints, queue and exchange behavior, message acknowledgement settings, serialization, and producer/consumer-specific options such as reply queues and connection retry limits. ## Properties | Property | Type | |---|---| | `transport` | `Transport.RMQ` | | `options` | `{ /** * An array of connection URLs to try in order. */ urls?: string[] | RmqUrl[]; /** * The name of the queue. */ queue?: string; /** * A prefetch count for this channel. The count given is the maximum number of messages sent over the channel that can be awaiting acknowledgement; * once there are count messages outstanding, the server will not send more messages on this channel until one or more have been acknowledged. */ prefetchCount?: number; /** * Sets the per-channel behavior for prefetching messages. */ isGlobalPrefetchCount?: boolean; /** * Amqplib queue options. * @see https://amqp-node.github.io/amqplib/channel_api.html#channel_assertQueue */ queueOptions?: AmqplibQueueOptions; /** * AMQP Connection Manager socket options. */ socketOptions?: AmqpConnectionManagerSocketOptions; /** * If true, the broker won’t expect an acknowledgement of messages delivered to this consumer; i.e., it will dequeue messages as soon as they’ve been sent down the wire. * @default false */ noAck?: boolean; /** * A name which the server will use to distinguish message deliveries for the consumer; mustn’t be already in use on the channel. It’s usually easier to omit this, in which case the server will create a random name and supply it in the reply. */ consumerTag?: string; /** * A serializer for the message payload. */ serializer?: Serializer; /** * A deserializer for the message payload. */ deserializer?: Deserializer; /** * A reply queue for the producer. * @default 'amq.rabbitmq.reply-to' */ replyQueue?: string; /** * If truthy, the message will survive broker restarts provided it’s in a queue that also survives restarts. */ persistent?: boolean; /** * Additional headers to be sent with every message. * Applies only to the producer configuration. */ headers?: Record; /** * When false, a queue will not be asserted before consuming. * @default false */ noAssert?: boolean; /** * Name for the exchange. Defaults to the queue name when "wildcards" is set to true. * @default '' */ exchange?: string; /** * Type of the exchange. * Accepts the AMQP standard types ('direct', 'fanout', 'topic', 'headers') or any custom exchange type name provided as a string literal. * @default 'topic' */ exchangeType?: 'direct' | 'fanout' | 'topic' | 'headers' | (string & {}); /** * Exchange arguments */ exchangeArguments?: Record; /** * Additional routing key for the topic exchange. */ routingKey?: string; /** * Set to true only if you want to use Topic Exchange for routing messages to queues. * Enabling this will allow you to use wildcards (*, #) as message and event patterns. * @see https://www.rabbitmq.com/tutorials/tutorial-five-python#topic-exchange * @default false */ wildcards?: boolean; /** * Maximum number of connection attempts. * Applies only to the consumer configuration. * -1 === infinite * @default -1 */ maxConnectionAttempts?: number; }` | ## Diagram ```mermaid graph LR App[NestJS Application] --> Config[RmqOptions] Config --> Transport[Transport.RMQ] Config --> Connection[urls + socketOptions] Config --> Queue[queue + queueOptions] Config --> Consumer[prefetchCount + noAck + consumerTag] Config --> Producer[replyQueue + persistent + headers] Config --> Routing[wildcards + exchange + exchangeType + routingKey] Connection --> RabbitMQ[RabbitMQ Broker] Queue --> RabbitMQ Routing --> RabbitMQ ``` ## Usage ```ts import { Transport, type RmqOptions } from '@nestjs/microservices'; const rmqOptions: RmqOptions = { transport: Transport.RMQ, options: { urls: ['amqp://guest:guest@localhost:5672'], queue: 'orders', queueOptions: { durable: true, }, prefetchCount: 10, noAck: false, // Enable topic-exchange routing when message patterns use * or #. wildcards: true, exchange: 'orders.exchange', exchangeType: 'topic', routingKey: 'orders.created', persistent: true, headers: { 'x-service-name': 'orders-service', }, maxConnectionAttempts: -1, }, }; // Example: NestFactory.createMicroservice(AppModule, rmqOptions); ``` ## AI Coding Instructions - Always set `transport: Transport.RMQ`; RabbitMQ-specific settings belong under `options`. - Configure `queueOptions.durable: true` and `persistent: true` when messages and queues must survive broker restarts. - Keep `noAck` disabled for reliable processing, and set `prefetchCount` to limit unacknowledged messages per consumer channel. - Enable `wildcards` only when using topic-exchange pattern routing; configure a compatible `exchange`, `exchangeType`, and optional `routingKey`. - Use `maxConnectionAttempts` for consumer reconnection behavior; `-1` retries indefinitely. # ChatModule **Kind:** Module **Source:** [`integration/inspector/src/chat/chat.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/chat/chat.module.ts#L5) ## Relationships - MODULE_PROVIDES β†’ `ChatGateway` - MODULE_PROVIDES β†’ `ChatService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # CompressionTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1129) ## Values - `None` - `GZIP` - `Snappy` - `LZ4` - `ZSTD` # 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) Configurable module host. See properties for more details `ConfigurableModuleHost` describes the artifacts produced by NestJS's `ConfigurableModuleBuilder`. It groups the generated configurable module class, dependency-injection token, and type helpers used to implement synchronous and asynchronous module registration APIs. Use it when building reusable modules that expose strongly typed configuration methods such as `register()` or `registerAsync()`. ## 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 / registerAsync] Token --> Injection[Inject module options] ``` ## Usage ```ts import { ConfigurableModuleBuilder, Inject, Injectable, Module, type ConfigurableModuleHost, } from '@nestjs/common'; interface FeatureModuleOptions { endpoint: string; timeout?: number; } const featureModuleHost: ConfigurableModuleHost = new ConfigurableModuleBuilder() .setClassMethodName('forRoot') .build(); export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE, } = featureModuleHost; @Injectable() export class FeatureService { constructor( @Inject(MODULE_OPTIONS_TOKEN) private readonly options: FeatureModuleOptions, ) {} getEndpoint() { return this.options.endpoint; } } @Module({ providers: [FeatureService], exports: [FeatureService], }) export class FeatureModule extends ConfigurableModuleClass {} // AppModule imports: // FeatureModule.forRoot({ endpoint: 'https://api.example.com', timeout: 5000 }); ``` ## AI Coding Instructions - Create configurable modules through `ConfigurableModuleBuilder` and treat its `build()` result as a `ConfigurableModuleHost`. - Export `ConfigurableModuleClass` and extend it with the module class so generated registration methods remain available. - Inject configuration using `MODULE_OPTIONS_TOKEN`; do not create a separate token for the same module options. - Use `typeof OPTIONS_TYPE` and `typeof ASYNC_OPTIONS_TYPE` when declaring custom registration method signatures or wrapper APIs. - Keep module option interfaces focused on consumer-provided configuration, and use extra module-definition options only for module metadata customization. # ConsumerEvents **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L910) ## 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… ``` # createUser **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L137) ## Endpoint `POST /user` ## Referenced By - `KafkaController` (MODULE_DECLARES) # ExternalSvcService **Kind:** Service **Source:** [`integration/inspector/src/external-svc/external-svc.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/external-svc/external-svc.service.ts#L5) `ExternalSvcService` is a NestJS service responsible for managing external service records within the Inspector integration. It provides the standard create, read, update, and delete operation surface used by controllers or other backend services. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createExternalSvcDto: CreateExternalSvcDto)` | `unknown` | | `findAll` | `findAll()` | `unknown` | | `findOne` | `findOne(id: number)` | `unknown` | | `update` | `update(id: number, updateExternalSvcDto: UpdateExternalSvcDto)` | `unknown` | | `remove` | `remove(id: number)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant ExternalSvcService participant Repository Client->>Controller: HTTP request Controller->>ExternalSvcService: create/findAll/findOne/update/remove ExternalSvcService->>Repository: Perform data operation Repository-->>ExternalSvcService: Return result ExternalSvcService-->>Controller: Return service response Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ExternalSvcService } from './external-svc.service'; @Injectable() export class ExternalSvcConsumer { constructor(private readonly externalSvcService: ExternalSvcService) {} async listExternalServices() { return this.externalSvcService.findAll(); } async getExternalService(id: string) { return this.externalSvcService.findOne(); } async createExternalService() { return this.externalSvcService.create(); } async updateExternalService(id: string) { return this.externalSvcService.update(); } async deleteExternalService(id: string) { return this.externalSvcService.remove(); } } ``` ## AI Coding Instructions - Keep business logic inside `ExternalSvcService`; controllers should delegate request handling to service methods. - Follow the existing CRUD method contract when implementing `create`, `findAll`, `findOne`, `update`, and `remove`. - Add DTO validation and explicit return types before exposing service methods through API controllers. - Ensure `findOne`, `update`, and `remove` handle missing records consistently, typically with NestJS `NotFoundException`. - Integrate persistence or external-client dependencies through NestJS dependency injection rather than creating them directly in methods. ## Referenced By - `ExternalSvcController` (DEPENDS_ON) - `ExternalSvcModule` (MODULE_PROVIDES) # 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) `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. # Injector **Kind:** Class **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L93) `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`. # MultipleVersionController **Kind:** Controller **Source:** [`integration/versioning/src/multiple.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/multiple.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ MultipleVersionController client->>+p1: MultipleVersionController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `multiple` ## Referenced By - `AppModule` (MODULE_DECLARES) # Mutation **Kind:** Graphql Type **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - CALLS_API β†’ `createCat` # 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) ## Definition ```ts GraphInspector ``` ## Value ```ts new Proxy( GraphInspector.prototype, { get: () => noop, }, ) ``` # ConfigResourceTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L295) ## Values - `UNKNOWN` - `TOPIC` - `BROKER` - `BROKER_LOGGER` # 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) ## 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: [] }, } ``` # EagerModule **Kind:** Module **Source:** [`integration/lazy-modules/src/eager.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/eager.module.ts#L15) ## Relationships - MODULE_PROVIDES β†’ `EagerService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # exec **Kind:** API Endpoint **Source:** [`integration/lazy-modules/src/lazy.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/lazy.controller.ts#L8) ## Endpoint `GET /lazy/transient` ## Referenced By - `LazyController` (MODULE_DECLARES) # HelloRequestService **Kind:** Service **Source:** [`integration/scopes/src/inject-inquirer/hello-request/hello-request.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello-request/hello-request.service.ts#L5) `HelloRequestService` is a NestJS service responsible for producing greeting and farewell responses within the request-scoped injection example. It demonstrates how a service can participate in Nest's dependency-injection lifecycle while exposing simple request-related operations to consumers such as controllers or other services. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `unknown` | | `farewell` | `farewell()` | `unknown` | ## Dependencies - `RequestLogger` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant HelloRequestService Client->>Controller: Send hello-related request Controller->>HelloRequestService: greeting() or farewell() HelloRequestService-->>Controller: Return response Controller-->>Client: Send HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { HelloRequestService } from './hello-request.service'; @Controller('hello') export class HelloController { constructor( private readonly helloRequestService: HelloRequestService, ) {} @Get('greeting') greeting() { return this.helloRequestService.greeting(); } @Get('farewell') farewell() { return this.helloRequestService.farewell(); } } ``` ## AI Coding Instructions - Inject `HelloRequestService` through the constructor rather than creating it with `new`. - Use `greeting()` and `farewell()` as the public interface for hello-related responses; keep controller logic thin. - Ensure the service is registered in the appropriate NestJS module's `providers` array. - Preserve request-scope behavior and avoid storing cross-request mutable state in the service. - Update consumers and tests when changing the return values or contracts of `greeting()` or `farewell()`. ## Relationships - DEPENDS_ON β†’ `RequestLogger` ## Referenced By - `HelloController` (DEPENDS_ON) - `HelloModule` (MODULE_PROVIDES) # 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) 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. # InstanceWrapper **Kind:** Class **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L66) `InstanceWrapper` is the internal container record used by the injector to describe and manage a provider, controller, or injectable instance. It stores instance state per dependency-injection context and inquirer, while also tracking constructor and property dependency metadata needed 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] --> Wrapper[InstanceWrapper] Wrapper --> Static[Static Context Instance] Wrapper --> ContextInstances[Instances by Context ID] ContextInstances --> InquirerInstances[Instances by Inquirer ID] Wrapper --> CtorMetadata[Constructor Dependency Metadata] Wrapper --> PropertyMetadata[Property Dependency Metadata] CtorMetadata --> Resolver[Dependency Resolver] PropertyMetadata --> Resolver ``` ## Usage ```ts import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; import { STATIC_CONTEXT } from '@nestjs/core/injector/constants'; class DatabaseService { connect() { return 'connected'; } } const wrapper = new InstanceWrapper({ token: DatabaseService, name: DatabaseService.name, metatype: DatabaseService, instance: new DatabaseService(), isResolved: true, }); // Store and retrieve an instance for a DI context wrapper.setInstanceByContextId(STATIC_CONTEXT, { instance: new DatabaseService(), isResolved: true, }); const host = wrapper.getInstanceByContextId(STATIC_CONTEXT); console.log(host.instance?.connect()); // "connected" // Register metadata used by the injector during dependency resolution wrapper.addCtorMetadata(0, anotherDependencyWrapper); wrapper.addPropertiesMetadata('logger', loggerWrapper); const constructorDependencies = wrapper.getCtorMetadata(); const propertyDependencies = wrapper.getPropertiesMetadata(); ``` ## AI Coding Instructions - Treat `InstanceWrapper` as injector infrastructure; prefer using higher-level Nest container APIs unless modifying dependency-resolution internals. - Use `getInstanceByContextId()` and `setInstanceByContextId()` for request-scoped or transient provider state instead of mutating instance maps directly. - Preserve the relationship between context IDs and inquirer IDs when resolving transient providers; transient instances may differ per consumer. - Register constructor metadata by parameter index and property metadata by property key so dependency resolution preserves declaration order. - Remove context or inquirer instances when their lifecycle ends to avoid retaining request-scoped objects unnecessarily. # Mutation **Kind:** Graphql Type **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - CALLS_API β†’ `createCat` # NestedTransientController **Kind:** Controller **Source:** [`integration/scopes/src/nested-transient/nested-transient.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/nested-transient.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ NestedTransientController participant p2 as βš™οΈ FirstRequestService participant p3 as βš™οΈ TransientLoggerService participant p4 as βš™οΈ NestedTransientService participant p5 as βš™οΈ SecondRequestService client->>+p1: NestedTransientController p1->>+p2: FirstRequestService p2->>+p3: TransientLoggerService p3->>+p4: NestedTransientService p4-->-p3: return p3-->-p2: return p2-->-p1: return p1->>+p5: SecondRequestService p5-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getIsolationData` - DEPENDS_ON β†’ `FirstRequestService` - DEPENDS_ON β†’ `SecondRequestService` ## Referenced By - `NestedTransientModule` (MODULE_DECLARES) # ReplFnDefinition **Kind:** Type **Source:** [`packages/core/repl/repl.interfaces.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl.interfaces.ts#L4) ## Definition ```ts { /** Function's name. Note that this should be a valid JavaScript function name. */ name: string; /** Alternative names to the function. */ aliases?: ReplFnDefinition['name'][]; /** Function's description to display when `.help` is entered. */ description: string; /** … ``` # 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) ## 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'` | # 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) Defines HTTP route param decorator `createParamDecorator` creates custom parameter decorators for controller route handlers. It stores extraction metadata that Nest uses at request time to resolve a value from the current `ExecutionContext` and inject it into the decorated method parameter. ## 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[Incoming HTTP request] --> B[Controller route handler] B --> C[Custom parameter decorator] C --> D[createParamDecorator factory] D --> E[ExecutionContext] E --> F[Extract request-specific value] F --> G[Inject value into handler parameter] ``` ## Usage ```ts import { Controller, createParamDecorator, ExecutionContext, Get, } from '@nestjs/common'; export const CurrentUser = createParamDecorator( (data: keyof User | undefined, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); const user = request.user as User; return data ? user?.[data] : user; }, ); interface User { id: string; email: string; } @Controller('profile') export class ProfileController { @Get() getProfile(@CurrentUser() user: User) { return user; } @Get('id') getUserId(@CurrentUser('id') userId: string) { return { userId }; } } ``` ## AI Coding Instructions - Define the decorator factory to accept optional `data` and an `ExecutionContext`; use `data` to support configurable extraction behavior. - Retrieve HTTP request data through `ctx.switchToHttp().getRequest()` rather than relying on global request state. - Keep extraction logic small and reusable; move complex authorization or database lookups into guards, interceptors, or services. - Ensure middleware or authentication guards populate expected request properties, such as `request.user`, before the controller handler runs. - Type the returned value and optional data argument where possible so decorated controller parameters remain type-safe. # 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) ## 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, } ``` # execRequestScope **Kind:** API Endpoint **Source:** [`integration/lazy-modules/src/lazy.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/lazy.controller.ts#L18) ## Endpoint `GET /lazy/request` ## Referenced By - `LazyController` (MODULE_DECLARES) # ExportsModule **Kind:** Module **Source:** [`integration/injector/src/exports/exports.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/exports/exports.module.ts#L4) ## Relationships - MODULE_EXPORTS β†’ `ExportsService` ## Referenced By - `ApplicationModule` (MODULE_IMPORTS) # KafkaStatus **Kind:** Enum **Source:** [`packages/microservices/events/kafka.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/kafka.events.ts#L1) ## Values - `DISCONNECTED` - `CONNECTED` - `CRASHED` - `STOPPED` - `REBALANCING` # Module **Kind:** Class **Source:** [`packages/core/injector/module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/module.ts#L44) `Module` is the internal NestJS container representation of a module definition. It owns provider, injectable, controller, export, and import metadata for a module, while registering core dependencies such as `ModuleRef` and `ApplicationConfig`. ## 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 metatype] --> B[Module instance] B --> C[Core providers] C --> C1[ModuleRef] C --> C2[ApplicationConfig] C --> C3[Module class provider] B --> D[addProvider] B --> E[addInjectable] D --> F[Class provider] D --> G[Custom provider] G --> G1[useValue] G --> G2[useFactory] G --> G3[useClass] G --> G4[useExisting] F --> H[Provider registry] G1 --> H G2 --> H G3 --> H G4 --> H E --> I[Injectable registry] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { Module as InternalModule } from '@nestjs/core/injector/module'; import { NestContainer } from '@nestjs/core/injector/container'; @Injectable() class AppService { getMessage() { return 'Hello from the container'; } } class AppModule {} // Typically created by Nest's scanner/container during bootstrap. function registerModuleProviders(container: NestContainer) { const moduleRef = new InternalModule(AppModule, container); // Register a class-based provider. moduleRef.addProvider(AppService); // Register a custom value provider. moduleRef.addProvider({ provide: 'APP_NAME', useValue: 'example-api', }); // Register an injectable used by framework features such as guards or pipes. moduleRef.addInjectable(AppService); return moduleRef; } ``` ## AI Coding Instructions - Treat `Module` as a container-internal type; application code should normally use the `@Module()` decorator rather than instantiate it directly. - Use `addProvider()` for both class providers and custom providers; custom providers must include a valid `provide` token. - Preserve provider tokens when extending registration logic, since tokens are the keys used for dependency resolution. - Keep core providers such as `ModuleRef`, the module metatype, and `ApplicationConfig` registered during module initialization. - Register framework enhancers through `addInjectable()` so they are tracked separately from ordinary providers. # Mutation **Kind:** Graphql Type **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - CALLS_API β†’ `createPost` - CALLS_API β†’ `updatePost` - CALLS_API β†’ `deletePost` # NestedTransientService **Kind:** Service **Source:** [`integration/scopes/src/nested-transient/nested-transient.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/nested-transient.service.ts#L3) `NestedTransientService` is a NestJS service used to store and retrieve context within a nested transient dependency scope. It provides a simple `setContext()` / `getContext()` interface so collaborating services can access context associated with the current transient instance. ## Methods | Method | Signature | Returns | |---|---|---| | `setContext` | `setContext(ctx: string)` | `unknown` | | `getContext` | `getContext()` | `string | undefined` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Calling Service participant Nested as NestedTransientService Consumer->>Nested: setContext(context) Note over Nested: Store context on this transient instance Consumer->>Nested: getContext() Nested-->>Consumer: context | undefined ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { NestedTransientService } from './nested-transient.service'; @Injectable() export class RequestHandlerService { constructor( private readonly nestedTransientService: NestedTransientService, ) {} handle(context: string): string | undefined { this.nestedTransientService.setContext(context); return this.nestedTransientService.getContext(); } } ``` ## AI Coding Instructions - Treat `NestedTransientService` as transient-scoped state; do not rely on its context being shared across unrelated instances. - Call `setContext()` before reading the value with `getContext()`, since `getContext()` may return `undefined`. - Keep stored context lightweight and scoped to the current operation or dependency chain. - When injecting this service, verify the consuming provider's NestJS scope is compatible with transient dependencies. ## Referenced By - `NestedTransientModule` (MODULE_PROVIDES) - `TransientLoggerService` (DEPENDS_ON) # OrdersController **Kind:** Controller **Source:** [`sample/30-event-emitter/src/orders/orders.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/orders.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ OrdersController participant p2 as βš™οΈ OrdersService client->>+p1: OrdersController p1->>+p2: OrdersService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - DEPENDS_ON β†’ `OrdersService` ## Referenced By - `OrdersModule` (MODULE_DECLARES) # RequestEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L408) ## 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; }> ``` # 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) 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. # Batch **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L887) ## Definition ```ts { topic: string; partition: number; highWatermark: string; messages: KafkaMessage[]; isEmpty(): boolean; firstOffset(): string | null; lastOffset(): string; offsetLag(): string; offsetLagLow(): string; } ``` # 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) ## Signature ```ts function FileFieldsInterceptor(uploadFields: MulterField[], localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `uploadFields` | `MulterField[]` | | `localOptions` | `MulterOptions` | **Returns:** `Type` # findOne **Kind:** API Endpoint **Source:** [`sample/21-serializer/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/app.controller.ts#L13) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) ## Definition ```ts Provider ``` ## Value ```ts { provide: INQUIRER, scope: Scope.TRANSIENT, useFactory: noop, } ``` # logLevel **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L618) ## Values - `NOTHING` - `ERROR` - `WARN` - `INFO` - `DEBUG` # Mutation **Kind:** Graphql Type **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - CALLS_API β†’ `addRecipe` - CALLS_API β†’ `removeRecipe` # MyWebhookModule **Kind:** Module **Source:** [`integration/discovery/src/my-webhook/my-webhook.module.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/my-webhook/my-webhook.module.ts#L5) ## Relationships - MODULE_PROVIDES β†’ `CleanupWebhook` - MODULE_PROVIDES β†’ `FlushWebhook` ## Referenced By - `AppModule` (MODULE_IMPORTS) # NestApplication **Kind:** Class **Source:** [`packages/core/nest-application.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-application.ts#L54) `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. # OverrideController **Kind:** Controller **Source:** [`integration/versioning/src/override.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/override.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ OverrideController client->>+p1: OverrideController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `overrideV1` - MODULE_DECLARES β†’ `overrideV2` ## Referenced By - `AppModule` (MODULE_DECLARES) # RequestLogger **Kind:** Service **Source:** [`integration/scopes/src/inject-inquirer/hello-request/request-logger.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello-request/request-logger.service.ts#L4) `RequestLogger` is a NestJS service responsible for logging activity within the `hello-request` request flow. It can be injected into controllers or other providers to centralize request-related logging behavior and keep logging concerns separate from business logic. ## Methods | Method | Signature | Returns | |---|---|---| | `log` | `log(message: string)` | `unknown` | ## Dependencies - `Logger` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant RequestLogger participant Logger as Logging Output Client->>Controller: Send request Controller->>RequestLogger: log() RequestLogger->>Logger: Write request log entry Controller-->>Client: Return response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { RequestLogger } from './request-logger.service'; @Controller('hello-request') export class HelloRequestController { constructor(private readonly requestLogger: RequestLogger) {} @Get() getHello(): string { this.requestLogger.log(); return 'Hello, request!'; } } ``` ## AI Coding Instructions - Inject `RequestLogger` through NestJS constructor injection; do not instantiate it with `new`. - Call `log()` at request-flow boundaries, such as controller handlers or orchestration services. - Keep request logging concerns inside this service rather than duplicating logging code across controllers. - Ensure `RequestLogger` is registered in the appropriate NestJS module `providers` array before injecting it. - Preserve the existing `log(): unknown` contract unless all consumers are updated together. ## Relationships - DEPENDS_ON β†’ `Logger` ## Referenced By - `HelloRequestService` (DEPENDS_ON) - `HelloModule` (MODULE_PROVIDES) # 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) Options passed to validator during validation. `ValidatorOptions` configures how validation is performed when validating objects and DTOs. It controls property filtering, validation groups, message output, and how `null`, `undefined`, or missing values are handled during the validation process. ## Properties | Property | Type | |---|---| | `enableDebugMessages` | `boolean` | | `skipUndefinedProperties` | `boolean` | | `skipNullProperties` | `boolean` | | `skipMissingProperties` | `boolean` | | `whitelist` | `boolean` | | `forbidNonWhitelisted` | `boolean` | | `groups` | `string[]` | | `always` | `boolean` | | `strictGroups` | `boolean` | | `dismissDefaultMessages` | `boolean` | | `validationError` | `{ /** * Indicates if target should be exposed in ValidationError. */ target?: boolean; /** * Indicates if validated value should be exposed in ValidationError. */ 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[Error Messages] B --> F[Whitelist Rules] 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 '@nestjs/common'; const validatorOptions: ValidatorOptions = { whitelist: true, forbidNonWhitelisted: true, skipMissingProperties: true, skipUndefinedProperties: true, groups: ['update'], strictGroups: true, dismissDefaultMessages: false, }; async function validateUpdatePayload(payload: unknown) { // Pass these options to the validation layer used by your application. return validate(payload, validatorOptions); } ``` ## AI Coding Instructions - Enable `whitelist` when DTOs should reject or remove properties that have no validation decorators. - Use `forbidNonWhitelisted` together with `whitelist` when unexpected input should produce validation errors instead of being silently stripped. - Use `skipMissingProperties` for partial update flows; do not use it for required create payloads unless missing fields are intentionally allowed. - Configure `groups`, `always`, and `strictGroups` consistently with the validation decorators defined on DTO properties. - Avoid enabling `enableDebugMessages` in production if validation details could expose internal implementation information. # 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) 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. # 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) ## Signature ```ts function FileInterceptor(fieldName: string, localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `fieldName` | `string` | | `localOptions` | `MulterOptions` | **Returns:** `Type` # findOne **Kind:** API Endpoint **Source:** [`sample/11-swagger/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/cats.controller.ts#L25) ## Endpoint `GET /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # MqttEvents **Kind:** Type **Source:** [`packages/microservices/events/mqtt.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/mqtt.events.ts#L29) 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. # MqttStatus **Kind:** Enum **Source:** [`packages/microservices/events/mqtt.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/mqtt.events.ts#L5) ## Values - `DISCONNECTED` - `RECONNECTING` - `CONNECTED` - `CLOSED` # Mutation **Kind:** Graphql Type **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - CALLS_API β†’ `addRecipe` - CALLS_API β†’ `removeRecipe` # NestApplicationContext **Kind:** Class **Source:** [`packages/core/nest-application-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-application-context.ts#L40) `NestApplicationContext` provides a standalone Nest dependency-injection container without creating an HTTP server. It is used by application contexts created through `NestFactory.createApplicationContext()` to retrieve singleton providers, resolve scoped or transient providers, and narrow lookups to a selected module. **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 2 places: it logs it and continues in all 2. ## Diagram ```mermaid graph LR A[NestFactory.createApplicationContext] --> B[NestApplicationContext] B --> C[Root Module] C --> D[Module Container] D --> E[Singleton Providers] D --> F[Request-scoped Providers] D --> G[Transient Providers] B --> H[get()] B --> I[resolve()] B --> J[select()] H --> E I --> F I --> G J --> K[Selected Module Context] ``` ## Usage ```ts import { Injectable, Module } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; @Injectable() class ReportService { generate() { return 'Report generated'; } } @Module({ providers: [ReportService], }) class AppModule {} async function bootstrap() { const app = await NestFactory.createApplicationContext(AppModule); // Retrieve a singleton provider from the application context. const reports = app.get(ReportService); console.log(reports.generate()); // Limit provider lookup to a specific module when needed. const moduleContext = app.select(AppModule); const selectedReports = moduleContext.get(ReportService, { strict: true }); console.log(selectedReports.generate()); await app.close(); } bootstrap(); ``` ## AI Coding Instructions - Create this context through `NestFactory.createApplicationContext()` rather than instantiating `NestApplicationContext` directly. - Use `get()` for singleton/static providers; use `resolve()` for request-scoped or transient providers that require a new DI context. - Use `select(Module)` with `get(..., { strict: true })` when provider lookup must be restricted to a specific module. - Prefer injection tokens when resolving interface-based or dynamically configured providers. - Always close standalone application contexts with `await app.close()` to release lifecycle-managed resources. # OverridePartialController **Kind:** Controller **Source:** [`integration/versioning/src/override-partial.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/override-partial.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ OverridePartialController client->>+p1: OverridePartialController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `overridePartialV1` - MODULE_DECLARES β†’ `overridePartialV2` ## Referenced By - `AppModule` (MODULE_DECLARES) # 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) ## Definition ```ts Provider ``` ## Value ```ts { provide: REQUEST, scope: Scope.REQUEST, useFactory: noop, } ``` # TasksModule **Kind:** Module **Source:** [`sample/27-scheduling/src/tasks/tasks.module.ts`](https://github.com/nestjs/nest/blob/master/sample/27-scheduling/src/tasks/tasks.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `TasksService` ## Referenced By - `AppModule` (MODULE_IMPORTS) # TransientLogger **Kind:** Service **Source:** [`integration/scopes/src/inject-inquirer/hello-transient/transient-logger.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello-transient/transient-logger.service.ts#L4) `TransientLogger` is a NestJS service used in the `hello-transient` integration scope to record log activity for transiently created dependencies. Its `log()` method provides the service’s logging behavior and helps validate dependency injection behavior when a new instance is resolved per request or consumer. ## Methods | Method | Signature | Returns | |---|---|---| | `log` | `log(message: string)` | `unknown` | ## Dependencies - `Logger` ## Diagram ```mermaid sequenceDiagram participant Consumer as Injecting Service/Controller participant DI as NestJS DI Container participant Logger as TransientLogger Consumer->>DI: Resolve TransientLogger DI-->>Consumer: New transient instance Consumer->>Logger: log() Logger-->>Consumer: Logging completed ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { TransientLogger } from './transient-logger.service'; @Injectable() export class HelloService { constructor(private readonly transientLogger: TransientLogger) {} handleHello(): void { this.transientLogger.log(); } } ``` ## AI Coding Instructions - Preserve the service’s transient lifecycle configuration; this service is intended to support per-consumer or per-resolution instances. - Inject `TransientLogger` through NestJS dependency injection instead of creating it manually with `new`. - Keep `log()` focused on logging-related behavior and avoid adding request-handling or business logic to this service. - When testing, resolve or inject the service through a Nest testing module to verify its configured scope correctly. ## Relationships - DEPENDS_ON β†’ `Logger` ## Referenced By - `HelloTransientService` (DEPENDS_ON) - `HelloModule` (MODULE_PROVIDES) # ApplicationModule **Kind:** Module **Source:** [`integration/microservices/src/tcp-tls/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.module.ts#L58) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # AssignerProtocol **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L613) ## Definition ```ts { MemberMetadata: ISerializer; MemberAssignment: ISerializer; } ``` # findOne **Kind:** API Endpoint **Source:** [`sample/01-cats-app/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.controller.ts#L25) ## Endpoint `GET /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `number` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # FirstRequestService **Kind:** Service **Source:** [`integration/scopes/src/nested-transient/first-request.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/first-request.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ FirstRequestService participant p2 as βš™οΈ TransientLoggerService participant p3 as βš™οΈ NestedTransientService client->>+p1: FirstRequestService p1->>+p2: TransientLoggerService p2->>+p3: NestedTransientService p3-->-p2: return p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `TransientLoggerService` ## Referenced By - `NestedTransientController` (DEPENDS_ON) - `NestedTransientModule` (MODULE_PROVIDES) # isMiddlewareRouteExcluded **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L118) ## Signature ```ts function isMiddlewareRouteExcluded(req: Record, excludedRoutes: ExcludeRouteMetadata[], httpAdapter: HttpServer): boolean ``` ## Parameters | Name | Type | |---|---| | `req` | `Record` | | `excludedRoutes` | `ExcludeRouteMetadata[]` | | `httpAdapter` | `HttpServer` | **Returns:** `boolean` # 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) `MulterOptions` configures how Multer processes `multipart/form-data` requests in the Express platform integration. Use it to select file storage behavior, configure upload size and count limits, and control filename/path parsing defaults. ## Properties | Property | Type | |---|---| | `dest` | `string | Function` | | `storage` | `any` | | `limits` | `{ /** Max field name size (Default: 100 bytes) */ fieldNameSize?: number; /** Max field value size (Default: 1MB) */ fieldSize?: number; /** Max number of non- file fields (Default: Infinity) */ fields?: number; /** For multipart forms, the max file size (in bytes)(Default: Infinity) */ fileSize?: number; /** For multipart forms, the max number of file fields (Default: Infinity) */ files?: number; /** For multipart forms, the max number of parts (fields + files)(Default: Infinity) */ parts?: number; /** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */ headerPairs?: number; }` | | `preservePath` | `boolean` | | `defParamCharset` | `string` | ## Diagram ```mermaid graph LR A[Multipart HTTP Request] --> B[MulterOptions] B --> C[Multer Middleware] B --> D[Storage Configuration] B --> E[Upload Limits] C --> F[Parsed Fields] C --> G[Uploaded Files] D --> G ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import type { MulterOptions } from '@nestjs/platform-express'; const uploadOptions: MulterOptions = { dest: './uploads', limits: { fileSize: 5 * 1024 * 1024, // 5 MB files: 3, fields: 10, fieldNameSize: 100, }, preservePath: false, defParamCharset: 'utf8', }; @Module({ imports: [MulterModule.register(uploadOptions)], }) export class AppModule {} ``` ## AI Coding Instructions - Configure `limits` for all public upload endpoints to prevent oversized files or excessive multipart fields. - Use `storage` when custom file naming, destination selection, or non-disk storage behavior is required. - Treat `fileSize`, `files`, and `parts` limits as security controls; validate uploaded file types separately. - Keep `preservePath` disabled unless preserving client-provided paths is explicitly required and safely handled. - Pass these options through `MulterModule.register()` or a feature-specific Multer module configuration. # NestContainer **Kind:** Class **Source:** [`packages/core/injector/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/container.ts#L31) `NestContainer` is the core registry for Nest application modules, dynamic module metadata, global modules, and HTTP adapter references. It coordinates module compilation and insertion during application bootstrap, ensuring modules are registered once and global modules are available across the dependency graph. ## 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 App[Application Bootstrap] --> Container[NestContainer] Container --> Compiler[Module Compiler] Compiler --> AddModule[addModule / replaceModule] AddModule --> Modules[ModulesContainer] Container --> DynamicMetadata[Dynamic Module Metadata] Container --> GlobalModules[Global Modules Set] Container --> HttpAdapter[HTTP Adapter Reference] Modules --> Module[Module Instances] ``` ## Usage ```ts import { ApplicationConfig } from '@nestjs/core/application-config'; import { NestContainer } from '@nestjs/core/injector/container'; class AppModule {} async function registerApplicationModule() { const applicationConfig = new ApplicationConfig(); const container = new NestContainer(applicationConfig); const result = await container.addModule(AppModule, []); if (result?.inserted) { console.log('AppModule registered successfully'); } const modules = container.getModules(); console.log(`Registered modules: ${modules.size}`); } registerApplicationModule(); ``` ## AI Coding Instructions - Treat `NestContainer` as framework infrastructure; prefer Nest’s public application APIs unless extending the core runtime. - Use `addModule()` for normal registration and check the returned `inserted` flag before assuming a new module was created. - Use `replaceModule()` when overriding modules in testing or custom platform integrations. - Preserve dynamic module metadata through `addDynamicMetadata()` and `addDynamicModules()` so imported dynamic modules are registered correctly. - Register HTTP adapters through `setHttpAdapter()` before components that depend on `getHttpAdapterRef()` or `getHttpAdapterHostRef()`. # Query **Kind:** Graphql Type **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - CALLS_API β†’ `recipe` - CALLS_API β†’ `recipes` # RecordMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L748) ## Definition ```ts { topicName: string; partition: number; errorCode: number; offset?: string; timestamp?: string; baseOffset?: string; logAppendTime?: string; logStartOffset?: string; } ``` # ResourcePatternTypes **Kind:** Enum **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L335) ## Values - `UNKNOWN` - `ANY` - `MATCH` - `LITERAL` - `PREFIXED` # VersionNeutralController **Kind:** Controller **Source:** [`integration/versioning/src/neutral.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/neutral.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ VersionNeutralController client->>+p1: VersionNeutralController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `neutral` ## Referenced By - `AppModule` (MODULE_DECLARES) # AppModule **Kind:** Module **Source:** [`integration/nest-application/global-prefix/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # 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) 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. # findOne **Kind:** API Endpoint **Source:** [`sample/36-hmr-esm/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/cats.controller.ts#L25) ## Endpoint `GET /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `number` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) `GrpcOptions` configures a Nest microservice that uses the `Transport.GRPC` transport. It defines how protobuf definitions are loaded, how the gRPC server and channel behave, and optional lifecycle hooks such as graceful shutdown and package-definition customization. ## 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 A[GrpcOptions] --> B[transport: Transport.GRPC] A --> C[options] C --> D[Service definition] D --> D1[package] D --> D2[protoPath] D --> D3[packageDefinition] C --> E[Proto loading] E --> E1[protoLoader] E --> E2[loader] E --> E3[includeDirs] C --> F[Connection settings] F --> F1[url] F --> F2[credentials] F --> F3[channelOptions] F --> F4[keepalive] C --> G[Message limits] G --> G1[maxSendMessageLength] G --> G2[maxReceiveMessageLength] G --> G3[maxMetadataSize] C --> H[Lifecycle hooks] H --> H1[gracefulShutdown] H --> H2[onLoadPackageDefinition] ``` ## Usage ```ts import { Transport, type MicroserviceOptions } from '@nestjs/microservices'; import { join } from 'path'; const grpcOptions: MicroserviceOptions = { transport: Transport.GRPC, options: { url: '0.0.0.0:50051', package: 'users', protoPath: join(__dirname, 'proto/users.proto'), maxReceiveMessageLength: 10 * 1024 * 1024, maxSendMessageLength: 10 * 1024 * 1024, keepalive: { keepaliveTimeMs: 30_000, keepaliveTimeoutMs: 10_000, keepalivePermitWithoutCalls: 1, }, loader: { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, includeDirs: [join(__dirname, 'proto')], }, gracefulShutdown: true, onLoadPackageDefinition: (pkg, server) => { // Register or inspect loaded package definitions if needed. }, }, }; ``` ## AI Coding Instructions - Always set `transport: Transport.GRPC` and provide a `package` value matching the protobuf `package` declaration. - Use `protoPath` for file-based `.proto` loading, or provide `packageDefinition` when definitions are loaded externally. - Configure `loader.includeDirs` when protobuf files import shared or external `.proto` definitions. - Set message-size limits deliberately for large payloads; ensure client and server limits are compatible. - Enable `gracefulShutdown` for production services and use `onLoadPackageDefinition` only for package-registration or server customization workflows. # HelloTransientService **Kind:** Service **Source:** [`integration/scopes/src/inject-inquirer/hello-transient/hello-transient.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello-transient/hello-transient.service.ts#L4) `HelloTransientService` is a NestJS service used in the `inject-inquirer` integration scope to provide a greeting value. It is designed to participate in Nest's dependency-injection flow, likely helping validate transient-provider behavior and inquirer-aware resolution. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `unknown` | ## Dependencies - `TransientLogger` ## Diagram ```mermaid sequenceDiagram participant Consumer as Injecting Provider participant Nest as NestJS DI Container participant Hello as HelloTransientService Consumer->>Nest: Request HelloTransientService Nest->>Hello: Create/resolve transient instance Hello-->>Nest: Service instance Nest-->>Consumer: Inject service Consumer->>Hello: greeting() Hello-->>Consumer: Greeting result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloTransientService } from './hello-transient.service'; @Injectable() export class GreetingConsumer { constructor( private readonly helloTransientService: HelloTransientService, ) {} getGreeting() { return this.helloTransientService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloTransientService` through NestJS constructor injection rather than creating it with `new`. - Call `greeting()` as the public service API; keep greeting-related logic encapsulated in the service. - Preserve the configured provider scope when modifying this service, especially if integration tests depend on transient instance creation. - Ensure the service is registered in the appropriate NestJS module's `providers` array before injecting it elsewhere. ## Relationships - DEPENDS_ON β†’ `TransientLogger` ## Referenced By - `HelloController` (DEPENDS_ON) - `HelloModule` (MODULE_PROVIDES) # longPayload **Kind:** Constant **Source:** [`packages/microservices/test/json-socket/data/long-payload-with-special-chars.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/test/json-socket/data/long-payload-with-special-chars.ts#L1) ## Definition ```ts [ { _id: '584f17147fce7ca0a8bacfd2', index: 0, guid: '1d127572-0369-45fb-aa2f-e3bb083ac2b2', isActive: true, balance: '$2,926.06', picture: 'http://placehold.it/32x32', age: 26, eyeColor: 'green', name: 'WΓ§Γͺtson Aguilar [special characters in name that used to fail on long payloads]', gender: 'male', company: 'PROWASTE', email: 'watsonaguilar@prowa… ``` ## Value ```ts [ { _id: '584f17147fce7ca0a8bacfd2', index: 0, guid: '1d127572-0369-45fb-aa2f-e3bb083ac2b2', isActive: true, balance: '$2,926.06', picture: 'http://placehold.it/32x32', age: 26, eyeColor: 'green', name: 'WΓ§Γͺtson Aguilar [special characters in name that used to fail on long payloads]', gender: 'male', company: 'PROWASTE', email: 'watsonaguilar@prowa… ``` # NestMicroservice **Kind:** Class **Source:** [`packages/microservices/nest-microservice.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/nest-microservice.ts#L35) `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. # Query **Kind:** Graphql Type **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - CALLS_API β†’ `getCats` - CALLS_API β†’ `cat` # RequestTimeoutEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L421) ## Definition ```ts InstrumentationEvent<{ apiKey: number; apiName: string; apiVersion: number; broker: string; clientId: string; correlationId: number; createdAt: number; pendingDuration: number; sentAt: number; }> ``` # RmqEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/rmq.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/rmq.events.ts#L12) ## Values - `ERROR` - `DISCONNECT` - `CONNECT` - `BLOCKED` - `UNBLOCKED` # VersionNeutralMiddlewareController **Kind:** Controller **Source:** [`integration/versioning/src/neutral-middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/neutral-middleware.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ VersionNeutralMiddlewareController client->>+p1: VersionNeutralMiddlewareController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `neutral` ## Referenced By - `AppModule` (MODULE_DECLARES) # AppModule **Kind:** Module **Source:** [`integration/microservices/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.module.ts#L45) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # Assigner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L243) ## Definition ```ts { name: string; version: number; assign(group: { members: GroupMember[]; topics: string[]; }): Promise; protocol(subscription: { topics: string[] }): GroupState; } ``` # getInterceptorDelayedSseStats **Kind:** API Endpoint **Source:** [`integration/nest-application/sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.controller.ts#L211) ## Endpoint `GET /sse/interceptor/promise-delayed/stats` ## Referenced By - `AppController` (MODULE_DECLARES) # HostArrayService **Kind:** Service **Source:** [`integration/hello-world/src/host-array/host-array.service.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.service.ts#L3) `HostArrayService` is a NestJS provider responsible for supplying a greeting string within the hello-world integration application. It encapsulates the greeting behavior behind a service method so controllers or other providers can consume it through dependency injection. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant HostArrayService Client->>Controller: Request greeting endpoint Controller->>HostArrayService: greeting() HostArrayService-->>Controller: string greeting Controller-->>Client: Response with greeting ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HostArrayService } from './host-array.service'; @Injectable() export class HostArrayController { constructor(private readonly hostArrayService: HostArrayService) {} getGreeting(): string { return this.hostArrayService.greeting(); } } ``` ## AI Coding Instructions - Keep `HostArrayService` injectable and register it in the corresponding NestJS module's `providers` array. - Use constructor injection when consuming the service from controllers or other providers; do not instantiate it with `new`. - Preserve the `greeting(): string` contract when changing the implementation or adding callers. - Add new host-array-related business logic to this service rather than placing it directly in controllers. ## Referenced By - `HostArrayController` (DEPENDS_ON) - `HostArrayModule` (MODULE_PROVIDES) # 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) ## Signature ```ts function isRouteExcluded(excludedRoutes: ExcludeRouteMetadata[], path: string, requestMethod: RequestMethod) ``` ## Parameters | Name | Type | |---|---| | `excludedRoutes` | `ExcludeRouteMetadata[]` | | `path` | `string` | | `requestMethod` | `RequestMethod` | # LoggerService **Kind:** Interface **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L23) # NoVersioningController **Kind:** Controller **Source:** [`integration/versioning/src/no-versioning.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/no-versioning.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ NoVersioningController client->>+p1: NoVersioningController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `helloFoo` ## Referenced By - `AppModule` (MODULE_DECLARES) # Query **Kind:** Graphql Type **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - CALLS_API β†’ `cats` - CALLS_API β†’ `cat` # RmqStatus **Kind:** Enum **Source:** [`packages/microservices/events/rmq.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/rmq.events.ts#L5) ## Values - `DISCONNECTED` - `CONNECTED` - `BLOCKED` - `UNBLOCKED` # Server **Kind:** Class **Source:** [`packages/microservices/server/server.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server.ts#L47) `Server` is the base class for NestJS microservice transport servers. It manages message handlers registered by pattern and provides lifecycle hooks for starting, listening, processing messages, and shutting down a transport. ## 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 App[Microservice Application] --> Server[Server Transport Base Class] Server --> Handlers[Message Handler Map] Transport[Custom Transport Implementation] --> Server Server --> StartHook[Processing Start Hook] Server --> EndHook[Processing End Hook] Incoming[Incoming Message Pattern] --> Lookup[getHandlerByPattern] Lookup --> Handlers Handlers --> Response[Handler Response] ``` ## Usage ```ts import { Server, MessageHandler } from '@nestjs/microservices'; class CustomServer extends Server { listen(callback: () => void) { // Start the underlying transport here. console.log('Custom transport is listening'); callback(); } close() { // Close connections and release transport resources. console.log('Custom transport closed'); } receiveMessage(pattern: string, data: unknown) { const handler = this.getHandlerByPattern(pattern); if (!handler) { throw new Error(`No handler registered for pattern: ${pattern}`); } return handler(data); } } const server = new CustomServer(); server.addHandler('users.findOne', async (id: string) => { return { id, name: 'Ada Lovelace' }; }); server.setOnProcessingStartHook(() => { console.log('Started processing message'); }); server.setOnProcessingEndHook(() => { console.log('Finished processing message'); }); server.listen(() => { console.log('Server ready'); }); ``` ## AI Coding Instructions - Extend `Server` when implementing a custom microservice transport; provide transport-specific `listen()` and `close()` behavior. - Register request and event handlers through `addHandler()` rather than modifying the handler map returned by `getHandlers()`. - Use the same message pattern format when registering handlers and resolving them with `getHandlerByPattern()`. - Invoke processing hooks around transport message execution so tracing, metrics, and cleanup integrations run consistently. - Call `setTransportId()` when the transport needs a stable identifier for handler metadata or serialization behavior. ## How it works `Server` is an abstract base class for microservice transport servers. It holds a route-to-handler registry, transport identity, serializer/deserializer references, processing hooks, and a replayed status stream; concrete transports implement event subscription, underlying-server access, startup, and shutdown through `on`, `unwrap`, `listen`, and `close`. [packages/microservices/server/server.ts:47-107] - `transportId` is optional until assigned. `setTransportId()` stores a `Transport` enum value or symbol. [packages/microservices/server/server.ts:52-54, packages/microservices/server/server.ts:109-115] - `status` exposes the internal one-value `ReplaySubject` as an observable and suppresses consecutive duplicate values. The base class does not emit statuses itself. [packages/microservices/server/server.ts:73-80] - `setOnProcessingStartHook()` replaces the start hook. Its initial hook calls the supplied `done` callback; `setOnProcessingEndHook()` stores an optional completion hook. [packages/microservices/server/server.ts:60-72, packages/microservices/server/server.ts:117-137] ## Handler registration and lookup `addHandler(pattern, callback, isEventHandler, extras)` normalizes the pattern into a route, mutates the callback by assigning its `isEventHandler` and `extras` properties, then stores it in `messageHandlers`. [packages/microservices/server/server.ts:139-158] - If an event handler is registered for a route that already has a handler, it walks that handler’s `next` chain and appends the new callback at the tail. Otherwise, it replaces or creates the map entry for the normalized route. [packages/microservices/server/server.ts:149-158] - `getHandlers()` returns the actual internal `Map`, not a copy. `getHandlerByPattern()` converts the input pattern to a route and returns the mapped handler or `null`. [packages/microservices/server/server.ts:161-170] - Listener discovery registers handlers through `addHandler()`. For static event listeners, the listener controller wraps the callback and passes the event flag and metadata extras; non-event listeners are registered with the created proxy. [packages/microservices/listeners-controller.ts:89-140] - A `MessageHandler` accepts data and an optional context, returns a value or observable through a promise, and may carry `next`, `isEventHandler`, and `extras` properties. [packages/microservices/interfaces/message-handler.interface.ts:6-17] For route conversion, `getRouteFromPattern()` first attempts `JSON.parse()` on the supplied string; on parse failure it retains the original string, then normalizes it. [packages/microservices/server/server.ts:329-339] Normalization delegates to `transformPatternToRoute()`: strings and numbers become strings; object keys are sorted; object nesting beyond the depth limit yields `[MAX_DEPTH_REACHED]`; objects with more than 20 keys yield `[TOO_MANY_KEYS]`. [packages/microservices/server/server.ts:341-342, packages/microservices/utils/transform-pattern.utils.ts:8-9, packages/microservices/utils/transform-pattern.utils.ts:21-67] ## Event handling `handleEvent(pattern, packet, context)` looks up a handler. If none exists, it logs an error stating that no matching event handler is defined and returns the logger call’s result. [packages/microservices/server/server.ts:208-216, packages/microservices/constants.ts:55-56] When a handler exists, it invokes the configured start hook with the current transport ID, context, and a callback that awaits `handler(packet.data, context)`. [packages/microservices/server/server.ts:217-219] - If the result is an observable, it creates and connects a `connectable` observable with a `Subject` connector. On observable finalization, it invokes the end hook with the transport ID and context. [packages/microservices/server/server.ts:219-231] - For a non-observable result, it invokes the end hook immediately after the awaited handler result. [packages/microservices/server/server.ts:232-234] - The method passes `this.transportId!` to these hooks but has no runtime validation that a transport ID was assigned. [packages/microservices/server/server.ts:217-234] ## Response-stream handling `send(stream$, respond)` subscribes to a response observable and returns that RxJS subscription. [packages/microservices/server/server.ts:172-175, packages/microservices/server/server.ts:197-205] It queues outgoing packets and schedules asynchronous draining with `process.nextTick`; packets are sent one at a time by awaiting `respond(packet)`. [packages/microservices/server/server.ts:176-196] - Each emitted value is queued as `{ response }`. [packages/microservices/server/server.ts:197-205] - A stream error is queued as `{ err }` and then replaced with an empty observable, so the subscription completes. [packages/microservices/server/server.ts:199-202] - Finalization queues `{ isDisposed: true }`. If earlier packets remain queued, the disposed flag is added to the last queued packet instead of adding another packet. [packages/microservices/server/server.ts:179-183, packages/microservices/server/server.ts:203-205] - `WritePacket` supports optional `err`, `response`, `isDisposed`, and `status` fields. [packages/microservices/interfaces/packet.interface.ts:10-15] `transformToObservable()` converts a promise, observable, or plain result into an observable. A promise is converted with `from`, and if it resolves to an observable that observable is flattened; an observable is returned unchanged; every other value is wrapped with `of`. [packages/microservices/server/server.ts:238-258] ## Serialization, options, and errors Concrete transport constructors call `initializeSerializer()` and `initializeDeserializer()` after transport-specific setup; for example, `ServerTCP` does so during construction. [packages/microservices/server/server-tcp.ts:49-60] - `initializeSerializer()` selects `options.serializer` when truthy, otherwise creates an `IdentitySerializer`, whose `serialize()` returns its input unchanged. [packages/microservices/server/server.ts:297-308, packages/microservices/serializers/identity.serializer.ts:3-6] - `initializeDeserializer()` selects `options.deserializer` when truthy, otherwise creates `IncomingRequestDeserializer`. [packages/microservices/server/server.ts:310-321] - The default deserializer returns inputs already containing a defined `pattern` or `data`; otherwise it maps a value to `{ pattern: options.channel, data: value }`, or to undefined pattern/data when no options are supplied. [packages/microservices/deserializers/incoming-request.deserializer.ts:11-46] - `getOptionsProp()` returns an object property when the object exists and owns or inherits that property; otherwise it returns the passed default value, which defaults to `undefined`. [packages/microservices/server/server.ts:260-283] - `handleError()` logs the supplied string through the server logger. `loadPackage()` delegates package loading to Nest’s imported `loadPackage` helper. [packages/microservices/server/server.ts:285-295] # targetModulesByContainer **Kind:** Constant **Source:** [`packages/core/router/router-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-module.ts#L11) ## Definition ```ts new WeakMap< ModulesContainer, WeakSet >() ``` ## Value ```ts new WeakMap< ModulesContainer, WeakSet >() ``` # AppModule **Kind:** Module **Source:** [`integration/versioning/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app.module.ts#L13) ## Relationships - MODULE_DECLARES β†’ `appv1controller` - MODULE_DECLARES β†’ `appv2controller` - MODULE_DECLARES β†’ `MultipleVersionController` - MODULE_DECLARES β†’ `NoVersioningController` - MODULE_DECLARES β†’ `VersionNeutralController` - MODULE_DECLARES β†’ `OverrideController` - MODULE_DECLARES β†’ `OverridePartialController` - MODULE_DECLARES β†’ `MiddlewareController` - MODULE_DECLARES β†’ `MultipleMiddlewareVersionController` - MODULE_DECLARES β†’ `VersionNeutralMiddlewareController` # 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) ## Definition ```ts | RedisOptions | NatsOptions | MqttOptions | GrpcOptions | KafkaOptions | TcpClientOptions | RmqOptions ``` # 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) ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createWsParamDecorator( WsParamtype.SOCKET, ) ``` # getIsolationData **Kind:** API Endpoint **Source:** [`integration/scopes/src/nested-transient/nested-transient.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/nested-transient.controller.ts#L16) ## Endpoint `GET /` ## Referenced By - `NestedTransientController` (MODULE_DECLARES) # HostService **Kind:** Service **Source:** [`integration/hello-world/src/host/host.service.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.service.ts#L3) `HostService` is a NestJS provider in the hello-world host application. It encapsulates the host-facing greeting behavior and exposes a simple `greeting()` method that returns a string response for controllers or other injected services. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant HostService Client->>Controller: Request greeting endpoint Controller->>HostService: greeting() HostService-->>Controller: greeting string Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HostService } from './host.service'; @Injectable() export class HostController { constructor(private readonly hostService: HostService) {} getGreeting(): string { return this.hostService.greeting(); } } ``` ## AI Coding Instructions - Keep `HostService` focused on host-domain behavior; place HTTP request and response handling in controllers. - Inject the service through NestJS constructor dependency injection instead of creating it with `new HostService()`. - Preserve the `greeting(): string` return contract when updating the greeting behavior or its consumers. - Register the service in the appropriate NestJS module's `providers` array before injecting it elsewhere. ## Referenced By - `HostController` (DEPENDS_ON) - `HostModule` (MODULE_PROVIDES) # 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) `NatsOptions` configures a NestJS microservice or client that uses the NATS transport. It requires `Transport.NATS` and provides connection, authentication, reconnection, serialization, and request/reply behavior through its `options` object. Most connection settings are forwarded to the underlying NATS client configuration. ## 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[NestJS Application] --> Config[NatsOptions] Config --> Transport[Transport.NATS] Config --> Options[options] Options --> Connection[Servers and Connection Settings] Options --> Auth[Authentication and TLS] Options --> Resilience[Reconnect and Ping Settings] Options --> Messaging[Queue, Headers, Serializers] Connection --> NATS[NATS Server or Cluster] Auth --> NATS Resilience --> NATS Messaging --> NATS ``` ## Usage ```ts import { ClientProxyFactory, Transport } from '@nestjs/microservices'; import type { NatsOptions } from '@nestjs/microservices'; const natsConfig: NatsOptions = { transport: Transport.NATS, options: { servers: ['nats://localhost:4222'], queue: 'orders-service', name: 'orders-client', reconnect: true, maxReconnectAttempts: 10, reconnectTimeWait: 1_000, headers: { 'x-service-name': 'orders-service', }, }, }; const client = ClientProxyFactory.create(natsConfig); // Publish an event to NATS. client.emit('order.created', { orderId: 'order-123', customerId: 'customer-456', }); ``` ## AI Coding Instructions - Always set `transport` to `Transport.NATS`; place NATS-specific settings under `options`. - Configure `servers` with one or more broker URLs when connecting to a NATS cluster, rather than hard-coding a single local endpoint for production. - Use `queue` for competing consumers that should share message handling work; use distinct queues when services must each receive a message independently. - Configure authentication (`token`, `user`/`pass`, `userJWT`, `nkey`, or `tls`) from environment-backed configuration and never embed credentials in source code. - Supply compatible `serializer` and `deserializer` implementations on both sides when customizing message encoding. # Query **Kind:** Graphql Type **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - CALLS_API β†’ `posts` - CALLS_API β†’ `post` # repl **Kind:** Function **Source:** [`packages/core/repl/repl.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl.ts#L12) ## Signature ```ts async function repl(module: Type | DynamicModule, replOptions: ReplOptions) ``` ## Parameters | Name | Type | |---|---| | `module` | `Type | DynamicModule` | | `replOptions` | `ReplOptions` | # ScopedController **Kind:** Controller **Source:** [`integration/injector/src/scoped/scoped.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/scoped.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ ScopedController client->>+p1: ScopedController p1-->client: return response ``` ## Referenced By - `ScopedModule` (MODULE_DECLARES) # ServerGrpc **Kind:** Class **Source:** [`packages/microservices/server/server-grpc.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-grpc.ts#L59) `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) # 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) ## Values - `URI` - `HEADER` - `MEDIA_TYPE` - `CUSTOM` # AdvancedGrpcController **Kind:** Controller **Source:** [`integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AdvancedGrpcController client->>+p1: AdvancedGrpcController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `stream` # AModule **Kind:** Module **Source:** [`integration/injector/src/multiple-providers/a.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/multiple-providers/a.module.ts#L3) # ConsumerGroupJoinEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L942) ## Definition ```ts InstrumentationEvent<{ duration: number; groupId: string; isLeader: boolean; leaderId: string; groupProtocol: string; memberId: string; memberAssignment: IMemberAssignment; }> ``` # Ctx **Kind:** Constant **Source:** [`packages/microservices/decorators/ctx.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/ctx.decorator.ts#L4) ## Definition ```ts () => ParameterDecorator ``` ## Value ```ts createRpcParamDecorator( RpcParamtype.CONTEXT, ) ``` # getMany **Kind:** API Endpoint **Source:** [`sample/04-grpc/src/hero/hero.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/hero/hero.controller.ts#L31) ## Endpoint `GET /hero` ## Referenced By - `HeroController` (MODULE_DECLARES) # 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) ## Values - `NO_STREAMING` - `RX_STREAMING` - `PT_STREAMING` # NonDurableService **Kind:** Service **Source:** [`integration/scopes/src/durable/non-durable.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/non-durable.service.ts#L5) `NonDurableService` is a NestJS service used to access tenant-specific context for non-durable execution paths. Its primary responsibility is exposing the current tenant identifier through `getTenantId()`, allowing dependent services to apply tenant-aware behavior without directly managing context resolution. ## Methods | Method | Signature | Returns | |---|---|---| | `getTenantId` | `getTenantId()` | `unknown` | ## Dependencies - `TenantContext` ## Diagram ```mermaid sequenceDiagram participant Consumer as NestJS Consumer participant Service as NonDurableService participant Context as Request/Scope Context Consumer->>Service: getTenantId() Service->>Context: Resolve current tenant ID Context-->>Service: tenantId Service-->>Consumer: tenantId ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { NonDurableService } from './durable/non-durable.service'; @Injectable() export class TenantAwareService { constructor( private readonly nonDurableService: NonDurableService, ) {} getCurrentTenantData() { const tenantId = this.nonDurableService.getTenantId(); return { tenantId, message: 'Processing data for the current tenant', }; } } ``` ## AI Coding Instructions - Inject `NonDurableService` through NestJS dependency injection rather than constructing it manually. - Use `getTenantId()` as the single access point for the active tenant context in non-durable flows. - Treat the return value as `unknown` until it is validated or narrowed to the tenant ID type required by the calling code. - Ensure tenant context is established by the surrounding scope or request pipeline before calling this service. - Avoid caching tenant IDs globally, as tenant context may differ between requests or execution scopes. ## Relationships - DEPENDS_ON β†’ `TenantContext` ## Referenced By - `DurableController` (DEPENDS_ON) - `DurableModule` (MODULE_PROVIDES) # Query **Kind:** Graphql Type **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - CALLS_API β†’ `recipe` - CALLS_API β†’ `recipes` # 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) `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] # ServerKafka **Kind:** Class **Source:** [`packages/microservices/server/server-kafka.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-kafka.ts#L43) `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. # UNDEFINED_MODULE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L210) ## Signature ```ts function UNDEFINED_MODULE_MESSAGE(parentModule: any, index: number, scope: any[]) ``` ## Parameters | Name | Type | |---|---| | `parentModule` | `any` | | `index` | `number` | | `scope` | `any[]` | # AppController **Kind:** Controller **Source:** [`integration/nest-application/sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.controller.ts#L35) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `releaseSsePromiseDelayed` - MODULE_DECLARES β†’ `getSsePromiseDelayedStats` - MODULE_DECLARES β†’ `releaseInterceptorDelayedSse` - MODULE_DECLARES β†’ `getInterceptorDelayedSseStats` # AppModule **Kind:** Module **Source:** [`integration/inspector/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app.module.ts#L25) ## Relationships - MODULE_IMPORTS β†’ `coremodule` - MODULE_IMPORTS β†’ `catsmodule` - MODULE_IMPORTS β†’ `durablemodule` - MODULE_IMPORTS β†’ `DogsModule` - MODULE_IMPORTS β†’ `usersmodule` - MODULE_IMPORTS β†’ `databasemodule` - MODULE_IMPORTS β†’ `ExternalSvcModule` - MODULE_IMPORTS β†’ `ChatModule` - MODULE_IMPORTS β†’ `requestchainmodule` - MODULE_IMPORTS β†’ `propertiesmodule` - MODULE_IMPORTS β†’ `inputmodule` - MODULE_DECLARES β†’ `appv1controller` - MODULE_DECLARES β†’ `appv2controller` # 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) 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. # 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) 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. # ConsumerReceivedUnsubscribedTopicsEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L981) ## Definition ```ts InstrumentationEvent<{ groupId: string; generationId: number; memberId: string; assignedTopics: string[]; topicsSubscribed: string[]; topicsNotSubscribed: string[]; }> ``` # 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) ## Definition ```ts { [`${RpcParamtype.PAYLOAD}:0`]: { index: 0, data: undefined, pipes: [] }, } ``` ## Value ```ts { [`${RpcParamtype.PAYLOAD}:0`]: { index: 0, data: undefined, pipes: [] }, } ``` # getSsePromiseDelayedStats **Kind:** API Endpoint **Source:** [`integration/nest-application/sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.controller.ts#L141) ## Endpoint `GET /sse/promise-delayed/stats` ## Referenced By - `AppController` (MODULE_DECLARES) # NatsEventsMap **Kind:** Enum **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L14) ## Values - `DISCONNECT` - `RECONNECT` - `UPDATE` # OwnersService **Kind:** Service **Source:** [`sample/12-graphql-schema-first/src/owners/owners.service.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/owners/owners.service.ts#L4) `OwnersService` provides owner lookup functionality for the GraphQL schema-first example. It is responsible for retrieving an `Owner` by identifier and is typically called by GraphQL resolvers when resolving owner-related queries or relationships. ## Methods | Method | Signature | Returns | |---|---|---| | `findOneById` | `findOneById(id: number)` | `Owner` | ## Diagram ```mermaid sequenceDiagram participant Client as GraphQL Client participant Resolver as Owners Resolver participant Service as OwnersService participant Data as Owner Data Source Client->>Resolver: Query owner(id) Resolver->>Service: findOneById(id) Service->>Data: Find owner by ID Data-->>Service: Owner Service-->>Resolver: Owner Resolver-->>Client: Owner response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { OwnersService } from './owners.service'; @Injectable() export class OwnersResolver { constructor(private readonly ownersService: OwnersService) {} owner(_: unknown, { id }: { id: string }) { return this.ownersService.findOneById(id); } } ``` ## AI Coding Instructions - Keep owner retrieval logic in `OwnersService`; GraphQL resolvers should delegate to the service rather than access data directly. - Preserve the `findOneById()` return contract as `Owner` when updating lookup behavior or backing storage. - Ensure GraphQL argument types and owner identifiers match the identifier format expected by the service. - Add validation or not-found handling consistently if the service is connected to a database or external data source. ## Referenced By - `OwnersModule` (MODULE_PROVIDES) - `OwnersModule` (MODULE_EXPORTS) # Query **Kind:** Graphql Type **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - CALLS_API β†’ `recipe` - CALLS_API β†’ `recipes` # ServerMqtt **Kind:** Class **Source:** [`packages/microservices/server/server-mqtt.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-mqtt.ts#L38) `ServerMqtt` is the MQTT transport server implementation for NestJS microservices. It creates and manages an MQTT client connection, subscribes to registered message patterns, parses incoming packets, routes them to matching handlers, and publishes responses when required. **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[createMqttClient] C --> D[bindEvents] D --> E[Incoming MQTT Packet] E --> F[parseMessage] F --> G[matchMqttPattern] G --> H[getMessageHandler] H --> I[handleMessage] I --> J[getPublisher] J --> K[Publish Response to Broker] ``` ## AI Coding Instructions - Register message handlers with MQTT topic patterns that match the topics published by clients; account for MQTT wildcards such as `+` and `#`. - Keep `handleMessage()` focused on transport-level dispatching; put business logic in registered handlers or application services. - Ensure message payloads are serializable before publishing responses through the MQTT client. - Call `close()` during application shutdown to disconnect the MQTT client cleanly and release subscriptions. - Preserve the parsing and pattern-matching flow in `parseMessage()` and `matchMqttPattern()` when extending transport behavior. ## How it works `ServerMqtt` is an MQTT transport server that extends the shared `Server` base class and identifies itself with `Transport.MQTT`. It maintains an MQTT client, registered message handlers inherited from `Server`, queued MQTT-client event listeners, serializers/deserializers, and an MQTT status observable. [packages/microservices/server/server-mqtt.ts:38-45](packages/microservices/server/server-mqtt.ts#L38-L45) [packages/microservices/server/server.ts:56-59](packages/microservices/server/server.ts#L56-L59) [packages/microservices/server/server.ts:73-80](packages/microservices/server/server.ts#L73-L80) - **Construction and configuration:** The constructor reads `options.url`, defaulting to `mqtt://localhost:1883`, loads the optional `mqtt` package, selects `options.serializer` or a `MqttRecordSerializer`, and selects `options.deserializer` or `IncomingRequestDeserializer`. [packages/microservices/server/server-mqtt.ts:47-57](packages/microservices/server/server-mqtt.ts#L47-L57) [packages/microservices/constants.ts:8](packages/microservices/constants.ts#L8) [packages/microservices/server/server-mqtt.ts:314-316](packages/microservices/server/server-mqtt.ts#L314-L316) [packages/microservices/server/server.ts:310-320](packages/microservices/server/server.ts#L310-L320) MQTT options may include a URL, serializer, deserializer, client options, and subscription options. [packages/microservices/interfaces/microservice-configuration.interface.ts:142-167](packages/microservices/interfaces/microservice-configuration.interface.ts#L142-L167) - **Starting:** `listen(callback)` creates a client with `mqtt.connect(url, options)` and calls `start`; synchronous errors from either step are passed to `callback(err)`. [packages/microservices/server/server-mqtt.ts:59-68](packages/microservices/server/server-mqtt.ts#L59-L68) [packages/microservices/server/server-mqtt.ts:117-119](packages/microservices/server/server-mqtt.ts#L117-L119) `start` registers built-in `error`, `reconnect`, `disconnect`, `close`, and `connect` listeners; attaches listeners previously registered through `on`; binds incoming MQTT `message` handling and subscriptions; then calls the startup callback on `connect`. [packages/microservices/server/server-mqtt.ts:70-86](packages/microservices/server/server-mqtt.ts#L70-L86) - **Status and client events:** An MQTT `error` is logged. `reconnect`, `disconnect`, `close`, and `connect` emit `reconnecting`, `disconnected`, `closed`, and `connected`, respectively, through the inherited status subject; reconnect also logs a message. [packages/microservices/server/server-mqtt.ts:264-292](packages/microservices/server/server-mqtt.ts#L264-L292) The `status` getter exposes that subject as an observable with consecutive duplicate statuses removed. [packages/microservices/server/server.ts:73-80](packages/microservices/server/server.ts#L73-L80) Calling `on(event, callback)` after client creation attaches directly to the client; before creation it queues the listener until `start`. [packages/microservices/server/server-mqtt.ts:303-312](packages/microservices/server/server-mqtt.ts#L303-L312) - **Subscriptions:** `bindEvents` installs a `message` listener and subscribes once for each registered handler pattern. [packages/microservices/server/server-mqtt.ts:88-109](packages/microservices/server/server-mqtt.ts#L88-L109) The base `addHandler` normalizes patterns and records whether a handler is an event handler plus its `extras`; multiple event handlers for the same normalized pattern are chained. [packages/microservices/server/server.ts:139-159](packages/microservices/server/server.ts#L139-L159) Subscription options come from `options.subscribeOptions`; when a handler has `extras.qos !== undefined`, that QoS replaces the global QoS while other global subscription fields remain. [packages/microservices/server/server-mqtt.ts:96-108](packages/microservices/server/server-mqtt.ts#L96-L108) - **Incoming messages:** For each MQTT message, it converts the buffer to text, tries `JSON.parse`, and leaves the text unchanged when parsing fails. It then deserializes the value with `{ channel }` and creates an `MqttContext` containing the channel and original MQTT packet. [packages/microservices/server/server-mqtt.ts:121-139](packages/microservices/server/server-mqtt.ts#L121-L139) [packages/microservices/server/server-mqtt.ts:195-201](packages/microservices/server/server-mqtt.ts#L195-L201) With the default deserializer, values lacking both `pattern` and `data` are mapped to `{ pattern: channel, data: value }`; values containing either field pass through unchanged. [packages/microservices/deserializers/incoming-request.deserializer.ts:16-46](packages/microservices/deserializers/incoming-request.deserializer.ts#L16-L46) `MqttContext.getTopic()` returns the channel and `getPacket()` returns the original packet. [packages/microservices/ctx-host/mqtt.context.ts:13-25](packages/microservices/ctx-host/mqtt.context.ts#L13-L25) - **Events versus requests:** A deserialized packet whose `id` is `undefined` is handled as an event. [packages/microservices/server/server-mqtt.ts:137-140](packages/microservices/server/server-mqtt.ts#L137-L140) Event dispatch looks up a handler by topic, logs an error when absent, and invokes a found handler with `(packet.data, context)` inside the processing-start hook. For observable event results, the processing-end hook runs on finalization; otherwise it runs after the handler result is obtained. [packages/microservices/server/server.ts:208-235](packages/microservices/server/server.ts#L208-L235) - **Request handling and replies:** A packet with an `id` is treated as a request. The server finds a handler from the MQTT channel; if none matches, it publishes `{ id, status: 'error', err: NO_MESSAGE_HANDLER }`. [packages/microservices/server/server-mqtt.ts:141-166](packages/microservices/server/server-mqtt.ts#L141-L166) A found handler receives `(packet.data, mqttContext)`. Its result is converted to an observable, and each result, error, and completion packet is sent through the inherited `send` logic. [packages/microservices/server/server-mqtt.ts:157-166](packages/microservices/server/server-mqtt.ts#L157-L166) [packages/microservices/server/server.ts:172-206](packages/microservices/server/server.ts#L172-L206) Each outgoing packet is mutated to include the original request ID, serialized, and published to `${incomingTopic}/reply`; the processing-end hook runs before the publish call. [packages/microservices/server/server-mqtt.ts:169-192](packages/microservices/server/server-mqtt.ts#L169-L192) [packages/microservices/server/server-mqtt.ts:260-262](packages/microservices/server/server-mqtt.ts#L260-L262) - **`MqttRecord` reply options:** If an outgoing response’s `data` is an `MqttRecord`, its `options` are passed as MQTT publish options and `response.data.options` is deleted before serialization. [packages/microservices/server/server-mqtt.ts:174-191](packages/microservices/server/server-mqtt.ts#L174-L191) The default MQTT serializer serializes an `MqttRecord` as its contained `data`, rather than serializing the record wrapper. [packages/microservices/serializers/mqtt-record.serializer.ts:5-15](packages/microservices/serializers/mqtt-record.serializer.ts#L5-L15) - **Topic routing:** Exact normalized-topic lookup takes priority. If it fails, the server compares registered handler keys against the topic after removing a `$share//` prefix from handler keys. [packages/microservices/server/server-mqtt.ts:235-254](packages/microservices/server/server-mqtt.ts#L235-L254) Matching splits topics on `/`; a segment beginning with `+` matches one topic segment, and a segment beginning with `#` matches only when it is the final pattern segment. Otherwise, segment counts and literal segments must match. [packages/microservices/server/server-mqtt.ts:203-233](packages/microservices/server/server-mqtt.ts#L203-L233) [packages/microservices/constants.ts:14-16](packages/microservices/constants.ts#L14-L16) - **Shutdown and raw client access:** `close()` calls `mqttClient.end()` when a client exists and clears queued event listeners. [packages/microservices/server/server-mqtt.ts:112-115](packages/microservices/server/server-mqtt.ts#L112-L115) `unwrap()` returns the underlying client, but throws `Error('Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing the server.')` when no client has been created. [packages/microservices/server/server-mqtt.ts:294-300](packages/microservices/server/server-mqtt.ts#L294-L300) # AppController **Kind:** Controller **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L22) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController participant p2 as βš™οΈ ClientProxy client->>+p1: AppController p1->>+p2: ClientProxy p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `callWithClientUseFactory` - MODULE_DECLARES β†’ `callWithClientUseClass` - MODULE_DECLARES β†’ `stream` - MODULE_DECLARES β†’ `concurrent` - MODULE_DECLARES β†’ `serializeError` - MODULE_DECLARES β†’ `sendNotification` - DEPENDS_ON β†’ `ClientProxy` - DEPENDS_ON β†’ `ClientProxy` - DEPENDS_ON β†’ `ClientProxy` # AppModule **Kind:** Module **Source:** [`sample/34-using-esm-packages/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/34-using-esm-packages/src/app.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `superJSONProvider` - MODULE_PROVIDES β†’ `appservice` # 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) Interface that represents the module async options object Factory method name varies depending on the "FactoryClassMethodKey" type argument. `ConfigurableModuleAsyncOptions` defines how a configurable module obtains its options asynchronously during module registration. It supports resolving options from an existing provider, instantiating a factory class, or calling an inline factory function, with optional dependency injection support. ## 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[useExisting] A --> C[useClass] A --> D[useFactory] A --> E[inject] A --> F[provideInjectionTokensFrom] B --> G[ConfigurableModuleOptionsFactory] C --> G D --> H[ModuleOptions] E --> I[Injected dependencies] F --> J[Providers used for injection tokens] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import type { ConfigurableModuleAsyncOptions } from '@nestjs/common'; interface DatabaseModuleOptions { uri: string; poolSize?: number; } class DatabaseConfigService { createDatabaseOptions(): DatabaseModuleOptions { return { uri: process.env.DATABASE_URL ?? 'mongodb://localhost/app', poolSize: 10, }; } } const databaseOptions: ConfigurableModuleAsyncOptions< DatabaseModuleOptions, 'createDatabaseOptions' > = { useFactory: (config: DatabaseConfigService) => ({ uri: config.createDatabaseOptions().uri, poolSize: config.createDatabaseOptions().poolSize, }), inject: [DatabaseConfigService], provideInjectionTokensFrom: [DatabaseConfigService], }; @Module({ providers: [DatabaseConfigService], }) export class AppModule {} ``` ## AI Coding Instructions - Use exactly one options resolution strategy: `useExisting`, `useClass`, or `useFactory`. - Ensure factory classes implement `ConfigurableModuleOptionsFactory` with the method name specified by `FactoryClassMethodKey`. - Add dependencies required by `useFactory` to `inject`; include their providers through the surrounding module or `provideInjectionTokensFrom`. - Return a complete `ModuleOptions` object from `useFactory`, either synchronously or as a `Promise`. - Keep the factory method key consistent with the configurable module definition to avoid runtime provider-resolution errors. # ConsumerRunConfig **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1028) ## Definition ```ts { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; eachBatch?: EachBatchHandler; eachMessage?: EachMessageHandler; } ``` # filterMiddleware **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L44) ## Signature ```ts function filterMiddleware(middleware: T[], routes: RouteInfo[], httpAdapter: HttpServer) ``` ## Parameters | Name | Type | |---|---| | `middleware` | `T[]` | | `routes` | `RouteInfo[]` | | `httpAdapter` | `HttpServer` | # localPipe **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host/host.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.controller.ts#L29) ## Endpoint `GET /local-pipe/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `any` | βœ“ | | ## Referenced By - `HostController` (MODULE_DECLARES) # NatsStatus **Kind:** Enum **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L8) ## Values - `DISCONNECTED` - `RECONNECTING` - `CONNECTED` # 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) 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. # RequestService **Kind:** Service **Source:** [`integration/lazy-modules/src/request.service.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/request.service.ts#L4) `RequestService` is a NestJS service in the lazy-modules integration area. It exposes an `eager()` method for executing or retrieving the service's eagerly available request-related behavior, allowing consumers to access it through Nest dependency injection. ## Methods | Method | Signature | Returns | |---|---|---| | `eager` | `eager()` | `unknown` | ## Dependencies - `EagerService` ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Provider participant RequestService participant Result as Eager Result Consumer->>RequestService: eager() RequestService-->>Result: produce result Result-->>Consumer: return value ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { RequestService } from './request.service'; @Injectable() export class ExampleService { constructor(private readonly requestService: RequestService) {} handleRequest() { const result = this.requestService.eager(); return result; } } ``` ## AI Coding Instructions - Inject `RequestService` through NestJS constructor injection rather than creating it with `new`. - Treat the return value of `eager()` as `unknown` until it is narrowed, validated, or cast to the expected type. - Keep consumers decoupled from the service implementation; call `eager()` instead of accessing internal dependencies directly. - Register or export the service from the appropriate Nest module before injecting it into controllers or other providers. ## Relationships - DEPENDS_ON β†’ `EagerService` ## Referenced By - `RequestLazyModule` (MODULE_PROVIDES) - `RequestLazyModule` (MODULE_EXPORTS) # ServerRedis **Kind:** Class **Source:** [`packages/microservices/server/server-redis.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-redis.ts#L30) `ServerRedis` is the Redis transport server implementation for NestJS microservices. It creates Redis publisher/subscriber clients, subscribes to request patterns, parses incoming messages, and dispatches them to registered message handlers. **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 Client] -->|publish request| Redis[(Redis)] Redis -->|subscription message| ServerRedis[ServerRedis] ServerRedis --> Parse[parseMessage] Parse --> Pattern[getRequestPattern] Pattern --> Handler[getMessageHandler] Handler -->|response/event| Publisher[getPublisher] Publisher --> Redis Redis --> Client ``` ## AI Coding Instructions - Prefer configuring Redis microservices through `app.connectMicroservice({ transport: Transport.REDIS, options })`; Nest creates and manages `ServerRedis` in normal applications. - Register handlers with stable Redis-compatible patterns, such as `{ cmd: 'health' }`, so publishers and consumers resolve the same request pattern. - Ensure `close()` is called during application shutdown to disconnect both Redis subscriber and publisher clients. - Do not bypass message parsing or response publishing logic when extending the transport; use the existing handler, pattern, and publisher flow. - Verify Redis connection options such as `host`, `port`, authentication, and TLS settings match the target Redis deployment. # Subscription **Kind:** Graphql Type **Source:** [`integration/graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/schema.gql#L1) ## Relationships - CALLS_API β†’ `recipeAdded` # AppModule **Kind:** Module **Source:** [`sample/23-graphql-code-first/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/app.module.ts#L8) ## Relationships - MODULE_IMPORTS β†’ `recipesmodule` # 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) 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. # 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) ## Definition ```ts { id?: string; type: string; methodName: string; className: string; classNodeId: string; metadata: { key: string } & T; } ``` # GrpcController **Kind:** Controller **Source:** [`integration/microservices/src/grpc/grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc/grpc.controller.ts#L21) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ GrpcController client->>+p1: GrpcController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `callWithOptions` - MODULE_DECLARES β†’ `callMultiSum` - MODULE_DECLARES β†’ `callMultiSum2` - MODULE_DECLARES β†’ `serializeError` # loadAdapter **Kind:** Function **Source:** [`packages/core/helpers/load-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/load-adapter.ts#L11) ## Signature ```ts function loadAdapter(defaultPlatform: string, transport: string, loaderFn: Function) ``` ## Parameters | Name | Type | |---|---| | `defaultPlatform` | `string` | | `transport` | `string` | | `loaderFn` | `Function` | # localPipe **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host-array/host-array.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.controller.ts#L29) ## Endpoint `GET /local-pipe/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `any` | βœ“ | | ## Referenced By - `HostArrayController` (MODULE_DECLARES) # RedisStatus **Kind:** Enum **Source:** [`packages/microservices/events/redis.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/redis.events.ts#L5) ## Values - `DISCONNECTED` - `RECONNECTING` - `CONNECTED` # 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) 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. # SecondRequestService **Kind:** Service **Source:** [`integration/scopes/src/nested-transient/second-request.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/second-request.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ SecondRequestService participant p2 as βš™οΈ TransientLoggerService participant p3 as βš™οΈ NestedTransientService client->>+p1: SecondRequestService p1->>+p2: TransientLoggerService p2->>+p3: NestedTransientService p3-->-p2: return p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `TransientLoggerService` ## Referenced By - `NestedTransientController` (DEPENDS_ON) - `NestedTransientModule` (MODULE_PROVIDES) # ServerRMQ **Kind:** Class **Source:** [`packages/microservices/server/server-rmq.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-rmq.ts#L61) `ServerRMQ` is the RabbitMQ transport server used by the microservices package to connect to an AMQP broker, consume messages, and dispatch them to registered request or event handlers. It manages the connection and channel lifecycle, acknowledges messages according to configuration, and sends responses for request-based patterns. **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[createClient] C --> D[AMQP Connection] D --> E[setupChannel] E --> F[Consume Queue Messages] F --> G{Message Type} G -->|Request| H[handleMessage] G -->|Event| I[handleEvent] H --> J[sendMessage Response] I --> K[Event Handler] B --> L[close] ``` ## AI Coding Instructions - Configure `urls`, `queue`, and `queueOptions` consistently with the RabbitMQ infrastructure used by the application. - Register handlers before calling `listen()` so messages are not consumed before routing patterns are available. - Mark fire-and-forget handlers as event handlers by passing `true` to `addHandler`; request handlers should return serializable response data. - Respect `noAck` and prefetch settings: manual acknowledgements and bounded prefetch are important for reliable processing and backpressure. - Use `unwrap()` only when direct access to the underlying AMQP client is necessary; prefer the server lifecycle methods for normal connection management. # Subscription **Kind:** Graphql Type **Source:** [`integration/graphql-schema-first/src/cats/cats.types.graphql`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.types.graphql#L1) ## Relationships - CALLS_API β†’ `catCreated` # AppModule **Kind:** Module **Source:** [`integration/typeorm/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/app.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `photomodule` # 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) `FastifyStaticOptions` configures static asset serving for the Fastify platform integration. It controls the directories or URLs to expose, route prefix behavior, response decoration, caching headers, redirects, wildcard handling, and optional directory listing. ## 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] B --> G[Static files] C --> H[Registered Fastify routes] G --> H ``` ## Usage ```ts import { FastifyAdapter } from '@nestjs/platform-fastify'; import type { FastifyStaticOptions } from '@nestjs/platform-fastify'; import { join } from 'node:path'; 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('.css') || path.endsWith('.js')) { res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); } res.setHeader('Last-Modified', stat.mtime.toUTCString()); }, }; const adapter = new FastifyAdapter(); await adapter.register(require('@fastify/static'), staticOptions); ``` ## AI Coding Instructions - Provide an absolute filesystem path, URL, or an array of roots through `root`; use arrays when serving assets from multiple locations. - Keep `prefix` aligned with public asset URLs, including a trailing slash when required by the application routing convention. - Use `setHeaders` for cache-control and other response headers; avoid expensive synchronous work inside this callback. - Set `decorateReply` to `true` only when application code needs Fastify reply helpers exposed by the static plugin. - Disable `list` in production unless directory browsing is explicitly required, as listings can reveal application file structure. ## How it works `FastifyStaticOptions` is the exported TypeScript options interface accepted by `NestFastifyApplication.useStaticAssets()` and `FastifyAdapter.useStaticAssets()`. The application API describes this call as setting a base directory for public assets and shows `{ root: 'public' }` as an example. [packages/platform-fastify/interfaces/nest-fastify-application.interface.ts:72-77](packages/platform-fastify/interfaces/nest-fastify-application.interface.ts#L72-L77) - `root` is the only required member. It accepts one or more `string` paths or `URL` values. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:73-75](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L73-L75) - The interface is exported through the platform’s external-interface barrel. [packages/platform-fastify/interfaces/external/index.ts:1-3](packages/platform-fastify/interfaces/external/index.ts#L1-L3) - Calling `useStaticAssets(options)` loads `@fastify/static` and registers that plugin with the Fastify instance, passing `options` as the plugin options argument without transformations or field-level validation in this adapter method. [packages/platform-fastify/adapters/fastify-adapter.ts:526-532](packages/platform-fastify/adapters/fastify-adapter.ts#L526-L532) [packages/platform-fastify/adapters/fastify-adapter.ts:558-564](packages/platform-fastify/adapters/fastify-adapter.ts#L558-L564) Optional members declared directly on the interface are: - Routing and plugin settings: `prefix`, `prefixAvoidTrailingSlash`, `serve`, `decorateReply`, `schemaHide`, `redirect`, `wildcard`, and Fastify route `constraints`. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:75-82](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L75-L82) [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:105](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L105) - `setHeaders`, a callback that receives a response-shaped object, the path, and `fs.Stats`; the response object exposes `getHeader`, `setHeader`, read-only `filename`, and mutable `statusCode`. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:9-14](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L9-L14) [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:80](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L80) - `list`, which may be a boolean, JSON listing options, or HTML listing options. JSON options require `format: 'json'` and may include a renderer; HTML options require both `format: 'html'` and a renderer. Shared listing options contain required `names`, plus optional `extendedFolderInfo` and `jsonFormat`. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:42-57](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L42-L57) [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:83](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L83) - A listing renderer receives directory and file arrays and returns a string. Directory entries contain `href`, `name`, `Stats`, and optional extended aggregate information; file entries contain `href`, `name`, and `Stats`. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:16-40](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L16-L40) - `allowedPath`, a callback receiving `pathName`, the selected string root, and a `FastifyRequest`, returning a boolean. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:84-88](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L84-L88) - `preCompressed`, documented as opt-in to looking for pre-compressed files. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:89-93](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L89-L93) It extends the local `SendOptions` shape, adding optional `acceptRanges`, `cacheControl`, `dotfiles`, `etag`, `extensions`, `immutable`, `index`, `lastModified`, `maxAge`, and `serveDotFiles`. The source comments mark these as passed to `send`. [packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts:59-71](packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts#L59-L71) `@fastify/static` is an optional peer dependency of `@nestjs/platform-fastify`. [packages/platform-fastify/package.json:32-44](packages/platform-fastify/package.json#L32-L44) If its load callback throws, the package loader logs a message identifying the package and `FastifyAdapter.useStaticAssets()` context, flushes the logger, then exits the process with status `1`. [packages/platform-fastify/adapters/fastify-adapter.ts:558-562](packages/platform-fastify/adapters/fastify-adapter.ts#L558-L562) [packages/common/utils/load-package.util.ts:3-19](packages/common/utils/load-package.util.ts#L3-L19) # 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) ## Definition ```ts < TResult extends Observable = any, TResponse extends HeaderStream = any, TRequest extends IncomingMessage = any, >( result: TResult, res: TResponse, req: TRequest, ) => any ``` # KafkaController **Kind:** Controller **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L15) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ KafkaController client->>+p1: KafkaController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `mathSumSyncKafkaMessage` - MODULE_DECLARES β†’ `mathSumSyncWithoutKey` - MODULE_DECLARES β†’ `mathSumSyncPlainObject` - MODULE_DECLARES β†’ `mathSumSyncArray` - MODULE_DECLARES β†’ `mathSumSyncString` - MODULE_DECLARES β†’ `mathSumSyncNumber` - MODULE_DECLARES β†’ `sendNotification` - MODULE_DECLARES β†’ `createUser` - MODULE_DECLARES β†’ `createBusiness` # 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) ## Signature ```ts function loadPackage(packageName: string, context: string, loaderFn: Function) ``` ## Parameters | Name | Type | |---|---| | `packageName` | `string` | | `context` | `string` | | `loaderFn` | `Function` | # mathSumSyncArray **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L102) ## Endpoint `POST /mathSumSyncArray` ## Referenced By - `KafkaController` (MODULE_DECLARES) # 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) ## Values - `PAYLOAD` - `CONTEXT` - `GRPC_CALL` # ServerTCP **Kind:** Class **Source:** [`packages/microservices/server/server-tcp.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-tcp.ts#L33) `ServerTCP` is the TCP transport server used by the microservices layer to accept socket connections and route incoming packets to registered message handlers. It manages the server lifecycle, connection event listeners, message deserialization, handler execution, and graceful shutdown. **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] --> Server[ServerTCP] Server --> Listener[Node.js TCP Listener] Listener --> Bind[bindHandler] Bind --> Message[handleMessage] Message --> Handler[Registered Message Handler] Server --> Close[close / handleClose] ``` ## AI Coding Instructions - Register message handlers before calling `listen()` so incoming packets can be routed immediately. - Use transport-compatible message patterns, such as `{ cmd: 'ping' }`, consistently between TCP clients and handlers. - Do not call `bindHandler()` or `handleMessage()` directly; they are part of the connection and packet-processing lifecycle. - Always call `close()` during application shutdown to release the TCP listener and active resources cleanly. - Preserve the server’s serialization and deserialization flow when extending message handling behavior. # 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) 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. # Subscription **Kind:** Graphql Type **Source:** [`sample/12-graphql-schema-first/src/cats/cats.graphql`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.graphql#L1) ## Relationships - CALLS_API β†’ `catCreated` # Transient2Service **Kind:** Service **Source:** [`integration/injector/src/scoped/transient2.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/transient2.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ Transient2Service client->>+p1: Transient2Service p1-->client: return response ``` ## Referenced By - `ScopedModule` (MODULE_PROVIDES) - `TransientService` (DEPENDS_ON) # ApplicationConfig **Kind:** Class **Source:** [`packages/core/application-config.ts`](https://github.com/nestjs/nest/blob/master/packages/core/application-config.ts#L13) `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. # AppModule **Kind:** Module **Source:** [`sample/31-graphql-federation-code-first/gateway/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/gateway/src/app.module.ts#L6) # AProvider **Kind:** Service **Source:** [`integration/testing-module-override/circular-dependency/a.module.ts`](https://github.com/nestjs/nest/blob/master/integration/testing-module-override/circular-dependency/a.module.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ AProvider client->>+p1: AProvider p1-->client: return response ``` ## Referenced By - `AModule` (MODULE_PROVIDES) - `AModule` (MODULE_EXPORTS) # Logger **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L641) ## 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: … ``` # mathSumSyncKafkaMessage **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L55) ## Endpoint `POST /mathSumSyncKafkaMessage` ## Referenced By - `KafkaController` (MODULE_DECLARES) # 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) Interface defining the property object that describes the module. `ModuleMetadata` defines the configuration object used to describe a module and its dependencies. It groups imported modules, controllers, providers, and exported capabilities so the dependency injection system can assemble and expose module features correctly. This interface is commonly used when declaring static modules or creating dynamic module configurations. ## 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] M --> I[imports] M --> C[controllers] M --> P[providers] M --> E[exports] I --> IM[Modules / Dynamic Modules] I --> FR[Forward References] C --> CT[Controller Types] P --> PR[Injectable Providers] E --> EX[Public Providers / Modules / Tokens] ``` ## Usage ```ts import { ModuleMetadata, DynamicModule } 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], }; export class UsersModule { static register(): DynamicModule { return { module: UsersModule, ...usersModuleMetadata, }; } } ``` ## AI Coding Instructions - Add dependencies to `imports` only when the module needs providers exported by another module. - Register request handlers in `controllers` and injectable application services, factories, and values in `providers`. - Include a provider in `exports` only when consuming modules must inject or use it. - Use `forwardRef(() => OtherModule)` for circular module dependencies rather than importing the module directly. - Preserve provider tokens when exporting custom providers; export the same token used during registration. # MqttController **Kind:** Controller **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L16) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ MqttController client->>+p1: MqttController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `stream` - MODULE_DECLARES β†’ `concurrent` - MODULE_DECLARES β†’ `sendNotification` - MODULE_DECLARES β†’ `sendWildcardEvent` - MODULE_DECLARES β†’ `sendWildcardMessage` - MODULE_DECLARES β†’ `sendWildcardEvent2` - MODULE_DECLARES β†’ `sendWildcardMessage2` - MODULE_DECLARES β†’ `useRecordBuilderDuplex` - MODULE_DECLARES β†’ `sendSharedWildcardEvent` - MODULE_DECLARES β†’ `sendSharedWildcardMessage` - MODULE_DECLARES β†’ `sendSharedWildcardEvent2` - MODULE_DECLARES β†’ `sendSharedWildcardMessage2` # 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) 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. # STATIC_CONTEXT **Kind:** Constant **Source:** [`packages/core/injector/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/constants.ts#L6) ## Definition ```ts ContextId ``` ## Value ```ts Object.freeze({ id: STATIC_CONTEXT_ID, }) ``` # Subscription **Kind:** Graphql Type **Source:** [`sample/22-graphql-prisma/src/posts/schema.graphql`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/schema.graphql#L1) ## Relationships - CALLS_API β†’ `postCreated` # 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) ## Values - `SOCKET` - `PAYLOAD` - `ACK` # AppModule **Kind:** Module **Source:** [`sample/32-graphql-federation-schema-first/gateway/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/gateway/src/app.module.ts#L6) # BProvider **Kind:** Service **Source:** [`integration/testing-module-override/circular-dependency/b.module.ts`](https://github.com/nestjs/nest/blob/master/integration/testing-module-override/circular-dependency/b.module.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ BProvider client->>+p1: BProvider p1-->client: return response ``` ## Referenced By - `BModule` (MODULE_PROVIDES) - `BModule` (MODULE_EXPORTS) # ClientNats **Kind:** Class **Source:** [`packages/microservices/client/client-nats.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-nats.ts#L29) `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. # mathSumSyncNumber **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L121) ## Endpoint `POST /mathSumSyncNumber` ## Referenced By - `KafkaController` (MODULE_DECLARES) # 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) ## Definition ```ts | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy ``` # 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) ## Values - `MESSAGE` - `EVENT` # RMQController **Kind:** Controller **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L16) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RMQController client->>+p1: RMQController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `stream` - MODULE_DECLARES β†’ `concurrent` - MODULE_DECLARES β†’ `multipleUrls` - MODULE_DECLARES β†’ `useRecordBuilderDuplex` - MODULE_DECLARES β†’ `sendNotification` # Subscription **Kind:** Graphql Type **Source:** [`sample/23-graphql-code-first/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/schema.gql#L1) ## Relationships - CALLS_API β†’ `recipeAdded` # 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) Validation error description. `ValidationError` describes a validation failure for a specific property on an input object. It captures the invalid value, failed constraint messages, optional validation contexts, and nested child errors for validating complex or nested data structures. ## Properties | Property | Type | |---|---| | `target` | `Record` | | `property` | `string` | | `value` | `any` | | `constraints` | `{ [type: string]: string; }` | | `children` | `ValidationError[]` | | `contexts` | `{ [type: string]: any; }` | ## Diagram ```mermaid graph LR Target["target: Record"] --> Error["ValidationError"] Property["property: string"] --> Error Value["value: any"] --> Error Constraints["constraints: constraint β†’ message"] --> Error Contexts["contexts: constraint β†’ metadata"] --> Error Error --> Children["children: ValidationError[]"] Children --> Nested["Nested property errors"] ``` ## Usage ```ts interface ValidationError { target: Record; property: string; value: any; constraints: { [type: string]: string; }; children: ValidationError[]; contexts: { [type: string]: any; }; } const error: ValidationError = { target: { email: 'invalid-email' }, property: 'email', value: 'invalid-email', constraints: { isEmail: 'email must be a valid email address', }, children: [], contexts: { isEmail: { errorCode: 'INVALID_EMAIL', }, }, }; console.log(error.constraints.isEmail); // "email must be a valid email address" ``` ## AI Coding Instructions - Populate `property` with the field name being validated and `value` with the rejected input value. - Store constraint failures as a map of validator type to human-readable error message in `constraints`. - Use `children` for nested object or array validation errors instead of flattening nested paths manually. - Preserve `contexts` when available; consumers may use this metadata for error codes, localization, or API response formatting. - Avoid exposing sensitive values from `value` or `target` directly in client-facing validation responses. # 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) ## Signature ```ts function VERSIONED_CONTROLLER_MAPPING_MESSAGE(name: string, path: string, version: VersionValue) ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `path` | `string` | | `version` | `VersionValue` | # 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) ## Definition ```ts colorIfAllowed( (text: string) => `\x1B[38;5;3m${text}\x1B[39m`, ) ``` ## Value ```ts colorIfAllowed( (text: string) => `\x1B[38;5;3m${text}\x1B[39m`, ) ``` # AppController **Kind:** Controller **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L20) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController participant p2 as βš™οΈ ClientProxy client->>+p1: AppController p1->>+p2: ClientProxy p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `callWithClientUseFactory` - MODULE_DECLARES β†’ `callWithClientUseClass` - MODULE_DECLARES β†’ `stream` - MODULE_DECLARES β†’ `concurrent` - MODULE_DECLARES β†’ `serializeError` - MODULE_DECLARES β†’ `sendNotification` - DEPENDS_ON β†’ `ClientProxy` - DEPENDS_ON β†’ `ClientProxy` - DEPENDS_ON β†’ `ClientProxy` # AppModule **Kind:** Module **Source:** [`sample/05-sql-typeorm/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `usersmodule` # ChatService **Kind:** Service **Source:** [`integration/inspector/src/chat/chat.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/chat/chat.service.ts#L5) `ChatService` is a NestJS backend service that encapsulates chat-related business operations for the Inspector integration. It provides the standard create, read, update, and delete method surface used by controllers or other services to manage chat resources. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createChatDto: CreateChatDto)` | `unknown` | | `findAll` | `findAll()` | `unknown` | | `findOne` | `findOne(id: number)` | `unknown` | | `update` | `update(id: number, updateChatDto: UpdateChatDto)` | `unknown` | | `remove` | `remove(id: number)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as ChatController participant Service as ChatService participant Store as Data Store Client->>Controller: Request chat operation Controller->>Service: create/findAll/findOne/update/remove Service->>Store: Read or modify chat data Store-->>Service: Chat result(s) Service-->>Controller: Return result Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ChatService } from './chat.service'; @Injectable() export class ChatController { constructor(private readonly chatService: ChatService) {} async createChat() { return this.chatService.create(); } async getChats() { return this.chatService.findAll(); } async getChat() { return this.chatService.findOne(); } async updateChat() { return this.chatService.update(); } async deleteChat() { return this.chatService.remove(); } } ``` ## AI Coding Instructions - Keep chat business logic in `ChatService`; controllers should only handle request parsing and HTTP response concerns. - Preserve the existing CRUD method structure: `create`, `findAll`, `findOne`, `update`, and `remove`. - Add explicit DTOs, identifiers, and return types when implementing service behavior rather than leaving methods untyped. - Integrate persistence, validation, and external chat providers behind the service boundary so callers do not depend on implementation details. - Ensure `findOne`, `update`, and `remove` handle missing chat records consistently, typically by throwing NestJS `NotFoundException`. ## Referenced By - `ChatModule` (MODULE_PROVIDES) # 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) 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. # CONNECTION_FAILED_MESSAGE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L59) ## Definition ```ts 'Connection to transport failed. Trying to reconnect...' ``` ## Value ```ts 'Connection to transport failed. Trying to reconnect...' ``` # mathSumSyncNumberWait **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts#L60) ## Endpoint `POST /mathSumSyncNumberWait` ## Referenced By - `KafkaConcurrentController` (MODULE_DECLARES) # 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) ## Definition ```ts { metadata: { type: 'module'; global: boolean; dynamic: boolean; internal: boolean; }; } ``` # ServerNats **Kind:** Class **Source:** [`packages/microservices/server/server-nats.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-nats.ts#L38) `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. # Subscription **Kind:** Graphql Type **Source:** [`sample/33-graphql-mercurius/schema.gql`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/schema.gql#L1) ## Relationships - CALLS_API β†’ `recipeAdded` # TcpStatus **Kind:** Enum **Source:** [`packages/microservices/events/tcp.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/tcp.events.ts#L10) ## Values - `DISCONNECTED` - `CONNECTED` # 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) ## Signature ```ts function VERSIONED_ROUTE_MAPPED_MESSAGE(path: string, method: string | number, version: VersionValue) ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | | `method` | `string | number` | | `version` | `VersionValue` | # AppController **Kind:** Controller **Source:** [`sample/29-file-upload/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.controller.ts#L15) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `sayHello` - MODULE_DECLARES β†’ `uploadFile` - MODULE_DECLARES β†’ `uploadFileAndPassValidation` - MODULE_DECLARES β†’ `uploadFileAndFailValidation` - DEPENDS_ON β†’ `appservice` # AppModule **Kind:** Module **Source:** [`sample/07-sequelize/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `usersmodule` # 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) `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. # 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) ## Signature ```ts function extendArrayMetadata(key: string, metadata: T, target: Function) ``` ## Parameters | Name | Type | |---|---| | `key` | `string` | | `metadata` | `T` | | `target` | `Function` | # 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) ## Definition ```ts '__fastify_route_constraints__' ``` ## Value ```ts '__fastify_route_constraints__' ``` # mathSumSyncPlainObject **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L88) ## Endpoint `POST /mathSumSyncPlainObject` ## Referenced By - `KafkaController` (MODULE_DECLARES) # PartitionMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L151) ## Definition ```ts { partitionErrorCode: number; partitionId: number; leader: number; replicas: number[]; isr: number[]; offlineReplicas?: number[]; } ``` # TasksService **Kind:** Service **Source:** [`sample/27-scheduling/src/tasks/tasks.service.ts`](https://github.com/nestjs/nest/blob/master/sample/27-scheduling/src/tasks/tasks.service.ts#L4) `TasksService` demonstrates scheduled task execution in a NestJS backend. It owns cron, interval, and timeout handlers, allowing the application to run recurring or delayed background work through NestJS scheduling decorators. ## Methods | Method | Signature | Returns | |---|---|---| | `handleCron` | `handleCron()` | `unknown` | | `handleInterval` | `handleInterval()` | `unknown` | | `handleTimeout` | `handleTimeout()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Scheduler as NestJS Scheduler participant Service as TasksService participant App as Application Logic Scheduler->>Service: handleCron() at configured cron schedule Service->>App: Execute recurring task loop At configured interval Scheduler->>Service: handleInterval() Service->>App: Execute repeating task end Scheduler->>Service: handleTimeout() after configured delay Service->>App: Execute one-time delayed task ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { Cron, Interval, Timeout } from '@nestjs/schedule'; @Injectable() export class TasksService { @Cron('45 * * * * *') handleCron() { console.log('Cron task executed'); } @Interval(10_000) handleInterval() { console.log('Interval task executed every 10 seconds'); } @Timeout(5_000) handleTimeout() { console.log('Timeout task executed once after startup'); } } // Ensure ScheduleModule is registered in the application module: // imports: [ScheduleModule.forRoot()] ``` ## AI Coding Instructions - Register `ScheduleModule.forRoot()` once in the root module before using scheduling decorators. - Keep scheduled handlers lightweight; delegate expensive work to dedicated services, queues, or background workers. - Use `@Cron`, `@Interval`, and `@Timeout` decorators for declarative scheduling rather than manually creating timers. - Add error handling and structured logging inside task handlers so failures do not silently interrupt background operations. - Prevent overlapping executions for long-running interval or cron jobs when concurrent runs could cause duplicate work. ## Referenced By - `TasksModule` (MODULE_PROVIDES) # UuidFactoryMode **Kind:** Enum **Source:** [`packages/core/inspector/uuid-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/uuid-factory.ts#L4) ## Values - `Random` - `Deterministic` # 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) `WsAdapter` is Nest’s WebSocket adapter for the `ws` library. It creates and manages WebSocket servers, routes incoming messages to gateway handlers, supports custom message parsing, and coordinates cleanup when the application shuts down. **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 --> Server[ws WebSocket Server] Client[WebSocket Client] -->|message| Server Server --> Parser[Message Parser] Parser --> Handlers[Gateway Message Handlers] Handlers --> Transform[Response Transform] Transform --> Client Client -->|close| Disconnect[Disconnect Handler] Adapter --> Registry[WebSocket Server Registry] ``` ## 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); const wsAdapter = new WsAdapter(app); // Optional: support a custom incoming message format. wsAdapter.setMessageParser((buffer) => { const payload = JSON.parse(buffer.toString()); return { event: payload.type, data: payload.payload, }; }); app.useWebSocketAdapter(wsAdapter); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Use `WsAdapter` through `app.useWebSocketAdapter()` so Nest can connect gateway metadata and lifecycle hooks to the `ws` server. - Incoming messages must parse into an object containing `event` and `data`; use `setMessageParser()` when clients use a different payload format. - Prefer Nest gateway decorators such as `@SubscribeMessage()` rather than calling `bindMessageHandlers()` directly. - Ensure custom WebSocket server instances are closed through application shutdown or `dispose()` to prevent open sockets and port conflicts. - When creating servers manually, preserve the adapter’s error and disconnect handling patterns via `bindErrorHandler()` and `bindClientDisconnect()`. ## How it works ## `WsAdapter` `WsAdapter` is the public WebSocket adapter for `@nestjs/platform-ws`. It extends Nest’s `AbstractWsAdapter` and loads the `ws` package when constructed. [packages/platform-ws/adapters/ws-adapter.ts:36-63] [packages/websockets/adapters/ws-adapter.ts:13-35] Its constructor accepts an optional Nest application context or HTTP-server object, which the base class stores as the underlying HTTP server; when passed a `NestApplication`, the base class obtains that application’s underlying HTTP server. [packages/platform-ws/adapters/ws-adapter.ts:53-58] [packages/websockets/adapters/ws-adapter.ts:29-35] An optional `messageParser` constructor option replaces the default parser. [packages/platform-ws/adapters/ws-adapter.ts:30-32] [packages/platform-ws/adapters/ws-adapter.ts:60-62] # AppModule **Kind:** Module **Source:** [`sample/26-queues/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/26-queues/src/app.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `AudioController` - MODULE_PROVIDES β†’ `AudioProcessor` # 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) `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. # FooService **Kind:** Service **Source:** [`integration/auto-mock/src/foo.service.ts`](https://github.com/nestjs/nest/blob/master/integration/auto-mock/src/foo.service.ts#L3) `FooService` is a NestJS service that exposes the `foo()` method for use by other providers, controllers, or integration tests. It acts as an injectable backend dependency and is located in the auto-mock integration area, making it useful for validating service discovery and mocking behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `foo` | `foo()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller / Consumer participant DI as NestJS DI Container participant FooService as FooService Consumer->>DI: Request FooService dependency DI-->>Consumer: Inject FooService instance Consumer->>FooService: foo() FooService-->>Consumer: unknown result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { FooService } from './foo.service'; @Injectable() export class ExampleService { constructor(private readonly fooService: FooService) {} execute() { const result = this.fooService.foo(); return result; } } ``` ## AI Coding Instructions - Inject `FooService` through NestJS constructor injection instead of creating it manually with `new`. - Preserve the `foo(): unknown` contract unless callers require a more specific return type. - Register `FooService` in the appropriate NestJS module's `providers` array before injecting it. - When testing consumers, mock `FooService` through the NestJS testing module or the repository's auto-mock utilities. ## Referenced By - `BarService` (DEPENDS_ON) # getGrpcPackageDefinition **Kind:** Function **Source:** [`packages/microservices/helpers/grpc-helpers.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/grpc-helpers.ts#L5) ## Signature ```ts function getGrpcPackageDefinition(options: GrpcOptions['options'], grpcProtoLoaderPackage: any) ``` ## Parameters | Name | Type | |---|---| | `options` | `GrpcOptions['options']` | | `grpcProtoLoaderPackage` | `any` | # 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) 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. # KafkaConcurrentController **Kind:** Controller **Source:** [`integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts#L24) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ KafkaConcurrentController client->>+p1: KafkaConcurrentController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `mathSumSyncNumberWait` # mathSumSyncString **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L111) ## Endpoint `POST /mathSumSyncString` ## Referenced By - `KafkaController` (MODULE_DECLARES) # ModuleRef **Kind:** Class **Source:** [`packages/core/injector/module-ref.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/module-ref.ts#L26) `ModuleRef` provides programmatic access to the dependency injection container from within an application module. Use it to retrieve registered providers with `get()`, resolve scoped or transient providers with `resolve()`, or instantiate a class with its dependencies using `create()`. **Extends:** `AbstractInstanceResolver` ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(typeOrToken: Type | Function | string | symbol)` | `TResult` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: { /** * If enabled, lookup will only be performed in the host module. * @default true */ strict?: boolean; /** This indicates that only the first instance registered will be returned. */ each?: undefined | false; })` | `TResult` | | `get` | `get(typeOrToken: Type | Function | string | symbol, options: { /** * If enabled, lookup will only be performed in the host module. * @default true */ strict?: boolean; /** This indicates that a list of instances will be returned. */ 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 A[Consumer Service] --> B[ModuleRef] B -->|get()| C[Existing Singleton Provider] B -->|resolve()| D[Scoped / Transient Provider] B -->|create()| E[New Class Instance] C --> F[DI Container] D --> F E --> F ``` ## 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 provider from the current module context. const logger = this.moduleRef.get(AppLogger); // Resolve a transient or request-scoped provider. const reportBuilder = await this.moduleRef.resolve(ReportBuilder); // Create a class and inject its registered dependencies. const exporter = await this.moduleRef.create(CsvExporter); logger.log('Generating report'); const report = await reportBuilder.build(); return exporter.export(report); } } ``` ## AI Coding Instructions - Prefer constructor injection for known dependencies; use `ModuleRef` when dependencies must be selected or created dynamically. - Use `get()` for already-instantiated singleton/static providers and `resolve()` for transient or request-scoped providers. - Pass `{ strict: false }` to `get()` or `resolve()` only when intentionally searching providers outside the current module. - Ensure tokens passed to `get()` and `resolve()` are registered providers, injection tokens, or supported class references. - Use `create()` for classes that are not registered as providers but still require dependencies from the DI container. # RedisEvents **Kind:** Type **Source:** [`packages/microservices/events/redis.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/redis.events.ts#L26) 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. # AppModule **Kind:** Module **Source:** [`integration/graphql-code-first/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/app.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `recipesmodule` # CatSchema **Kind:** Constant **Source:** [`integration/mongoose/src/cats/schemas/cat.schema.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/schemas/cat.schema.ts#L3) ## Definition ```ts new mongoose.Schema({ name: String, age: Number, breed: String, }) ``` ## Value ```ts new mongoose.Schema({ name: String, age: Number, breed: String, }) ``` # 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) 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. # 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) ## Signature ```ts function getInjectionProviders(providers: Provider[], tokens: FactoryProvider['inject']): Provider[] ``` ## Parameters | Name | Type | |---|---| | `providers` | `Provider[]` | | `tokens` | `FactoryProvider['inject']` | **Returns:** `Provider[]` # InjectService **Kind:** Service **Source:** [`integration/injector/src/inject/inject.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/inject/inject.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ InjectService client->>+p1: InjectService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `coreservice` ## Referenced By - `InjectModule` (MODULE_PROVIDES) # KafkaMessagesController **Kind:** Controller **Source:** [`integration/microservices/src/kafka/kafka.messages.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.messages.controller.ts#L9) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ KafkaMessagesController client->>+p1: KafkaMessagesController p1-->client: return response ``` # mathSumSyncWithoutKey **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L72) ## Endpoint `POST /mathSumSyncWithoutKey` ## Referenced By - `KafkaController` (MODULE_DECLARES) # 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) `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. # TcpEvents **Kind:** Type **Source:** [`packages/microservices/events/tcp.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/tcp.events.ts#L31) 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. # AdminEvents **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L389) ## 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'; } ``` # AppModule **Kind:** Module **Source:** [`sample/13-mongo-typeorm/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/13-mongo-typeorm/src/app.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `photomodule` # CatSchema **Kind:** Constant **Source:** [`sample/14-mongoose-base/src/cats/schemas/cat.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/schemas/cat.schema.ts#L3) ## Definition ```ts new mongoose.Schema({ name: String, age: Number, breed: String, }) ``` ## Value ```ts new mongoose.Schema({ name: String, age: Number, breed: String, }) ``` # 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) "fastify/view" interfaces `FastifyViewOptions` defines the configuration accepted by the Fastify view integration. It selects a template engine, configures template lookup and rendering behavior, and provides defaults such as layouts, encoding, caching, and shared template context. ## 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[options] A --> E[defaultContext] A --> F[layout] A --> G[Rendering behavior] B --> B1[ejs / eta / nunjucks] B --> B2[pug / handlebars / mustache] B --> B3[twig / liquid / dot] C --> C1[Template files] D --> D1[Engine-specific settings] G --> G1[includeViewExtension] G --> G2[charset] G --> G3[maxCache] G --> G4[production] ``` ## Usage ```ts import type { FastifyViewOptions } from './interfaces/external/fastify-view-options.interface'; import ejs from 'ejs'; const viewOptions: FastifyViewOptions = { engine: { ejs, }, root: `${process.cwd()}/views`, layout: 'layouts/main.ejs', includeViewExtension: true, templates: ['views/**/*.ejs'], options: { cache: true, }, charset: 'utf-8', maxCache: 100, production: process.env.NODE_ENV === 'production', defaultContext: { applicationName: 'My Fastify App', }, }; ``` ## AI Coding Instructions - Provide exactly one or more engine implementations under `engine`; the selected engine must match the extensions used by your templates. - Set `root` to the directory containing view files, and use `templates` when the integration needs explicit template paths or glob patterns. - Keep engine-specific configuration inside `options` rather than adding unsupported top-level properties. - Enable `production` and configure `maxCache` appropriately for deployed environments; avoid excessive caching during local development. - Use `defaultContext` for shared template values and `layout` for the default wrapper template when the selected engine supports layouts. # 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) `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. # HttpException **Kind:** Class **Source:** [`packages/common/exceptions/http.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts#L27) 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. # LazyService **Kind:** Service **Source:** [`integration/lazy-modules/src/lazy.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/lazy.module.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ LazyService participant p2 as βš™οΈ GlobalService client->>+p1: LazyService p1->>+p2: GlobalService p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `GlobalService` ## Referenced By - `LazyModule` (MODULE_PROVIDES) # multipleUrls **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L64) ## Endpoint `POST /multiple-urls` ## Referenced By - `RMQController` (MODULE_DECLARES) # NatsController **Kind:** Controller **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L19) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ NatsController participant p2 as βš™οΈ NatsService client->>+p1: NatsController p1->>+p2: NatsService p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `stream` - MODULE_DECLARES β†’ `concurrent` - MODULE_DECLARES β†’ `useRecordBuilderDuplex` - MODULE_DECLARES β†’ `getError` - MODULE_DECLARES β†’ `sendNotification` - DEPENDS_ON β†’ `NatsService` # AppModule **Kind:** Module **Source:** [`sample/24-serve-static/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/24-serve-static/src/app.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # catsProviders **Kind:** Constant **Source:** [`sample/14-mongoose-base/src/cats/cats.providers.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/cats.providers.ts#L4) ## Definition ```ts [ { provide: 'CAT_MODEL', useFactory: (mongoose: Mongoose) => mongoose.model('Cat', CatSchema), inject: ['DATABASE_CONNECTION'], }, ] ``` ## Value ```ts [ { provide: 'CAT_MODEL', useFactory: (mongoose: Mongoose) => mongoose.model('Cat', CatSchema), inject: ['DATABASE_CONNECTION'], }, ] ``` # 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) ## Definition ```ts | Array | { clients: Array; isGlobal?: boolean; } ``` # 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) `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. # 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) `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. # 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) `KafkaOptions` configures a NestJS microservice or client that communicates through Apache Kafka using KafkaJS. It defines Kafka client, consumer, producer, subscription, serialization, and message-processing behavior, while allowing separate settings for server-side consumers and producer-only clients. ## Properties | Property | Type | |---|---| | `transport` | `Transport.KAFKA` | | `options` | `{ /** * Defaults to `"-server"` on server side and `"-client"` on client side. */ postfixId?: string; client?: KafkaConfig; consumer?: ConsumerConfig; /** * Options passed to KafkaJS consumer.run(). * Note: `partitionsConsumedConcurrently` (KafkaJS parameter) controls * concurrent processing at the partition level (not topic level). */ 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[postfixId] C --> E[client: KafkaConfig] C --> F[consumer: ConsumerConfig] C --> G[run: ConsumerRunConfig] C --> H[subscribe: ConsumerSubscribeTopics] C --> I[producer: ProducerConfig] C --> J[send: ProducerRecord] C --> K[serializer] C --> L[deserializer] C --> M[parser: KafkaParserConfig] C --> N[producerOnlyMode] E --> O[Kafka Broker Connection] F --> P[Kafka Consumer] I --> Q[Kafka Producer] P --> R[Subscribed Topics] Q --> S[Published Messages] ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import type { KafkaOptions } from '@nestjs/microservices'; const kafkaOptions: KafkaOptions = { transport: Transport.KAFKA, options: { client: { clientId: 'billing-service', brokers: ['localhost:9092'], }, consumer: { groupId: 'billing-service-consumers', }, subscribe: { fromBeginning: false, }, run: { partitionsConsumedConcurrently: 3, }, producer: { allowAutoTopicCreation: true, }, }, }; // Example server registration: // NestFactory.createMicroservice(AppModule, kafkaOptions); ``` ## AI Coding Instructions - Always set `transport` to `Transport.KAFKA`; Kafka-specific settings belong under `options`. - Provide a stable, unique `consumer.groupId` for consumer-based services to avoid unintended message processing behavior. - Use `run.partitionsConsumedConcurrently` to increase parallelism across partitions, not across topics. - Do not provide `eachMessage` or `eachBatch` in `run`; NestJS manages KafkaJS message handlers internally. - Enable `producerOnlyMode` for clients that only publish messages and should not create or run a Kafka consumer. # LoggerService **Kind:** Service **Source:** [`integration/scopes/src/resolve-scoped/logger.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/resolve-scoped/logger.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ LoggerService client->>+p1: LoggerService p1-->client: return response ``` ## Referenced By - `RequestLoggerService` (DEPENDS_ON) # RedisController **Kind:** Controller **Source:** [`integration/microservices/src/redis/redis.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis.controller.ts#L12) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RedisController client->>+p1: RedisController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` - MODULE_DECLARES β†’ `stream` - MODULE_DECLARES β†’ `concurrent` - MODULE_DECLARES β†’ `sendNotification` # releaseInterceptorDelayedSse **Kind:** API Endpoint **Source:** [`integration/nest-application/sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.controller.ts#L201) ## Endpoint `POST /sse/interceptor/promise-delayed/release` ## Referenced By - `AppController` (MODULE_DECLARES) # AppController **Kind:** Controller **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getFile` - MODULE_DECLARES β†’ `getBuffer` - MODULE_DECLARES β†’ `getNonFile` - MODULE_DECLARES β†’ `getRxJSFile` - MODULE_DECLARES β†’ `getFileWithHeaders` - MODULE_DECLARES β†’ `getNonExistantFile` - MODULE_DECLARES β†’ `getSlowFile` - DEPENDS_ON β†’ `appservice` # AppModule **Kind:** Module **Source:** [`sample/12-graphql-schema-first/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/app.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # 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) ## Definition ```ts | Array | { clients: Array; isGlobal?: boolean; } ``` # databaseProviders **Kind:** Constant **Source:** [`sample/14-mongoose-base/src/database/database.providers.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/database/database.providers.ts#L3) ## Definition ```ts [ { provide: 'DATABASE_CONNECTION', useFactory: async (): Promise => await mongoose.connect('mongodb://localhost/test'), }, ] ``` ## Value ```ts [ { provide: 'DATABASE_CONNECTION', useFactory: async (): Promise => await mongoose.connect('mongodb://localhost/test'), }, ] ``` # 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) `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. # 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) # NatsService **Kind:** Service **Source:** [`integration/microservices/src/nats/nats.service.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ NatsService client->>+p1: NatsService p1-->client: return response ``` ## Referenced By - `NatsController` (DEPENDS_ON) # releaseSsePromiseDelayed **Kind:** API Endpoint **Source:** [`integration/nest-application/sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.controller.ts#L131) ## Endpoint `POST /sse/promise-delayed/release` ## Referenced By - `AppController` (MODULE_DECLARES) # WebSocketsController **Kind:** Class **Source:** [`packages/websockets/web-sockets-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/web-sockets-controller.ts#L29) `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) # AppController **Kind:** Controller **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - MODULE_DECLARES β†’ `getParams` - MODULE_DECLARES β†’ `getHealth` - MODULE_DECLARES β†’ `getTest` - MODULE_DECLARES β†’ `postTest` - MODULE_DECLARES β†’ `getHome` - MODULE_DECLARES β†’ `getCount` # AppModule **Kind:** Module **Source:** [`sample/33-graphql-mercurius/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/app.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `recipesmodule` # 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) Factory that lets you create configurable modules and provides a way to reduce the majority of dynamic module boilerplate. `ConfigurableModuleBuilder` creates the boilerplate required for NestJS configurable modules, including typed options injection, synchronous registration, and asynchronous registration APIs. Use it when building reusable modules that need consumer-provided configuration without manually implementing dynamic module factories. ## 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 extra options] B --> D[build()] C --> D D --> E[ConfigurableModuleClass] D --> F[MODULE_OPTIONS_TOKEN] E --> G[forRoot / register methods] G --> H[DynamicModule definition] H --> I[Consumer application module] ``` ## Usage ```ts import { Module, ConfigurableModuleBuilder } from '@nestjs/common'; export interface ConfigModuleOptions { folder: string; cache?: boolean; } const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, } = new ConfigurableModuleBuilder() .setClassMethodName('forRoot') .setFactoryMethodName('createConfigOptions') .setExtras( { isGlobal: false }, (definition, extras) => ({ ...definition, global: extras.isGlobal, }), ) .build(); @Module({}) export class ConfigModule extends ConfigurableModuleClass {} // App module usage @Module({ imports: [ ConfigModule.forRoot({ folder: './config', cache: true, isGlobal: true, }), ], }) export class AppModule {} // Inject options within providers in ConfigModule // @Inject(MODULE_OPTIONS_TOKEN) private readonly options: ConfigModuleOptions ``` ## AI Coding Instructions - Create one builder per configurable module and export the generated `ConfigurableModuleClass` and `MODULE_OPTIONS_TOKEN` when consumers or internal providers need them. - Use `setClassMethodName()` to expose domain-appropriate APIs such as `forRoot`, `register`, or `configure`; keep the chosen name consistent in documentation and module imports. - Use `setExtras()` only for dynamic module definition concerns, such as `global`, exports, or imports; keep runtime module options in the main options interface. - Extend `ConfigurableModuleClass` with `@Module()` metadata rather than manually recreating `register()` or `registerAsync()` methods. - Inject configuration through `MODULE_OPTIONS_TOKEN` instead of relying on hard-coded configuration values inside providers. # 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) 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. # grpcClientOptions **Kind:** Constant **Source:** [`sample/04-grpc/src/grpc-client.options.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/grpc-client.options.ts#L5) ## Definition ```ts GrpcOptions ``` ## Value ```ts { transport: Transport.GRPC, options: { package: 'hero', // ['hero', 'hero2'] protoPath: join(__dirname, './hero/hero.proto'), // ['./hero/hero.proto', './hero/hero2.proto'] onLoadPackageDefinition: (pkg, server) => { new ReflectionService(pkg).addToServer(server); }, }, } ``` # 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) 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. # 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) `MqttOptions` configures a NestJS microservice that communicates through the MQTT transport. It combines standard MQTT client settings with Nest-specific serialization, deserialization, subscription behavior, and MQTT v5 user properties. ## Properties | Property | Type | |---|---| | `transport` | `Transport.MQTT` | | `options` | `MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; subscribeOptions?: { /** * The QoS */ qos: QoS; /* * No local flag * */ nl?: boolean; /* * Retain as Published flag * */ rap?: boolean; /* * Retain Handling option * */ rh?: number; }; userProperties?: Record; }` | ## Diagram ```mermaid graph LR A[MqttOptions] --> B[transport: Transport.MQTT] A --> C[options] C --> D[MqttClientOptions] C --> E[url] C --> F[serializer / deserializer] C --> G[subscribeOptions] C --> H[userProperties] G --> I[qos] G --> J[nl, rap, rh] D --> K[MQTT Broker Connection] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { Transport, type MqttOptions } from '@nestjs/microservices'; import { AppModule } from './app.module'; const mqttOptions: MqttOptions = { transport: Transport.MQTT, options: { url: 'mqtt://localhost:1883', clientId: 'orders-service', username: 'orders-service', password: process.env.MQTT_PASSWORD, subscribeOptions: { qos: 1, nl: false, rap: true, rh: 0, }, userProperties: { service: 'orders', environment: process.env.NODE_ENV ?? 'development', }, }, }; async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, mqttOptions); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Always set `transport` to `Transport.MQTT`; this interface is intended only for MQTT microservice configurations. - Put broker connection settings such as `url`, `clientId`, credentials, TLS options, and reconnect settings inside `options`. - Configure `subscribeOptions.qos` explicitly when message delivery guarantees matter; valid MQTT QoS levels are typically `0`, `1`, and `2`. - Use custom `serializer` and `deserializer` only when both message producers and consumers agree on the payload format. - Treat `userProperties` as MQTT v5 metadata and verify that the selected broker and client configuration support MQTT v5 features. # ScopedService **Kind:** Service **Source:** [`integration/injector/src/scoped/scoped.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/scoped.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ ScopedService client->>+p1: ScopedService p1-->client: return response ``` ## Referenced By - `ScopedModule` (MODULE_PROVIDES) # serializeError **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc/grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc/grpc.controller.ts#L163) ## Endpoint `POST /error` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `client` | query | `'custom' | 'standard'` | - | | ## Referenced By - `GrpcController` (MODULE_DECLARES) # 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) ## Signature ```ts function AnyFilesInterceptor(localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `localOptions` | `MulterOptions` | **Returns:** `Type` # AppController **Kind:** Controller **Source:** [`sample/28-sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/28-sse/src/app.controller.ts#L8) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `index` # AppModule **Kind:** Module **Source:** [`integration/graphql-schema-first/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/app.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # ConsumerCommitOffsetsEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L933) ## Definition ```ts InstrumentationEvent<{ groupId: string; memberId: string; groupGenerationId: number; topics: TopicOffsets[]; }> ``` # ListenersController **Kind:** Class **Source:** [`packages/microservices/listeners-controller.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listeners-controller.ts#L45) `ListenersController` is Nest microservices infrastructure that discovers `@MessagePattern()` and `@EventPattern()` handlers, then registers them with a transport server. It also injects client proxies, creates request-scoped handlers when needed, and normalizes handler return values 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[Microservice bootstrap] --> B[ListenersController] B --> C[Discover controller patterns] C --> D[Register request handlers] C --> E[Register event handlers] B --> F[Assign @Client() proxies] D --> G[Create request-scoped handler] D --> H[Transform result to Observable] E --> H H --> I[Microservice transport server] ``` ## Usage ```ts import { Controller } from '@nestjs/common'; import { EventPattern, MessagePattern, Payload } from '@nestjs/microservices'; import { NestFactory } from '@nestjs/core'; import { Transport } from '@nestjs/microservices'; import { AppModule } from './app.module'; @Controller() class OrdersController { @MessagePattern('orders.find-one') findOne(@Payload() id: string) { return { id, status: 'created' }; } @EventPattern('orders.created') handleOrderCreated(@Payload() order: { id: string }) { console.log(`Received order event: ${order.id}`); } } async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, }); // During startup, Nest uses ListenersController internally to discover // and register the MessagePattern/EventPattern handlers above. await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Treat `ListenersController` as framework infrastructure; prefer defining handlers with `@MessagePattern()` and `@EventPattern()` rather than calling its registration methods directly. - Ensure pattern handlers return values, promises, or RxJS observables; `transformToObservable()` normalizes these results before sending transport responses. - Preserve request-scoped provider behavior when changing handler creation logic; `createRequestScopedHandler()` is responsible for resolving dependencies per incoming message context. - Keep client-proxy assignment compatible with `@Client()`-decorated properties, as `assignClientsToProperties()` and `assignClientToInstance()` perform this integration during initialization. - When adding transport behavior, account for both request/response handlers and event handlers, including concurrent event processing through `forkJoinHandlersIfAttached()`. # loggerProvider **Kind:** Constant **Source:** [`integration/scopes/src/resolve-scoped/logger.provider.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/resolve-scoped/logger.provider.ts#L4) ## Definition ```ts FactoryProvider ``` ## Value ```ts { provide: LOGGER_PROVIDER, useFactory: () => { return { logger: true }; }, } ``` # 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) `MqttRecordOptions` defines MQTT delivery flags and MQTT v5 message properties used when building a record for publication. It controls the message QoS, retention and duplicate-delivery flags, while providing a structured container for optional protocol metadata such as expiry, 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 A[MqttRecordOptions] --> B[qos: 0 | 1 | 2] A --> C[retain: boolean] A --> D[dup: boolean] A --> E[properties] E --> F[payloadFormatIndicator] E --> G[messageExpiryInterval] E --> H[topicAlias] E --> I[responseTopic] E --> J[correlationData: Buffer] E --> K[userProperties] E --> L[subscriptionIdentifier] E --> M[contentType] ``` ## 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-456'), userProperties: { source: 'telemetry-service', tags: ['temperature', 'production'], }, }, }; // Pass options to the MQTT record builder/publish integration. const record = mqttRecordBuilder.build({ topic: 'devices/device-123/telemetry', payload: JSON.stringify({ temperature: 21.5 }), options, }); ``` ## AI Coding Instructions - Use only `0`, `1`, or `2` for `qos`; select QoS 1 or 2 only when the delivery guarantees justify their overhead. - Set `retain` only for messages that should represent the latest state for newly subscribing clients. - Preserve `dup` when retrying a previously sent MQTT message; do not set it for first-delivery attempts. - Keep MQTT v5 metadata inside `properties`, and use `Buffer` for binary `correlationData`. - Validate broker-supported property values, especially `topicAlias`, `subscriptionIdentifier`, and `messageExpiryInterval`, before publishing. # serializeError **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L80) ## Endpoint `POST /error` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `client` | query | `'custom' | 'standard'` | - | | ## Referenced By - `AppController` (MODULE_DECLARES) # ServiceInjectingItselfForward **Kind:** Service **Source:** [`integration/injector/src/self-injection/self-injection-provider.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/self-injection/self-injection-provider.module.ts#L8) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ ServiceInjectingItselfForward participant p2 as βš™οΈ ServiceInjectingItself client->>+p1: ServiceInjectingItselfForward p1->>+p2: ServiceInjectingItself p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `ServiceInjectingItself` ## Referenced By - `SelfInjectionForwardProviderModule` (MODULE_PROVIDES) # AppModule **Kind:** Module **Source:** [`sample/22-graphql-prisma/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/app.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `postsmodule` # AppV2Controller **Kind:** Controller **Source:** [`integration/inspector/src/app-v2.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app-v2.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppV2Controller client->>+p1: AppV2Controller p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `helloWorldV2` - MODULE_DECLARES β†’ `paramV1` # 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) ## Signature ```ts function compareElementAt(prev: unknown[], curr: unknown[], index: number) ``` ## Parameters | Name | Type | |---|---| | `prev` | `unknown[]` | | `curr` | `unknown[]` | | `index` | `number` | # ConsumerGroup **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L838) ## Definition ```ts { groupId: string; generationId: number; memberId: string; coordinator: Broker; } ``` # dynamicProvider **Kind:** Constant **Source:** [`integration/injector/src/dynamic/dynamic.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/dynamic/dynamic.module.ts#L6) ## Definition ```ts { provide: DYNAMIC_TOKEN, useValue: DYNAMIC_VALUE, } ``` ## Value ```ts { provide: DYNAMIC_TOKEN, useValue: DYNAMIC_VALUE, } ``` # GraphInspector **Kind:** Class **Source:** [`packages/core/inspector/graph-inspector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/graph-inspector.ts#L13) `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. # 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) `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. # serializeError **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L93) ## Endpoint `POST /error` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `client` | query | `'custom' | 'standard'` | - | | ## Referenced By - `AppController` (MODULE_DECLARES) # ServiceInjectingItselfViaCustomToken **Kind:** Service **Source:** [`integration/injector/src/self-injection/self-injection-provider.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/self-injection/self-injection-provider.module.ts#L16) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ ServiceInjectingItselfViaCustomToken client->>+p1: ServiceInjectingItselfViaCustomToken p1-->client: return response ``` ## Referenced By - `SelfInjectionProviderCustomTokenModule` (MODULE_PROVIDES) # AppModule **Kind:** Module **Source:** [`integration/lazy-modules/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/app.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `GlobalModule` - MODULE_IMPORTS β†’ `EagerModule` # CatsController **Kind:** Controller **Source:** [`sample/06-mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.controller.ts#L7) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `update` - MODULE_DECLARES β†’ `delete` - DEPENDS_ON β†’ `catsservice` # ConsumerGroupState **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L854) ## Definition ```ts | 'Unknown' | 'PreparingRebalance' | 'CompletingRebalance' | 'Stable' | 'Dead' | 'Empty' ``` # 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) ## Signature ```ts function getBodyParserOptions(rawBody: boolean, options: Omit): Options ``` ## Parameters | Name | Type | |---|---| | `rawBody` | `boolean` | | `options` | `Omit` | **Returns:** `Options` # jwtConstants **Kind:** Constant **Source:** [`sample/19-auth-jwt/src/auth/constants.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/constants.ts#L1) ## Definition ```ts { secret: 'DO NOT USE THIS VALUE. INSTEAD, CREATE A COMPLEX SECRET AND KEEP IT SAFE OUTSIDE OF THE SOURCE CODE.', } ``` ## Value ```ts { secret: 'DO NOT USE THIS VALUE. INSTEAD, CREATE A COMPLEX SECRET AND KEEP IT SAFE OUTSIDE OF THE SOURCE CODE.', } ``` # 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) `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. # 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) `RouterResponseController` centralizes how router handler output is converted into an HTTP response. It manages response status codes and headers, supports redirects, rendering, server-sent events (SSE), and applies the final response to the underlying transport. ## 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 Result] --> Controller[RouterResponseController] Controller --> Transform[transformToResult()] Controller --> Status[setStatus() / getStatusByMethod()] Controller --> Headers[setHeaders()] Controller --> Redirect[redirect()] Controller --> Render[render()] Controller --> SSE[sse()] Transform --> Apply[apply()] Status --> Apply Headers --> Apply Redirect --> Apply Render --> Apply SSE --> Apply Apply --> HTTP[HTTP Response] ``` ## Usage ```ts import { RouterResponseController } from '@your-package/core/router'; // Typically created and provided by the router/runtime. async function createUser( response: RouterResponseController, user: { id: string; email: string }, ) { response.setStatus(201); response.setHeaders({ 'cache-control': 'no-store', 'x-resource-id': user.id, }); // Convert the handler value into the router's response result. return response.transformToResult({ data: user, }); } // Other response modes: // response.redirect('/login'); // response.render('users/profile', { user }); // response.sse(stream); ``` ## AI Coding Instructions - Use `setStatus()` and `setHeaders()` before finalizing a response so response metadata is applied consistently. - Return values through `transformToResult()` when integrating custom handler output with the router response pipeline. - Use `redirect()` for navigation responses instead of manually setting `Location` headers and redirect status codes. - Use `render()` only for renderer-backed routes; keep API routes focused on structured response data. - Treat `apply()` as the final transport stepβ€”avoid writing directly to the underlying HTTP response after it has been applied. # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts#L48) HTTP Proxy entry for support client-side stream find method The `stream` endpoint is an HTTP `POST` proxy for the advanced gRPC client's streaming `find` operation. It accepts an HTTP request, forwards the request data to the gRPC client-side stream, and returns the resulting response through the NestJS HTTP layer. ## Endpoint `POST /client-streaming` ## Diagram ```mermaid sequenceDiagram participant Client as HTTP Client participant Controller as AdvancedGrpcController participant GrpcClient as gRPC Client participant Service as gRPC Service Client->>Controller: POST stream request Controller->>GrpcClient: Start client-side find stream GrpcClient->>Service: Send streamed find request data Service-->>GrpcClient: Stream processing result GrpcClient-->>Controller: Resolved response Controller-->>Client: HTTP response ``` ## Usage ```ts const response = await fetch('/grpc-advanced/stream', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ requests: [ { id: 'customer-001' }, { id: 'customer-002' }, ], }), }); if (!response.ok) { throw new Error(`Stream request failed: ${response.status}`); } const result = await response.json(); console.log(result); ``` ## AI Coding Instructions - Keep this endpoint thin: it should translate HTTP input into the gRPC client's streaming request rather than implement business logic. - Ensure the HTTP payload shape matches the protobuf request messages expected by the gRPC `find` stream. - Preserve NestJS controller conventions, including the existing `@Post` route and `@HttpCode` response behavior. - Handle gRPC stream errors explicitly and map them to appropriate HTTP exceptions when extending the endpoint. - Avoid buffering unbounded stream data in memory; validate and limit incoming request payloads where applicable. ## Referenced By - `AdvancedGrpcController` (MODULE_DECLARES) # Transient3Service **Kind:** Service **Source:** [`integration/injector/src/scoped/transient3.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/transient3.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ Transient3Service client->>+p1: Transient3Service p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `transientservice` ## Referenced By - `ScopedModule` (MODULE_PROVIDES) # AsyncApplicationModule **Kind:** Module **Source:** [`integration/graphql-schema-first/src/async-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/async-options.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # CatsController **Kind:** Controller **Source:** [`sample/01-cats-app/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.controller.ts#L9) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - DEPENDS_ON β†’ `catsservice` # 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) ## Definition ```ts ( error: any, req: TRequest, res: TResponse, next?: Function, ) => any ``` # ExportsService **Kind:** Service **Source:** [`integration/injector/src/exports/exports.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/exports/exports.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ ExportsService client->>+p1: ExportsService p1-->client: return response ``` ## Referenced By - `ExportsModule` (MODULE_EXPORTS) # 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) ## Signature ```ts function NoFilesInterceptor(localOptions: MulterOptions): Type ``` ## Parameters | Name | Type | |---|---| | `localOptions` | `MulterOptions` | **Returns:** `Type` # 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) `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. # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L37) ## Endpoint `POST /stream` ## Referenced By - `MqttController` (MODULE_DECLARES) # TestingModuleBuilder **Kind:** Class **Source:** [`packages/testing/testing-module.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-module.builder.ts#L37) `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) # WebhookHandler **Kind:** Constant **Source:** [`integration/discovery/src/decorators/webhook.decorators.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/decorators/webhook.decorators.ts#L4) ## Definition ```ts DiscoveryService.createDecorator<{ event: string; }>() ``` ## Value ```ts DiscoveryService.createDecorator<{ event: string; }>() ``` # 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) 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. # AppService **Kind:** Service **Source:** [`integration/send-files/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.service.ts#L9) `AppService` provides file-response fixtures for the `send-files` integration, returning `StreamableFile` instances backed by streams or buffers. It also exposes edge-case responsesβ€”including non-file payloads, RxJS observables, custom headers, missing files, and slow streamsβ€”to validate NestJS file delivery behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `getReadStream` | `getReadStream()` | `StreamableFile` | | `getBuffer` | `getBuffer()` | `StreamableFile` | | `getNonFile` | `getNonFile()` | `NonFile` | | `getRxJSFile` | `getRxJSFile()` | `Observable` | | `getFileWithHeaders` | `getFileWithHeaders()` | `StreamableFile` | | `getFileThatDoesNotExist` | `getFileThatDoesNotExist()` | `StreamableFile` | | `getSlowStream` | `getSlowStream()` | `StreamableFile` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant AppService participant FileSystem participant NestJS Client->>Controller: Request file endpoint Controller->>AppService: Call file-producing method alt Stream-backed file AppService->>FileSystem: Create/read file stream FileSystem-->>AppService: Readable stream AppService-->>Controller: StreamableFile else Buffer-backed file AppService-->>Controller: StreamableFile(buffer) else Observable response AppService-->>Controller: Observable else Non-file response AppService-->>Controller: NonFile payload end Controller->>NestJS: Return response NestJS-->>Client: Stream content or serialized payload ``` ## Usage ```ts import { Controller, Get, Res } from '@nestjs/common'; import { Response } from 'express'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get('files/stream') getStream() { return this.appService.getReadStream(); } @Get('files/buffer') getBuffer() { return this.appService.getBuffer(); } @Get('files/headers') getFileWithHeaders(@Res({ passthrough: true }) response: Response) { response.setHeader('Content-Disposition', 'attachment; filename="file.txt"'); return this.appService.getFileWithHeaders(); } @Get('files/rxjs') getRxJSFile() { return this.appService.getRxJSFile(); } } ``` ## AI Coding Instructions - Return `StreamableFile` for binary or streamed file responses so NestJS can manage the response body correctly. - Preserve stream-based behavior for large files; avoid eagerly loading files into buffers unless testing buffer-specific behavior. - Use `getRxJSFile()` only from routes or handlers that support observable return values. - Keep edge-case methods such as `getFileThatDoesNotExist()` and `getSlowStream()` available for integration and error-handling tests. - When adding download endpoints, configure response headers such as `Content-Type` and `Content-Disposition` at the controller or response layer. # AsyncClassApplicationModule **Kind:** Module **Source:** [`integration/graphql-schema-first/src/async-options-class.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/async-options-class.module.ts#L15) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # CatsController **Kind:** Controller **Source:** [`sample/36-hmr-esm/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/cats.controller.ts#L9) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - DEPENDS_ON β†’ `catsservice` # GroupDescription **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L862) ## Definition ```ts { groupId: string; members: MemberDescription[]; protocol: string; protocolType: string; state: ConsumerGroupState; } ``` # 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) `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) # 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) 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. # uploadFile **Kind:** API Endpoint **Source:** [`sample/29-file-upload/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.controller.ts#L24) ## Endpoint `POST /file` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) `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] # APP_FILTER **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L16) ## Definition ```ts 'APP_FILTER' ``` ## Value ```ts 'APP_FILTER' ``` # AsyncExistingApplicationModule **Kind:** Module **Source:** [`integration/graphql-schema-first/src/async-options-existing.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/async-options-existing.module.ts#L8) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # CatsController **Kind:** Controller **Source:** [`sample/10-fastify/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/cats.controller.ts#L9) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - DEPENDS_ON β†’ `catsservice` # ConsumerConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L164) `ConsumerConfig` defines the configuration used when creating a Kafka consumer in the microservices integration layer. It controls consumer-group membership, partition assignment, heartbeat and rebalance behavior, and message-fetching limits that affect throughput and latency. ## 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 --> Session[sessionTimeout] Config --> Rebalance[rebalanceTimeout] Config --> Heartbeat[heartbeatInterval] Config --> Fetch[Fetch Limits] Fetch --> MinBytes[minBytes] Fetch --> MaxBytes[maxBytes] Fetch --> MaxPartition[maxBytesPerPartition] Fetch --> Wait[maxWaitTimeInMs] Config --> Kafka[Kafka Consumer] Kafka --> Broker[Kafka Brokers] ``` ## Usage ```ts import { ConsumerConfig } from './kafka.interface'; const consumerConfig: ConsumerConfig = { groupId: 'orders-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 the configuration to the Kafka consumer setup. const consumer = kafka.consumer(consumerConfig); ``` ## AI Coding Instructions - Use a stable, service-specific `groupId` so consumer offsets are shared correctly across instances of the same service. - Keep `heartbeatInterval` significantly lower than `sessionTimeout` to prevent accidental consumer removal during normal processing. - Ensure `maxBytes` is greater than or equal to `maxBytesPerPartition`; overly large values can increase memory usage. - Tune `minBytes` and `maxWaitTimeInMs` together: higher values improve batching efficiency but can increase message-processing latency. - Provide compatible `partitionAssigners` when custom partition distribution behavior is required; otherwise preserve the project's existing assignment strategy. # 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) ## Definition ```ts { path: string; requestMethod: keyof typeof RequestMethod; methodVersion?: VersionValue; controllerVersion?: VersionValue; } ``` # PostsService **Kind:** Service **Source:** [`sample/22-graphql-prisma/src/posts/posts.service.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/posts.service.ts#L6) `PostsService` encapsulates post persistence operations for the NestJS GraphQL application. It provides methods to retrieve, create, update, and delete `Post` records, typically delegating database access to the Prisma integration layer. GraphQL resolvers should use this service rather than accessing Prisma directly. ## Methods | Method | Signature | Returns | |---|---|---| | `findOne` | `findOne(id: string)` | `Promise` | | `findAll` | `findAll()` | `Promise` | | `create` | `create(input: NewPost)` | `Promise` | | `update` | `update(params: UpdatePost)` | `Promise` | | `delete` | `delete(id: string)` | `Promise` | ## Dependencies - `PrismaService` ## Diagram ```mermaid sequenceDiagram participant Client as GraphQL Client participant Resolver as Posts Resolver participant Service as PostsService participant Prisma as PrismaService participant DB as Database Client->>Resolver: Query/Mutation Resolver->>Service: findOne(), findAll(), create(), update(), or delete() Service->>Prisma: Execute Prisma operation Prisma->>DB: Read or modify Post record DB-->>Prisma: Post data Prisma-->>Service: Post or Post[] Service-->>Resolver: Result Resolver-->>Client: GraphQL response ``` ## Usage ```ts import { Resolver, Query } from '@nestjs/graphql'; import { Post } from '@prisma/client'; import { PostsService } from './posts.service'; @Resolver(() => Post) export class PostsResolver { constructor(private readonly postsService: PostsService) {} @Query(() => [Post]) async posts(): Promise { return this.postsService.findAll(); } @Query(() => Post, { nullable: true }) async post(): Promise { return this.postsService.findOne(); } } ``` ## AI Coding Instructions - Keep database logic inside `PostsService`; resolvers should remain focused on GraphQL input/output handling. - Preserve the declared return contracts: `findOne()` may return `null`, while mutation methods return a `Post`. - Use Prisma-backed operations consistently when implementing or extending `create`, `update`, and `delete`. - Ensure GraphQL resolver nullability matches the service contract, especially for `findOne()`. - Add validation and authorization checks at the resolver, guard, or service boundary before mutating posts. ## Relationships - DEPENDS_ON β†’ `PrismaService` # 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) `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. # 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) 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. # uploadFileAndFailValidation **Kind:** API Endpoint **Source:** [`sample/29-file-upload/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.controller.ts#L57) ## Endpoint `POST /file/fail-validation` ## Referenced By - `AppController` (MODULE_DECLARES) # APP_GUARD **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L15) ## Definition ```ts 'APP_GUARD' ``` ## Value ```ts 'APP_GUARD' ``` # AppService **Kind:** Service **Source:** [`sample/34-using-esm-packages/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/sample/34-using-esm-packages/src/app.service.ts#L4) `AppService` is a NestJS provider responsible for supplying application-level behavior to other components, typically controllers. Its `getHello()` method exposes a simple value that can be injected and returned by the application's request-handling layer. ## Methods | Method | Signature | Returns | |---|---|---| | `getHello` | `getHello()` | `unknown` | ## Dependencies - `SuperJSON` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as AppController participant Service as AppService Client->>Controller: GET request Controller->>Service: getHello() Service-->>Controller: response value Controller-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello() { return this.appService.getHello(); } } ``` ## AI Coding Instructions - Keep `AppService` focused on reusable application or domain behavior; place HTTP-specific logic in controllers. - Inject `AppService` through NestJS constructor injection rather than creating it with `new`. - Ensure `AppService` is registered in the appropriate NestJS module's `providers` array before injecting it elsewhere. - Preserve the return contract of `getHello()` when changing its implementation, and update consuming controllers or tests if the response shape changes. ## Relationships - DEPENDS_ON β†’ `superjson` # AsyncOptionsClassModule **Kind:** Module **Source:** [`integration/mongoose/src/async-class-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/async-class-options.module.ts#L17) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # CatsController **Kind:** Controller **Source:** [`integration/inspector/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/cats.controller.ts#L8) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - DEPENDS_ON β†’ `catsservice` # 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) 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. # 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) ## Definition ```ts | string | symbol | Type | Abstract | Function ``` # SerializedGraph **Kind:** Class **Source:** [`packages/core/inspector/serialized-graph.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/serialized-graph.ts#L26) `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) # UNKNOWN_EXPORT_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L227) ## Signature ```ts function UNKNOWN_EXPORT_MESSAGE(token: string | symbol, module: string) ``` ## Parameters | Name | Type | |---|---| | `token` | `string | symbol` | | `module` | `string` | # uploadFileAndPassValidation **Kind:** API Endpoint **Source:** [`sample/29-file-upload/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.controller.ts#L36) ## Endpoint `POST /file/pass-validation` ## Referenced By - `AppController` (MODULE_DECLARES) # APP_INTERCEPTOR **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L13) ## Definition ```ts 'APP_INTERCEPTOR' ``` ## Value ```ts 'APP_INTERCEPTOR' ``` # AsyncOptionsClassModule **Kind:** Module **Source:** [`integration/typeorm/src/async-class-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/async-class-options.module.ts#L27) ## Relationships - MODULE_IMPORTS β†’ `photomodule` # AuthGuard **Kind:** Service **Source:** [`sample/19-auth-jwt/src/auth/auth.guard.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/auth.guard.ts#L13) `AuthGuard` is a NestJS guard that protects routes by validating incoming JWT-based authentication before a request reaches its controller handler. Its `canActivate()` method determines whether the current request is authorized and typically attaches authenticated user information to the request context for downstream use. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `Promise` | ## Dependencies - `JwtService` - `Reflector` ## Where it refuses work - `AuthGuard` stops the work with `UnauthorizedException` when `!token`. - `AuthGuard` stops the work with an early return when `isPublic`. ## When something fails - `AuthGuard` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid sequenceDiagram participant Client participant Guard as AuthGuard participant JWT as JWT Validation participant Controller Client->>Guard: Request with Authorization header Guard->>Guard: canActivate() Guard->>JWT: Extract and validate JWT alt Valid token JWT-->>Guard: Decoded user payload Guard-->>Controller: Allow request Controller-->>Client: Protected response else Missing or invalid token JWT-->>Guard: Validation failed Guard-->>Client: 401 Unauthorized end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { AuthGuard } from './auth/auth.guard'; @Controller('profile') export class ProfileController { @Get() @UseGuards(AuthGuard) getProfile() { return { message: 'This endpoint requires authentication.' }; } } ``` ## AI Coding Instructions - Keep authentication decisions inside `canActivate()`; controllers should receive requests only after the guard approves them. - Ensure JWT extraction consistently handles the `Authorization: Bearer ` header format. - Throw NestJS authentication exceptions for missing, expired, malformed, or invalid tokens rather than returning successful access. - Apply `@UseGuards(AuthGuard)` to protected controllers or routes, and register the guard globally only when most endpoints require authentication. - If user data is decoded from the token, attach only the required safe payload fields to `request.user`. ## Relationships - DEPENDS_ON β†’ `jwtservice` - DEPENDS_ON β†’ `Reflector` # CatsController **Kind:** Controller **Source:** [`sample/11-swagger/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/cats.controller.ts#L12) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findOne` - DEPENDS_ON β†’ `catsservice` # ContextUtils **Kind:** Class **Source:** [`packages/core/helpers/context-utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-utils.ts#L23) `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. # 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) 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. # MemberDescription **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L845) ## Definition ```ts { clientHost: string; clientId: string; memberId: string; memberAssignment: Buffer; memberMetadata: Buffer; } ``` # 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) 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. # useRecordBuilderDuplex **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L79) ## Endpoint `POST /record-builder-duplex` ## Referenced By - `RMQController` (MODULE_DECLARES) # APP_PIPE **Kind:** Constant **Source:** [`packages/core/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/constants.ts#L14) ## Definition ```ts 'APP_PIPE' ``` ## Value ```ts 'APP_PIPE' ``` # AsyncOptionsExistingModule **Kind:** Module **Source:** [`integration/mongoose/src/async-existing-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/async-existing-options.module.ts#L23) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # CatsRequestScopedService **Kind:** Service **Source:** [`integration/graphql-schema-first/src/cats/cats-request-scoped.service.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats-request-scoped.service.ts#L4) `CatsRequestScopedService` is a NestJS request-scoped service that provides GraphQL-facing operations for creating and retrieving `Cat` entities. It supports creating a cat, listing all cats, and looking up an individual cat by ID within the lifecycle of the current request. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `Cat` | | `findAll` | `findAll()` | `Cat[]` | | `findOneById` | `findOneById(id: number)` | `Cat` | ## Diagram ```mermaid sequenceDiagram participant Client as GraphQL Client participant Resolver as Cats Resolver participant Service as CatsRequestScopedService participant Store as Cat Data Store Client->>Resolver: create/findAll/findOneById request Resolver->>Service: Call service method Service->>Store: Read or create Cat data Store-->>Service: Cat or Cat[] Service-->>Resolver: Return result Resolver-->>Client: GraphQL response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsRequestScopedService } from './cats-request-scoped.service'; import { Cat } from './models/cat.model'; @Injectable() export class CatsResolver { constructor( private readonly catsService: CatsRequestScopedService, ) {} createCat(): Cat { return this.catsService.create(); } cats(): Cat[] { return this.catsService.findAll(); } cat(id: string): Cat { return this.catsService.findOneById(); } } ``` ## AI Coding Instructions - Inject `CatsRequestScopedService` through NestJS dependency injection; do not instantiate it manually. - Preserve the request-scoped lifecycle when adding dependencies or changing provider configuration. - Keep GraphQL resolver methods thin and delegate cat creation and lookup logic to this service. - Ensure `findOneById()` receives and uses the requested identifier if extending its implementation or resolver integration. - Return the GraphQL `Cat` model consistently from `create()` and `findOneById()`, and return arrays from `findAll()`. # DisconnectedClientController **Kind:** Controller **Source:** [`integration/microservices/src/disconnected.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/disconnected.controller.ts#L12) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ DisconnectedClientController client->>+p1: DisconnectedClientController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `call` # 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) `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. # InjectorDependencyContext **Kind:** Interface **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L67) 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. # 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) ## Definition ```ts { transportId: keyof typeof Transport | symbol; patterns: PatternMetadata[]; isEventHandler: boolean; extras?: Record; } ``` # useRecordBuilderDuplex **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L67) ## Endpoint `POST /record-builder-duplex` ## Referenced By - `NatsController` (MODULE_DECLARES) # 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) `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. # asyncGreeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.controller.ts#L16) ## Endpoint `GET /hello/async` ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) ## Definition ```ts 'Async' ``` ## Value ```ts 'Async' ``` # AsyncOptionsExistingModule **Kind:** Module **Source:** [`integration/typeorm/src/async-existing-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/async-existing-options.module.ts#L33) ## Relationships - MODULE_IMPORTS β†’ `photomodule` # CatsService **Kind:** Service **Source:** [`sample/06-mongoose/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.service.ts#L8) `CatsService` encapsulates MongoDB persistence operations for cat records using Mongoose. It provides the application’s cat-related CRUD workflow and is typically consumed by a NestJS controller to create, retrieve, update, and delete `Cat` documents. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createCatDto: CreateCatDto)` | `Promise` | | `findAll` | `findAll()` | `Promise` | | `findOne` | `findOne(id: string)` | `Promise` | | `update` | `update(id: string, updateCatDto: UpdateCatDto)` | `Promise` | | `delete` | `delete(id: string)` | `Promise` | ## Dependencies - `Model` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as CatsController participant Service as CatsService participant Model as Mongoose Cat Model participant DB as MongoDB Client->>Controller: HTTP request Controller->>Service: create/findAll/findOne/update/delete Service->>Model: Execute Mongoose query Model->>DB: Read or write document DB-->>Model: Query result Model-->>Service: Cat or Cat[] Service-->>Controller: Return result Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsService } from './cats.service'; @Injectable() export class CatsController { constructor(private readonly catsService: CatsService) {} async createCat() { return this.catsService.create(); } async getCats() { return this.catsService.findAll(); } async getCat() { return this.catsService.findOne(); } async updateCat() { return this.catsService.update(); } async deleteCat() { return this.catsService.delete(); } } ``` ## AI Coding Instructions - Keep database access inside `CatsService`; controllers should delegate CRUD operations rather than call Mongoose models directly. - Preserve the promise-based return contracts: `create`, `findOne`, `update`, and `delete` return `Promise`, while `findAll` returns `Promise`. - Add DTO validation and identifier parameters at the controller/service boundary when extending CRUD methods. - Handle missing documents consistently, typically by throwing NestJS `NotFoundException` before returning from `findOne`, `update`, or `delete`. - Ensure the Mongoose `Cat` model is registered in the owning module with `MongooseModule.forFeature()` before injecting the service. ## Relationships - DEPENDS_ON β†’ `model` # DurableController **Kind:** Controller **Source:** [`integration/scopes/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ DurableController participant p2 as βš™οΈ NonDurableService participant p3 as πŸ“¦ TenantContext client->>+p1: DurableController p1->>+p2: NonDurableService p2->>+p3: TenantContext p3-->-p2: return p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - MODULE_DECLARES β†’ `echo` - MODULE_DECLARES β†’ `getRequestContext` - DEPENDS_ON β†’ `durableservice` - DEPENDS_ON β†’ `NonDurableService` # 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) `KafkaReplyPartitionAssigner` coordinates Kafka reply-topic partition assignments for members of a consumer group. It decodes member metadata, considers prior assignments, and produces stable `GroupMemberAssignment` entries so request/reply consumers can receive responses on the correct partitions. ## 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 A[Kafka consumer-group members] --> B[decodeMember] B --> C[getPreviousAssignment] C --> D[assign] D --> E[GroupMemberAssignment[]] F[protocol] --> G[Group protocol metadata] G --> A ``` ## Usage ```ts import { KafkaReplyPartitionAssigner } from '@nestjs/microservices'; // Create an assigner for the Kafka client and consumer group. const assigner = new KafkaReplyPartitionAssigner( 'billing-service', 'billing-service-consumer', ); // Provide protocol metadata during consumer-group negotiation. const protocol = assigner.protocol(); // Generate reply-partition assignments for group members. const assignments = await assigner.assign(); console.log(protocol.name); console.log(assignments); ``` ## AI Coding Instructions - Keep assignment behavior deterministic: members with the same group state should receive the same reply-partition allocation. - Preserve and reuse previous assignments where possible to reduce partition movement during consumer-group rebalances. - Ensure member metadata remains compatible with `decodeMember()` when changing the protocol payload or versioning strategy. - Integrate this assigner only with Kafka reply-topic consumer groups; normal event-consumer partition assignment should continue using the configured Kafka assigner. - Handle missing or invalid member metadata defensively so one malformed member does not prevent group assignment. # 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) # ProducerEvents **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L790) ## 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'; } ``` # 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) `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. # asyncGreeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host/host.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.controller.ts#L19) ## Endpoint `GET /async` ## Referenced By - `HostController` (MODULE_DECLARES) # AsyncOptionsFactoryModule **Kind:** Module **Source:** [`integration/typeorm/src/async-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/async-options.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `photomodule` # CATCH_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L46) ## Definition ```ts '__catch__' ``` ## Value ```ts '__catch__' ``` # CatsService **Kind:** Service **Source:** [`integration/graphql-schema-first/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.service.ts#L4) `CatsService` provides the core in-memory business operations for the Cats domain in the GraphQL schema-first integration. It creates cats, returns the complete collection, and retrieves individual cats by ID for use by GraphQL resolvers. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `Cat` | | `findAll` | `findAll()` | `Cat[]` | | `findOneById` | `findOneById(id: number)` | `Cat` | ## Diagram ```mermaid sequenceDiagram participant Resolver as GraphQL Resolver participant Service as CatsService participant Store as Cats Collection Resolver->>Service: create() Service->>Store: Add new Cat Store-->>Service: Created Cat Service-->>Resolver: Cat Resolver->>Service: findAll() Service->>Store: Read all cats Store-->>Service: Cat[] Service-->>Resolver: Cat[] Resolver->>Service: findOneById() Service->>Store: Find cat by ID Store-->>Service: Cat Service-->>Resolver: Cat ``` ## Usage ```ts import { CatsService } from './cats.service'; const catsService = new CatsService(); // Create a cat using the service's default creation behavior. const cat = catsService.create(); // Retrieve every available cat. const cats = catsService.findAll(); // Retrieve a single cat by its identifier. const selectedCat = catsService.findOneById(); console.log({ cat, cats, selectedCat }); ``` ## AI Coding Instructions - Keep GraphQL resolver logic thin; delegate cat creation and lookup behavior to `CatsService`. - Preserve the declared return types: `create()` and `findOneById()` return a single `Cat`, while `findAll()` returns `Cat[]`. - When adding lookup parameters such as an ID, update the corresponding GraphQL schema and resolver signatures together. - Handle missing cats consistently if `findOneById()` is extended to query external storage; use an appropriate NestJS/GraphQL error strategy. - Keep the `Cat` model aligned with the schema-first GraphQL type definitions. # ErrorsController **Kind:** Controller **Source:** [`integration/hello-world/src/errors/errors.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/errors/errors.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ ErrorsController client->>+p1: ErrorsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `synchronous` - MODULE_DECLARES β†’ `asynchronous` - MODULE_DECLARES β†’ `unexpectedError` # MiddlewareModule **Kind:** Class **Source:** [`packages/core/middleware/middleware-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/middleware-module.ts#L35) `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. # 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) 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. # 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) ## Definition ```ts | Type | ClassProvider | ValueProvider | FactoryProvider | ExistingProvider ``` # 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) `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. # asyncGreeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host-array/host-array.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.controller.ts#L19) ## Endpoint `GET /async` ## Referenced By - `HostArrayController` (MODULE_DECLARES) # AsyncOptionsFactoryModule **Kind:** Module **Source:** [`integration/mongoose/src/async-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/async-options.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # CatSchema **Kind:** Constant **Source:** [`sample/06-mongoose/src/cats/schemas/cat.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/schemas/cat.schema.ts#L18) ## Definition ```ts SchemaFactory.createForClass(Cat) ``` ## Value ```ts SchemaFactory.createForClass(Cat) ``` # CatsService **Kind:** Service **Source:** [`sample/12-graphql-schema-first/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.service.ts#L4) `CatsService` provides the core business logic for managing `Cat` entities in the GraphQL schema-first sample. It is responsible for creating cats, listing all cats, and retrieving a single cat by its identifier for use by GraphQL resolvers or other NestJS providers. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `Cat` | | `findAll` | `findAll()` | `Cat[]` | | `findOneById` | `findOneById(id: number)` | `Cat` | ## Diagram ```mermaid sequenceDiagram participant Client as GraphQL Client participant Resolver as CatsResolver participant Service as CatsService participant Store as Cat Data Store Client->>Resolver: createCat(input) Resolver->>Service: create() Service->>Store: Save cat Store-->>Service: Cat Service-->>Resolver: Cat Resolver-->>Client: Cat result Client->>Resolver: cats() / cat(id) Resolver->>Service: findAll() / findOneById() Service->>Store: Read cat data Store-->>Service: Cat[] Service-->>Resolver: Cat or Cat[] Resolver-->>Client: Query result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsService } from './cats.service'; @Injectable() export class CatsResolver { constructor(private readonly catsService: CatsService) {} cats() { return this.catsService.findAll(); } cat(id: string) { return this.catsService.findOneById(id); } createCat() { return this.catsService.create(); } } ``` ## AI Coding Instructions - Keep `CatsService` focused on cat-related business logic; GraphQL argument parsing and schema concerns belong in the resolver. - Preserve the declared return types: `create()` and `findOneById()` return a single `Cat`, while `findAll()` returns `Cat[]`. - When adding persistence, replace in-memory logic behind the existing service methods rather than exposing repository calls directly from resolvers. - Add explicit not-found handling in `findOneById()` when integrating a database, using an appropriate NestJS exception such as `NotFoundException`. - Update the GraphQL schema and resolver mappings whenever service method inputs or returned `Cat` fields change. # HelloController **Kind:** Controller **Source:** [`integration/hello-world/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - MODULE_DECLARES β†’ `asyncGreeting` - MODULE_DECLARES β†’ `streamGreeting` - MODULE_DECLARES β†’ `localPipe` - DEPENDS_ON β†’ `helloservice` # 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) ## Properties | Property | Type | |---|---| | `logger` | `LoggerService | LogLevel[] | false` | | `abortOnError` | `boolean | undefined` | | `bufferLogs` | `boolean` | | `autoFlushLogs` | `boolean` | | `preview` | `boolean` | | `snapshot` | `boolean` | | `moduleIdGeneratorAlgorithm` | `'deep-hash' | 'reference'` | | `instrument` | `{ /** * Function that decorates each instance created by the application context. * This function can be used to add custom properties or methods to the instance. * @param instance The instance to decorate. * @returns The decorated instance. */ instanceDecorator: (instance: unknown) => unknown; }` | | `forceConsole` | `boolean` | # 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) `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. # RmqEvents **Kind:** Type **Source:** [`packages/microservices/events/rmq.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/rmq.events.ts#L25) 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. # 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) `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. # 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) 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. # asynchronous **Kind:** API Endpoint **Source:** [`integration/hello-world/src/errors/errors.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/errors/errors.controller.ts#L10) ## Endpoint `GET /async` ## Referenced By - `ErrorsController` (MODULE_DECLARES) # AudioModule **Kind:** Module **Source:** [`sample/26-queues/src/audio/audio.module.ts`](https://github.com/nestjs/nest/blob/master/sample/26-queues/src/audio/audio.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `AudioController` - MODULE_PROVIDES β†’ `AudioProcessor` # 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) ## Definition ```ts 'class_serializer:options' ``` ## Value ```ts 'class_serializer:options' ``` # DurableService **Kind:** Service **Source:** [`integration/scopes/src/durable/durable.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.service.ts#L10) `DurableService` is a NestJS service responsible for exposing durable, tenant-aware behavior within the integration scopes module. It provides a greeting operation and access to the current tenant identifier, allowing downstream components to operate within the correct tenant context. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `unknown` | | `getTenantId` | `getTenantId()` | `unknown` | ## Dependencies - `TenantContext` ## Where it refuses work - `DurableService` stops the work with `PreconditionFailedException` when `requestPayload.forceError` β€” β€œForced error”. ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Consumer participant Service as DurableService participant Context as Tenant Context Consumer->>Service: greeting() Service-->>Consumer: Greeting response Consumer->>Service: getTenantId() Service->>Context: Resolve current tenant Context-->>Service: tenantId Service-->>Consumer: tenantId ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { DurableService } from './durable/durable.service'; @Injectable() export class ExampleService { constructor(private readonly durableService: DurableService) {} getTenantGreeting() { const tenantId = this.durableService.getTenantId(); const greeting = this.durableService.greeting(); return { tenantId, greeting, }; } } ``` ## AI Coding Instructions - Inject `DurableService` through NestJS constructor injection; do not instantiate it manually. - Use `getTenantId()` when tenant-specific behavior, logging, or resource selection is required. - Ensure callers execute within an initialized tenant/request scope before relying on `getTenantId()`. - Keep tenant-context resolution inside the service or its configured scope integrations rather than passing tenant IDs through unrelated layers. - Preserve the service's durable lifecycle configuration when modifying its NestJS module registration. ## Relationships - DEPENDS_ON β†’ `TenantContext` # 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) `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] # HelloController **Kind:** Controller **Source:** [`integration/scopes/src/inject-inquirer/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController participant p2 as βš™οΈ HelloTransientService participant p3 as βš™οΈ TransientLogger participant p4 as βš™οΈ Logger participant p5 as βš™οΈ HelloRequestService participant p6 as βš™οΈ RequestLogger client->>+p1: HelloController p1->>+p2: HelloTransientService p2->>+p3: TransientLogger p3->>+p4: Logger p4-->-p3: return p3-->-p2: return p2-->-p1: return p1->>+p5: HelloRequestService p5->>+p6: RequestLogger p6-->-p5: return p5-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greetingTransient` - MODULE_DECLARES β†’ `greetingRequest` - DEPENDS_ON β†’ `HelloTransientService` - DEPENDS_ON β†’ `HelloRequestService` # 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) `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. # Transaction **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L831) ## Definition ```ts Sender & { sendOffsets(offsets: Offsets & { consumerGroupId: string }): Promise; commit(): Promise; abort(): Promise; isActive(): boolean; } ``` # BModule **Kind:** Module **Source:** [`integration/injector/src/multiple-providers/b.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/multiple-providers/b.module.ts#L3) # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc/grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc/grpc.controller.ts#L52) ## Endpoint `POST /sum` ## Referenced By - `GrpcController` (MODULE_DECLARES) # CLIENT_CONFIGURATION_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L36) ## Definition ```ts 'microservices:client' ``` ## Value ```ts 'microservices:client' ``` # 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) ## Signature ```ts function defineDefaultCommandsOnRepl(replServer: REPLServer): void ``` ## Parameters | Name | Type | |---|---| | `replServer` | `REPLServer` | **Returns:** `void` # ExceptionInterceptor **Kind:** Service **Source:** [`sample/10-fastify/src/common/interceptors/exception.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/common/interceptors/exception.interceptor.ts#L12) `ExceptionInterceptor` is a NestJS interceptor that wraps request handling to observe and transform errors emitted by downstream handlers. It provides a centralized place to apply consistent exception logging, error mapping, or response formatting across Fastify routes. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Fastify participant Interceptor as ExceptionInterceptor participant Handler as Controller/Route Handler participant Filter as Exception Filter Client->>Fastify: HTTP request Fastify->>Interceptor: intercept(context, next) Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable response or error alt Successful response Interceptor-->>Fastify: Return response Observable Fastify-->>Client: HTTP response else Handler throws error Interceptor->>Interceptor: catchError / transform error Interceptor-->>Filter: Re-throw mapped exception Filter-->>Client: Error response end ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { ExceptionInterceptor } from './common/interceptors/exception.interceptor'; @Controller('users') @UseInterceptors(ExceptionInterceptor) export class UsersController { @Get() findAll() { // Exceptions thrown here can be handled consistently // by ExceptionInterceptor. return [{ id: 1, name: 'Ada Lovelace' }]; } } ``` To apply it globally: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ExceptionInterceptor } from './common/interceptors/exception.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new ExceptionInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Preserve the NestJS interceptor contract: `intercept()` must return an `Observable` from `next.handle()`. - Use RxJS operators such as `catchError` when transforming or logging errors; avoid subscribing inside the interceptor. - Re-throw NestJS-compatible exceptions after processing so configured exception filters can generate the correct Fastify response. - Register the interceptor with `@UseInterceptors()` for scoped behavior or `useGlobalInterceptors()` for application-wide handling. - Keep error response formatting aligned with existing exception filters to avoid duplicate logging or inconsistent API error payloads. # HelloController **Kind:** Controller **Source:** [`integration/inspector/src/circular-hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/hello.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `helloservice` - DEPENDS_ON β†’ `usersservice` # NestFactoryStatic **Kind:** Class **Source:** [`packages/core/nest-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts#L48) `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. # 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) `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) # 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) ## Definition ```ts VersioningCommonOptions & ( | HeaderVersioningOptions | UriVersioningOptions | MediaTypeVersioningOptions | CustomVersioningOptions ) ``` # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc-advanced/advanced.grpc.controller.ts#L37) HTTP Proxy entry for support non-stream find method `call` exposes an HTTP `POST` entry point that proxies non-streaming find requests to the advanced gRPC service. It accepts the request payload, forwards it to the underlying gRPC `find` operation, and returns the resulting response through the HTTP API with the status configured by `@HttpCode`. ## Endpoint `POST /` ## Diagram ```mermaid sequenceDiagram participant Client as HTTP Client participant Controller as AdvancedGrpcController.call participant GrpcClient as gRPC Client Proxy participant GrpcService as Advanced gRPC Service Client->>Controller: POST request with find payload Controller->>GrpcClient: Invoke non-stream find method GrpcClient->>GrpcService: gRPC find request GrpcService-->>GrpcClient: Found entity response GrpcClient-->>Controller: Observable/result Controller-->>Client: HTTP response ``` ## Usage ```ts const response = await fetch('http://localhost:3000/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ id: 1, }), }); if (!response.ok) { throw new Error(`Request failed: ${response.status}`); } const entity = await response.json(); console.log(entity); ``` ## AI Coding Instructions - Keep this handler as a thin HTTP-to-gRPC proxy; place business logic in the gRPC service implementation. - Ensure the request body matches the protobuf-generated input type expected by the non-streaming find method. - Preserve the gRPC client service lookup and method naming conventions when adding additional proxy endpoints. - Do not treat this endpoint as a streaming API; return the single response produced by the gRPC find call. - Keep the explicit `@HttpCode` behavior intact so HTTP clients receive the expected success status. ## Referenced By - `AdvancedGrpcController` (MODULE_DECLARES) # CatsModule **Kind:** Module **Source:** [`integration/graphql-schema-first/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.module.ts#L6) ## Relationships - MODULE_PROVIDES β†’ `catsservice` - MODULE_PROVIDES β†’ `CatsResolvers` # CLIENT_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L38) ## Definition ```ts 'microservices:is_client_instance' ``` ## Value ```ts 'microservices:is_client_instance' ``` # ConsumerCrashEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L972) ## Definition ```ts InstrumentationEvent<{ error: Error; groupId: string; restart: boolean; }> ``` # 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) `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. # Guard **Kind:** Service **Source:** [`integration/scopes/src/hello/guards/request-scoped.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/guards/request-scoped.guard.ts#L10) `Guard` is a NestJS request-scoped guard that participates in the authorization phase of the request lifecycle. Its `canActivate()` method determines whether an incoming request may continue to the target controller handler, supporting synchronous, asynchronous, or observable-based authorization checks. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean | Promise | Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Guard participant Controller Client->>NestJS: HTTP request NestJS->>Guard: canActivate(context) Guard-->>NestJS: boolean / Promise / Observable alt Access granted NestJS->>Controller: Invoke route handler Controller-->>Client: Response else Access denied NestJS-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Guard } from './guards/request-scoped.guard'; @Controller('hello') @UseGuards(Guard) export class HelloController { @Get() getHello() { return { message: 'Hello, authorized user!' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` focused on authorization decisions and return `true` only when the request should reach the controller handler. - Preserve the supported NestJS return types: `boolean`, `Promise`, or `Observable`. - Use request-scoped dependencies only when authorization requires per-request state, such as request metadata or authenticated user context. - Apply the guard with `@UseGuards(Guard)` at the controller or route level, or register it globally when the policy applies to all endpoints. - Avoid performing response formatting in the guard; throw an appropriate NestJS exception or return `false` for denied access. # HelloController **Kind:** Controller **Source:** [`integration/scopes/src/circular-hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/hello.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `helloservice` - DEPENDS_ON β†’ `usersservice` # 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) `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) # RoutesResolver **Kind:** Class **Source:** [`packages/core/router/routes-resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/routes-resolver.ts#L35) `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) # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L32) ## Endpoint `POST /` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # CLOSE_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L14) ## Definition ```ts 'close' ``` ## Value ```ts 'close' ``` # ConfigModule **Kind:** Module **Source:** [`sample/25-dynamic-modules/src/config/config.module.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/config/config.module.ts#L9) # ConsumerFetchEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L952) ## Definition ```ts InstrumentationEvent<{ numberOfBatches: number; duration: number; nodeId: number; }> ``` # 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) `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. # Guard **Kind:** Service **Source:** [`integration/scopes/src/msvc/guards/request-scoped.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/guards/request-scoped.guard.ts#L10) `Guard` is a NestJS request-scoped guard used to control whether an incoming request may access a route or controller. Its `canActivate()` method participates in NestJS's authorization pipeline and may return a synchronous boolean, a `Promise`, or an `Observable`. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean | Promise | Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Guard participant Controller Client->>NestJS: HTTP request NestJS->>Guard: canActivate(context) Guard->>Guard: Evaluate request-specific access rules alt Access granted Guard-->>NestJS: true / Promise / Observable NestJS->>Controller: Invoke route handler Controller-->>Client: Response else Access denied Guard-->>NestJS: false / Promise / Observable NestJS-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Guard } from './msvc/guards/request-scoped.guard'; @Controller('protected') @UseGuards(Guard) export class ProtectedController { @Get() getProtectedResource() { return { message: 'Access granted' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` compatible with NestJS guard return types: `boolean`, `Promise`, or `Observable`. - Treat the guard as request-scoped; do not store request-specific state in shared singleton variables. - Apply the guard with `@UseGuards(Guard)` at the controller or route-handler level. - Return `false` for denied access, or throw a NestJS HTTP exception when a more specific error response is required. - Access request metadata through NestJS's `ExecutionContext` when adding request-aware authorization logic. # HelloController **Kind:** Controller **Source:** [`integration/scopes/src/circular-transient/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/hello.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `helloservice` - DEPENDS_ON β†’ `usersservice` # 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) `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. # TcpSocket **Kind:** Class **Source:** [`packages/microservices/helpers/tcp-socket.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/tcp-socket.ts#L7) `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. # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/redis/redis.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis.controller.ts#L19) ## Endpoint `POST /` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `RedisController` (MODULE_DECLARES) # CONFIG_OPTIONS **Kind:** Constant **Source:** [`sample/25-dynamic-modules/src/config/constants.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/config/constants.ts#L1) ## Definition ```ts 'CONFIG_OPTIONS' ``` ## Value ```ts 'CONFIG_OPTIONS' ``` # ConsumerHeartbeatEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L928) ## Definition ```ts InstrumentationEvent<{ groupId: string; memberId: string; groupGenerationId: number; }> ``` # CoreModule **Kind:** Module **Source:** [`integration/inspector/src/core/core.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/core/core.module.ts#L8) # 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) `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. # HelloController **Kind:** Controller **Source:** [`integration/scopes/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/hello.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `helloservice` - DEPENDS_ON β†’ `usersservice` # HttpCacheInterceptor **Kind:** Service **Source:** [`sample/20-cache/src/common/http-cache.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/20-cache/src/common/http-cache.interceptor.ts#L4) `HttpCacheInterceptor` extends NestJS caching behavior to determine the cache key for incoming HTTP requests through its `trackBy()` method. It is used in the request pipeline to cache eligible responses while allowing requests without a valid cache key to bypass caching. ## Methods | Method | Signature | Returns | |---|---|---| | `trackBy` | `trackBy(context: ExecutionContext)` | `string | undefined` | ## Where it refuses work - `HttpCacheInterceptor` stops the work with an early return when `!isGetRequest || (isGetRequest && excludePaths.includes(httpAdapter.getRequestUrl(request…`. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant Interceptor as HttpCacheInterceptor participant Cache as Cache Store participant Handler as Route Handler Client->>Controller: HTTP request Controller->>Interceptor: Intercept request Interceptor->>Interceptor: trackBy() alt Cache key is available Interceptor->>Cache: Get cached response alt Cache hit Cache-->>Interceptor: Cached value Interceptor-->>Client: Return cached response else Cache miss Interceptor->>Handler: Execute route handler Handler-->>Interceptor: Response data Interceptor->>Cache: Store response using cache key Interceptor-->>Client: Return response end else No cache key Interceptor->>Handler: Execute route handler Handler-->>Interceptor: Response data Interceptor-->>Client: Return response end ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { CacheTTL } from '@nestjs/cache-manager'; import { HttpCacheInterceptor } from '../common/http-cache.interceptor'; @Controller('products') @UseInterceptors(HttpCacheInterceptor) export class ProductsController { @Get() @CacheTTL(60_000) findAll() { return [ { id: 1, name: 'Keyboard' }, { id: 2, name: 'Mouse' }, ]; } } ``` ## AI Coding Instructions - Use `HttpCacheInterceptor` on controllers or routes that return safe, repeatable HTTP responses. - Keep `trackBy()` deterministic: identical cacheable requests must produce the same cache key. - Return `undefined` from `trackBy()` when a request should bypass caching, such as non-cacheable HTTP methods or user-specific responses. - Ensure cache module configuration is registered before applying this interceptor. - Avoid caching responses containing authentication-specific, private, or rapidly changing data unless the cache key includes the required scope. # MicroservicesModule **Kind:** Class **Source:** [`packages/microservices/microservices-module.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/microservices-module.ts#L23) `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. # 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) `TcpOptions` configures a TCP-based microservice transport. It defines the TCP host and port, connection retry behavior, serialization, TLS settings, socket implementation, and the maximum inbound message buffer size. ## Properties | Property | Type | |---|---| | `transport` | `Transport.TCP` | | `options` | `{ host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; tlsOptions?: TlsOptions; deserializer?: Deserializer; socketClass?: Type; /** * Maximum buffer size in characters (default: 128MB in characters, i.e., (512 * 1024 * 1024) / 4). * This limit prevents memory exhaustion when receiving large TCP messages. */ maxBufferSize?: number; }` | ## Diagram ```mermaid graph LR App[Microservice Configuration] --> TcpOptions TcpOptions --> Transport[transport: Transport.TCP] TcpOptions --> Connection[host and port] TcpOptions --> Retry[retryAttempts and retryDelay] TcpOptions --> Encoding[serializer and deserializer] TcpOptions --> Security[tlsOptions] TcpOptions --> Socket[socketClass] TcpOptions --> Buffer[maxBufferSize] Connection --> TcpServer[TCP Server] ``` ## Usage ```ts import { Transport } from '@nestjs/microservices'; import type { TcpOptions } from '@nestjs/microservices'; const tcpOptions: TcpOptions = { transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001, retryAttempts: 5, retryDelay: 1000, // Limit buffered inbound TCP data to 64 MB in characters. maxBufferSize: 64 * 1024 * 1024, }, }; // Example: NestFactory.createMicroservice(AppModule, tcpOptions) ``` ## AI Coding Instructions - Always set `transport` to `Transport.TCP`; this interface is only valid for TCP microservice configuration. - Configure `host` and `port` explicitly for deployed environments rather than relying on defaults. - Use `retryAttempts` and `retryDelay` to handle temporary connection failures, especially for TCP clients that depend on startup ordering. - Set `maxBufferSize` based on expected message sizes; avoid increasing it unnecessarily because large values can increase memory usage. - Provide matching `serializer` and `deserializer` implementations on communicating services, and configure `tlsOptions` when TCP traffic requires encryption. # 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) 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. # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L34) ## Endpoint `POST /` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `RMQController` (MODULE_DECLARES) # 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) ## Definition ```ts 'CONFIGURABLE_MODULE_ID' ``` ## Value ```ts 'CONFIGURABLE_MODULE_ID' ``` # DatabaseModule **Kind:** Module **Source:** [`integration/typeorm/src/database.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/database.module.ts#L5) # DeleteGroupsResult **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L904) ## Definition ```ts { groupId: string; errorCode?: number; error?: KafkaJSProtocolError; } ``` # 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) 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. # HelloController **Kind:** Controller **Source:** [`integration/scopes/src/msvc/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/hello.controller.ts#L8) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `helloservice` - DEPENDS_ON β†’ `usersservice` # PhotoService **Kind:** Service **Source:** [`integration/typeorm/src/photo/photo.service.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/photo/photo.service.ts#L6) `PhotoService` is a NestJS service responsible for managing photo records in the TypeORM integration layer. It exposes methods to retrieve all persisted photos and create a new photo entity, acting as the boundary between application logic and the photo repository. ## Methods | Method | Signature | Returns | |---|---|---| | `findAll` | `findAll()` | `Promise` | | `create` | `create()` | `Promise` | ## Dependencies - `Repository` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as PhotoController participant Service as PhotoService participant Repository as TypeORM Photo Repository participant Database Client->>Controller: Request photo operation Controller->>Service: findAll() or create() Service->>Repository: find() or save(photo) Repository->>Database: Execute query Database-->>Repository: Photo data Repository-->>Service: Photo[] or Photo Service-->>Controller: Return result Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { PhotoService } from './photo.service'; import { Photo } from './photo.entity'; @Injectable() export class PhotoController { constructor(private readonly photoService: PhotoService) {} async listPhotos(): Promise { return this.photoService.findAll(); } async createPhoto(): Promise { return this.photoService.create(); } } ``` ## AI Coding Instructions - Keep database access inside `PhotoService`; controllers should delegate photo persistence and retrieval operations to this service. - Preserve the `Promise` return type for `findAll()` and `Promise` for `create()`. - Use the injected TypeORM repository for entity queries and persistence rather than constructing database connections directly. - Add validation and input DTO handling at the controller or service boundary before persisting user-provided photo data. - When extending the service, handle repository errors consistently with NestJS exception patterns. ## Relationships - DEPENDS_ON β†’ `repository` # 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) `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] # call **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L45) ## Endpoint `POST /` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `command` | query | `unknown` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # CONN_ERR **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L29) ## Definition ```ts 'CONN_ERR' ``` ## Value ```ts 'CONN_ERR' ``` # DatabaseModule **Kind:** Module **Source:** [`integration/repl/src/database/database.module.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/database/database.module.ts#L4) # 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) ## Definition ```ts ( result: TResult, res: TResponse, req?: any, ) => any ``` # HelloController **Kind:** Controller **Source:** [`integration/scopes/src/transient/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/hello.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ HelloController client->>+p1: HelloController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `helloservice` - DEPENDS_ON β†’ `usersservice` # 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) 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. # PostsService **Kind:** Service **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/posts/posts.service.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/posts/posts.service.ts#L4) `PostsService` provides the application-layer operations for retrieving post data in the posts application. It supports fetching all posts, finding a single post, and filtering posts by author ID for GraphQL federation resolvers and other backend consumers. ## Methods | Method | Signature | Returns | |---|---|---| | `findAllByAuthorId` | `findAllByAuthorId(authorId: number)` | `Post[]` | | `findOne` | `findOne(postId: number)` | `Post` | | `findAll` | `findAll()` | `Post[]` | ## Diagram ```mermaid sequenceDiagram participant Client participant PostsResolver participant PostsService participant PostsStore as Post Data Store Client->>PostsResolver: Query posts / post / author.posts PostsResolver->>PostsService: findAll(), findOne(), or findAllByAuthorId() PostsService->>PostsStore: Read matching post records PostsStore-->>PostsService: Post data PostsService-->>PostsResolver: Post or Post[] PostsResolver-->>Client: GraphQL response ``` ## Usage ```ts import { PostsService } from './posts.service'; export class PostsResolver { constructor(private readonly postsService: PostsService) {} posts() { return this.postsService.findAll(); } post(id: string) { return this.postsService.findOne(id); } postsByAuthor(authorId: string) { return this.postsService.findAllByAuthorId(authorId); } } ``` ## AI Coding Instructions - Keep `PostsService` focused on post retrieval and domain-level post operations; expose it through GraphQL resolvers rather than accessing storage directly from resolvers. - Use `findAllByAuthorId()` when resolving federated author-to-post relationships to ensure filtering remains centralized. - Ensure `findOne()` handles missing post IDs consistently with the application's GraphQL error strategy. - Preserve the `Post` return types when adding methods so GraphQL schema generation and federation entity resolution remain compatible. - Add persistence or external API integrations behind this service interface to avoid coupling resolvers to infrastructure details. # ReplContext **Kind:** Class **Source:** [`packages/core/repl/repl-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-context.ts#L29) `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] # callMultiSum **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc/grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc/grpc.controller.ts#L128) ## Endpoint `POST /multi/sum` ## Referenced By - `GrpcController` (MODULE_DECLARES) # CONNECTION_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L12) ## Definition ```ts 'connection' ``` ## Value ```ts 'connection' ``` # CreateDecoratorOptions **Kind:** Interface **Source:** [`packages/core/services/reflector.service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/services/reflector.service.ts#L8) `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. # DurableModule **Kind:** Module **Source:** [`integration/scopes/src/durable/durable.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.module.ts#L8) ## Relationships - MODULE_DECLARES β†’ `durablecontroller` - MODULE_PROVIDES β†’ `durableservice` - MODULE_PROVIDES β†’ `NonDurableService` # IEntryNestModule **Kind:** Type **Source:** [`packages/core/nest-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts#L39) 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. # KafkaConcurrentMessagesController **Kind:** Controller **Source:** [`integration/microservices/src/kafka-concurrent/kafka-concurrent.messages.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka-concurrent/kafka-concurrent.messages.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ KafkaConcurrentMessagesController client->>+p1: KafkaConcurrentMessagesController p1-->client: return response ``` # KafkaLogger **Kind:** Function **Source:** [`packages/microservices/helpers/kafka-logger.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/kafka-logger.ts#L3) ## Signature ```ts function KafkaLogger(logger: any) ``` ## Parameters | Name | Type | |---|---| | `logger` | `any` | # PostsService **Kind:** Service **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.service.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.service.ts#L4) `PostsService` encapsulates post retrieval logic for the posts application in the GraphQL federation example. It provides lookup methods for individual posts, posts by author ID, and the complete post collection, serving as the data-access layer used by GraphQL resolvers. ## Methods | Method | Signature | Returns | |---|---|---| | `findOneByAuthorId` | `findOneByAuthorId(authorId: number)` | `unknown` | | `findOne` | `findOne(postId: number)` | `unknown` | | `findAll` | `findAll()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Resolver as GraphQL Resolver participant Service as PostsService participant Store as Posts Data Store Resolver->>Service: findOne(postId) Service->>Store: Retrieve post by ID Store-->>Service: Post result Service-->>Resolver: Post Resolver->>Service: findOneByAuthorId(authorId) Service->>Store: Retrieve post for author Store-->>Service: Post result Service-->>Resolver: Post Resolver->>Service: findAll() Service->>Store: Retrieve all posts Store-->>Service: Posts[] Service-->>Resolver: Posts[] ``` ## Usage ```ts import { PostsService } from './posts.service'; export class PostsResolver { constructor(private readonly postsService: PostsService) {} post(id: string) { return this.postsService.findOne(id); } posts() { return this.postsService.findAll(); } postByAuthor(authorId: string) { return this.postsService.findOneByAuthorId(authorId); } } ``` ## AI Coding Instructions - Keep post retrieval and lookup logic inside `PostsService`; GraphQL resolvers should delegate to the service rather than access storage directly. - Use `findOne(id)` for entity resolution by post identifier and `findOneByAuthorId(authorId)` when resolving author-related post data. - Preserve return types and null/undefined behavior expected by GraphQL resolvers when a requested post does not exist. - Update resolver integrations and federation entity resolution code when changing method signatures or lookup behavior. - Add tests for valid IDs, missing IDs, and authors with no associated posts when modifying retrieval logic. # 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) `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) # callMultiSum2 **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc/grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc/grpc.controller.ts#L135) ## Endpoint `POST /multi/sum2` ## Referenced By - `GrpcController` (MODULE_DECLARES) # CONTEXT **Kind:** Constant **Source:** [`packages/microservices/tokens.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/tokens.ts#L3) ## Definition ```ts REQUEST ``` ## Value ```ts REQUEST ``` # 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) `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. # HelloModule **Kind:** Module **Source:** [`integration/scopes/src/hello/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/hello.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # LazyController **Kind:** Controller **Source:** [`integration/lazy-modules/src/lazy.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/lazy.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ LazyController participant p2 as βš™οΈ LazyModuleLoader client->>+p1: LazyController p1->>+p2: LazyModuleLoader p2-->-p1: return p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `exec` - MODULE_DECLARES β†’ `execRequestScope` - DEPENDS_ON β†’ `LazyModuleLoader` # MemberAssignment **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L607) ## Definition ```ts { version: number; assignment: Assignment; userData: Buffer; } ``` # RecipesService **Kind:** Service **Source:** [`integration/graphql-code-first/src/recipes/recipes.service.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/recipes/recipes.service.ts#L6) `RecipesService` provides the core application logic for managing recipe records in the code-first GraphQL integration. It exposes operations to create recipes, retrieve one or many recipes, and remove recipes, typically serving as the data-access layer used by GraphQL resolvers. ## Methods | Method | Signature | Returns | Description | |---|---|---|---| | `create` | `create(data: NewRecipeInput)` | `Promise` | MOCK Put some real business logic here Left for demonstration purposes | | `findOneById` | `findOneById(id: string)` | `Promise` | | | `findAll` | `findAll(recipesArgs: RecipesArgs)` | `Promise` | | | `remove` | `remove(id: string)` | `Promise` | | ## Diagram ```mermaid sequenceDiagram participant Client as GraphQL Client participant Resolver as RecipesResolver participant Service as RecipesService participant Store as Recipe Data Store Client->>Resolver: createRecipe(input) Resolver->>Service: create(input) Service->>Store: Persist recipe Store-->>Service: Recipe Service-->>Resolver: Recipe Resolver-->>Client: Recipe response Client->>Resolver: recipes() Resolver->>Service: findAll() Service->>Store: Retrieve recipes Store-->>Service: Recipe[] Service-->>Resolver: Recipe[] Resolver-->>Client: Recipe list ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { RecipesService } from './recipes.service'; @Injectable() export class RecipesResolver { constructor(private readonly recipesService: RecipesService) {} async recipe(id: string) { return this.recipesService.findOneById(id); } async recipes() { return this.recipesService.findAll(); } async deleteRecipe(id: string): Promise { return this.recipesService.remove(id); } } ``` ## AI Coding Instructions - Keep GraphQL resolver logic thin; delegate recipe creation, lookup, listing, and deletion behavior to `RecipesService`. - Preserve the asynchronous `Promise`-based method contracts when adding storage or database integrations. - Ensure `findOneById()` handles missing recipe IDs consistently with resolver and GraphQL error-handling expectations. - Return `false` from `remove()` when deletion cannot be completed, and avoid exposing persistence-specific details to callers. - When adding fields or validation rules, update the corresponding GraphQL recipe types and create-input definitions alongside the service logic. # 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) ## Signature ```ts function selectExceptionFilterMetadata(filters: ExceptionFilterMetadata[], exception: T): ExceptionFilterMetadata | undefined ``` ## Parameters | Name | Type | |---|---| | `filters` | `ExceptionFilterMetadata[]` | | `exception` | `T` | **Returns:** `ExceptionFilterMetadata | undefined` # 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) `StreamableFile` wraps a Node.js `Readable` stream or binary buffer so it can be returned from a NestJS controller as a streamed HTTP response. It stores response metadata such as content type, disposition, and length, while also providing configurable error handling and logging for stream failures. ## 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[Controller] --> B[StreamableFile] C[Readable stream or Buffer] --> B B --> D[getStream()] B --> E[getHeaders()] B --> F[Nest response handling] F --> G[HTTP streamed response] D --> G E --> G H[Custom error handler/logger] --> B ``` ## 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') downloadReport(): StreamableFile { const filePath = join(process.cwd(), 'files', 'report.pdf'); const stream = createReadStream(filePath); return new StreamableFile(stream, { type: 'application/pdf', disposition: 'attachment; filename="report.pdf"', }) .setErrorLogger((error) => { console.error('Report stream failed:', error); }) .setErrorHandler((error, response) => { if (!response.destroyed) { response.statusCode = 500; response.end('Unable to download the report.'); } }); } } ``` ## AI Coding Instructions - Return `StreamableFile` directly from controller handlers when serving files or large generated content; avoid reading large files fully into memory when a `Readable` stream is available. - Provide `type`, `disposition`, and `length` options when known so clients receive correct download behavior and response metadata. - Use `getStream()` only when integrating with lower-level streaming logic; normal NestJS controller responses should return the `StreamableFile` instance. - Configure `setErrorHandler()` for application-specific client responses, and use `setErrorLogger()` to send stream failures to the project’s logging system. - Ensure custom error handlers check whether the response has already been destroyed before attempting to write or end it. ## How it works - `StreamableFile` is an exported class that packages either a `Uint8Array` or a readable, pipe-capable input together with optional stream-response metadata and stream-error callbacks. Its constructor overloads declare `Uint8Array` and Node `Readable` inputs. [streamable-file.ts:13-14](packages/common/file-stream/streamable-file.ts#L13-L14) [streamable-file.ts:37-42](packages/common/file-stream/streamable-file.ts#L37-L42) - At runtime, the constructor checks whether its first argument is a `Uint8Array`. For that case, it creates a `Readable`, pushes the byte array, then pushes `null` to end that stream. If `options.length` is nullish, it mutates the supplied/default options object to set `length` to the byte-array length. [streamable-file.ts:43-47](packages/common/file-stream/streamable-file.ts#L43-L47) - Otherwise, the constructor accepts an input when it has a truthy `pipe` property that is a function, assigning that object as the stored stream. [streamable-file.ts:48-50](packages/common/file-stream/streamable-file.ts#L48-L50) There is no explicit exception or fallback in this class for an input that is neither a `Uint8Array` nor pipe-capable; in that case, no assignment to `stream` occurs. [streamable-file.ts:43-50](packages/common/file-stream/streamable-file.ts#L43-L50) The tests cover this runtime case by observing `getStream()` as `undefined`. [streamable-file.spec.ts:22-27](packages/common/test/file-stream/streamable-file.spec.ts#L22-L27) - `getStream()` returns the stored stream. [streamable-file.ts:53-55](packages/common/file-stream/streamable-file.ts#L53-L55) - The optional `StreamableFileOptions` fields are: - `type?: string`, documented as the `Content-Type` value; - `disposition?: string | string[]`, documented as the `Content-Disposition` value; - `length?: number`, documented as the `Content-Length` value. [streamable-options.interface.ts:8-21](packages/common/file-stream/interfaces/streamable-options.interface.ts#L8-L21) - `getHeaders()` returns `{ type, disposition, length }` from `options`; it defaults `type` to `'application/octet-stream'` and leaves the other two values `undefined` when absent. [streamable-file.ts:57-68](packages/common/file-stream/streamable-file.ts#L57-L68) - The default `errorHandler` handles an `Error` and a response shaped as `StreamableHandlerResponse`, which has `destroyed`, `headersSent`, `statusCode`, `send`, and `end` members. [streamable-handler-response.interface.ts:1-12](packages/common/file-stream/interfaces/streamable-handler-response.interface.ts#L1-L12) Its behavior is: - return without action if `response.destroyed` is true; - call `response.end()` if headers have already been sent; - otherwise set `response.statusCode` to `HttpStatus.BAD_REQUEST` and call `response.send(err.message)`. [streamable-file.ts:17-31](packages/common/file-stream/streamable-file.ts#L17-L31) - The default `errorLogger` sends the error to a `Logger` initialized with the context string `'StreamableFile'`. [streamable-file.ts:15](packages/common/file-stream/streamable-file.ts#L15) [streamable-file.ts:33-35](packages/common/file-stream/streamable-file.ts#L33-L35) - `setErrorHandler(handler)` replaces the error handler and returns the same `StreamableFile` instance. `setErrorLogger(handler)` similarly replaces the logger callback and returns the instance. Neither setter performs runtime validation of the supplied callback. [streamable-file.ts:77-91](packages/common/file-stream/streamable-file.ts#L77-L91) - In the Express adapter, a response body that is a `StreamableFile` has its headers applied only when each corresponding response header is currently absent; array dispositions are joined with commas. The adapter then attaches the file’s `errorHandler` to the source stream’s first `'error'` event, pipes the stream to the response, and sends pipe errors to `errorLogger`. [express-adapter.ts:103-119](packages/platform-express/adapters/express-adapter.ts#L103-L119) [express-adapter.ts:501-522](packages/platform-express/adapters/express-adapter.ts#L501-L522) - In the Fastify adapter, a `StreamableFile` similarly supplies absent `Content-Type`, `Content-Disposition`, and `Content-Length` headers, after which its stored stream becomes the body passed to `fastifyReply.send()`. [fastify-adapter.ts:449-482](packages/platform-fastify/adapters/fastify-adapter.ts#L449-L482) - The class serializer interceptor leaves `StreamableFile` instances unchanged rather than transforming them as ordinary object responses. [class-serializer.interceptor.ts:67-80](packages/common/serializer/class-serializer.interceptor.ts#L67-L80) # callWithOptions **Kind:** API Endpoint **Source:** [`integration/microservices/src/grpc/grpc.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/grpc/grpc.controller.ts#L60) ## Endpoint `POST /upperMethod/sum` ## Referenced By - `GrpcController` (MODULE_DECLARES) # CONTROLLER_ID_KEY **Kind:** Constant **Source:** [`packages/core/injector/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/constants.ts#L3) ## Definition ```ts 'CONTROLLER_ID' ``` ## Value ```ts 'CONTROLLER_ID' ``` # 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) `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. # DiscoveryService **Kind:** Class **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L49) `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. # HelloModule **Kind:** Module **Source:** [`integration/scopes/src/msvc/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/hello.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_DECLARES β†’ `HttpController` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # MemberMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L601) ## Definition ```ts { version: number; topics: string[]; userData: Buffer; } ``` # MqttBroadcastController **Kind:** Controller **Source:** [`integration/microservices/src/mqtt/mqtt-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt-broadcast.controller.ts#L11) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ MqttBroadcastController client->>+p1: MqttBroadcastController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `multicats` # RecipesService **Kind:** Service **Source:** [`sample/23-graphql-code-first/src/recipes/recipes.service.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/recipes/recipes.service.ts#L6) `RecipesService` provides the application’s recipe data operations for the GraphQL API. It is responsible for creating recipes, retrieving individual or all recipes, and removing recipes, typically acting as the data-access layer used by recipe resolvers. ## Methods | Method | Signature | Returns | Description | |---|---|---|---| | `create` | `create(data: NewRecipeInput)` | `Promise` | MOCK Put some real business logic here Left for demonstration purposes | | `findOneById` | `findOneById(id: string)` | `Promise` | | | `findAll` | `findAll(recipesArgs: RecipesArgs)` | `Promise` | | | `remove` | `remove(id: string)` | `Promise` | | ## Diagram ```mermaid sequenceDiagram participant Client as GraphQL Client participant Resolver as RecipesResolver participant Service as RecipesService participant Store as Recipe Data Store Client->>Resolver: createRecipe(input) Resolver->>Service: create(input) Service->>Store: Persist recipe Store-->>Service: Recipe Service-->>Resolver: Recipe Resolver-->>Client: Recipe result Client->>Resolver: recipes() Resolver->>Service: findAll() Service->>Store: Fetch recipes Store-->>Service: Recipe[] Service-->>Resolver: Recipe[] Resolver-->>Client: Recipe[] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { RecipesService } from './recipes.service'; import { NewRecipeInput } from './dto/new-recipe.input'; @Injectable() export class RecipeImportService { constructor(private readonly recipesService: RecipesService) {} async importRecipe(input: NewRecipeInput) { const recipe = await this.recipesService.create(input); return recipe; } async getRecipe(id: string) { return this.recipesService.findOneById(id); } async listRecipes() { return this.recipesService.findAll(); } async deleteRecipe(id: string): Promise { return this.recipesService.remove(id); } } ``` ## AI Coding Instructions - Keep business and persistence logic in `RecipesService`; GraphQL resolvers should primarily map GraphQL arguments to service calls. - Preserve the asynchronous `Promise` return types for all data operations, even when using an in-memory store. - Use `findOneById()` for single-recipe lookups and handle missing recipe behavior consistently with the GraphQL resolver contract. - Ensure `remove()` returns a boolean indicating whether a recipe was successfully removed. - When adding recipe fields or inputs, update the corresponding GraphQL object types, DTOs, resolver arguments, and service logic together. # 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) ## Signature ```ts function transformException(error: (Error & { field?: string }) | undefined) ``` ## Parameters | Name | Type | |---|---| | `error` | `(Error & { field?: string }) | undefined` | # 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) 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()` is a route-handler parameter decorator that reads data from `req.body` and injects it into a controller method parameter. It can bind the entire request body or a specific property, and optionally applies pipes for validation or transformation before the handler runs. ## 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 A[HTTP Request] --> B[req.body] B --> C[@Body decorator] C --> D{Property key provided?} D -->|Yes| E[Extract req.body[property]] D -->|No| F[Use entire req.body] E --> G[Apply pipes] F --> G G --> H[Controller handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; class CreateUserDto { email: string; role: string; } @Controller('users') export class UsersController { @Post() create( @Body(new ValidationPipe()) body: CreateUserDto, @Body('role', new ValidationPipe()) role: string, ) { return { email: body.email, role, }; } } ``` ## AI Coding Instructions - Use `@Body()` when a handler needs the complete request payload, and `@Body('property')` when it needs only one body field. - Pass pipes after the property name, such as `@Body('email', ValidationPipe)`, so validation and transformation run on the bound value. - Ensure the request body parser for the active HTTP adapter is configured; `@Body()` depends on `req.body` being populated. - Keep DTO validation at the body or field boundary rather than manually validating extracted values inside controller methods. - Avoid using a property key when nested or complete payload validation is required; bind the full DTO and validate its structure instead. # CONTROLLER_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L45) ## Definition ```ts '__controller__' ``` ## Value ```ts '__controller__' ``` # create **Kind:** API Endpoint **Source:** [`sample/11-swagger/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/cats.controller.ts#L18) Create cat The `create` endpoint handles `POST /cats` requests to create a new cat resource. It belongs to the NestJS cats controller, is documented under the `cats` Swagger tag, and exposes bearer authentication requirements through the API documentation. ## Endpoint `POST /cats` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as CatsController participant Swagger as Swagger/OpenAPI Client->>Controller: POST /cats + Bearer token + cat payload Controller->>Controller: create(createCatDto) Controller-->>Client: Creation response Swagger-->>Client: Documents operation and bearer auth ``` ## Usage ```ts const response = await fetch('https://api.example.com/cats', { method: 'POST', headers: { Authorization: 'Bearer ', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: 'Mittens', age: 3, breed: 'Tabby', }), }); if (!response.ok) { throw new Error(`Failed to create cat: ${response.status}`); } const cat = await response.json(); console.log(cat); ``` ## AI Coding Instructions - Keep this handler mapped to `POST /cats`; use a DTO such as `CreateCatDto` for request-body validation and typing. - Preserve `@ApiOperation` metadata so the endpoint remains clearly described in Swagger/OpenAPI. - Keep `@ApiBearerAuth()` aligned with the application’s actual authentication guard configuration; the decorator documents auth but does not enforce it by itself. - Return a consistent creation response, ideally including the newly created cat and an appropriate HTTP status such as `201 Created`. ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) `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] # HelloModule **Kind:** Module **Source:** [`integration/inspector/src/circular-hello/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/hello.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # 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) ## Definition ```ts { path: string; requestMethod: keyof typeof RequestMethod; version?: VersionValue; } ``` # NatsBroadcastController **Kind:** Controller **Source:** [`integration/microservices/src/nats/nats-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats-broadcast.controller.ts#L11) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ NatsBroadcastController client->>+p1: NatsBroadcastController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `multicats` # RecipesService **Kind:** Service **Source:** [`sample/33-graphql-mercurius/src/recipes/recipes.service.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/recipes/recipes.service.ts#L6) `RecipesService` encapsulates recipe data operations for the GraphQL Mercurius sample application. It provides methods to create recipes, retrieve one or many recipes, and remove recipes, serving as the backend layer used by recipe resolvers. ## Methods | Method | Signature | Returns | Description | |---|---|---|---| | `create` | `create(data: NewRecipeInput)` | `Promise` | MOCK Put some real business logic here Left for demonstration purposes | | `findOneById` | `findOneById(id: string)` | `Promise` | | | `findAll` | `findAll(recipesArgs: RecipesArgs)` | `Promise` | | | `remove` | `remove(id: string)` | `Promise` | | ## Diagram ```mermaid sequenceDiagram participant Resolver as GraphQL Resolver participant Service as RecipesService participant Store as Recipe Data Store Resolver->>Service: create(recipeInput) Service->>Store: persist recipe Store-->>Service: Recipe Service-->>Resolver: Promise Resolver->>Service: findOneById(id) Service->>Store: lookup recipe by ID Store-->>Service: Recipe Service-->>Resolver: Promise Resolver->>Service: findAll() Service->>Store: retrieve recipes Store-->>Service: Recipe[] Service-->>Resolver: Promise Resolver->>Service: remove(id) Service->>Store: delete recipe by ID Store-->>Service: deletion result Service-->>Resolver: Promise ``` ## Usage ```ts import { RecipesService } from './recipes.service'; async function manageRecipes(recipesService: RecipesService) { const recipe = await recipesService.create({ title: 'Chocolate Cake', description: 'A rich and moist chocolate cake.', ingredients: ['flour', 'cocoa powder', 'eggs', 'sugar'], }); const savedRecipe = await recipesService.findOneById(recipe.id); const allRecipes = await recipesService.findAll(); const removed = await recipesService.remove(recipe.id); return { savedRecipe, total: allRecipes.length, removed }; } ``` ## AI Coding Instructions - Inject `RecipesService` into GraphQL resolvers rather than accessing recipe storage directly. - Preserve the asynchronous `Promise` return types when adding or updating service methods. - Use `findOneById()` before performing operations that depend on a recipe existing, and handle missing-record behavior consistently with the resolver layer. - Keep GraphQL-specific concerns, such as argument parsing and GraphQL error formatting, in resolvers; keep recipe operations in this service. - When adding fields to `Recipe`, update the create flow and related GraphQL input/output types together. # RouterExplorer **Kind:** Class **Source:** [`packages/core/router/router-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-explorer.ts#L57) `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. # 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) 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()` is a route-handler parameter decorator that reads data from `req.body` and injects it into a controller method parameter. It can bind the entire request body or a specific property, and optionally applies pipes for validation or transformation before the handler runs. ## 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 A[HTTP Request] --> B[req.body] B --> C[@Body decorator] C --> D{Property key provided?} D -->|Yes| E[Extract req.body[property]] D -->|No| F[Use entire req.body] E --> G[Apply pipes] F --> G G --> H[Controller handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; class CreateUserDto { email: string; role: string; } @Controller('users') export class UsersController { @Post() create( @Body(new ValidationPipe()) body: CreateUserDto, @Body('role', new ValidationPipe()) role: string, ) { return { email: body.email, role, }; } } ``` ## AI Coding Instructions - Use `@Body()` when a handler needs the complete request payload, and `@Body('property')` when it needs only one body field. - Pass pipes after the property name, such as `@Body('email', ValidationPipe)`, so validation and transformation run on the bound value. - Ensure the request body parser for the active HTTP adapter is configured; `@Body()` depends on `req.body` being populated. - Keep DTO validation at the body or field boundary rather than manually validating extracted values inside controller methods. - Avoid using a property key when nested or complete payload validation is required; bind the full DTO and validate its structure instead. # 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) 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. # create **Kind:** API Endpoint **Source:** [`sample/01-cats-app/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.controller.ts#L14) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) `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] # HelloModule **Kind:** Module **Source:** [`integration/scopes/src/circular-hello/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/hello.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # 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) ## Definition ```ts (req: Req, res: Res, next: (err?: unknown) => void) => void ``` # RedisBroadcastController **Kind:** Controller **Source:** [`integration/microservices/src/redis/redis-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis-broadcast.controller.ts#L11) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RedisBroadcastController client->>+p1: RedisBroadcastController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `multicats` # RolesGuard **Kind:** Service **Source:** [`integration/inspector/src/common/guards/roles.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/common/guards/roles.guard.ts#L4) `RolesGuard` is a NestJS authorization guard that determines whether an incoming request can access a route based on role requirements. It runs after authentication, reads role metadata configured on handlers or controllers, and allows or blocks execution before the route handler is called. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean` | ## Dependencies - `Reflector` ## Where it refuses work - `RolesGuard` stops the work with an early return when `!roles`. ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant RolesGuard participant Reflector participant Handler Client->>NestJS: Request with authenticated user NestJS->>RolesGuard: canActivate(context) RolesGuard->>Reflector: Read required role metadata Reflector-->>RolesGuard: Required roles RolesGuard->>RolesGuard: Compare user roles to requirements alt User has required role RolesGuard-->>NestJS: true NestJS->>Handler: Execute route handler Handler-->>Client: Response else User lacks required role RolesGuard-->>NestJS: false NestJS-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { RolesGuard } from './common/guards/roles.guard'; import { Roles } from './common/decorators/roles.decorator'; @Controller('admin') @UseGuards(RolesGuard) export class AdminController { @Get('reports') @Roles('admin') getReports() { return { message: 'Admin-only report data' }; } } ``` ## AI Coding Instructions - Apply `RolesGuard` after an authentication guard so `request.user` is populated before role validation runs. - Define route or controller role requirements through the project’s role metadata decorator rather than hard-coding roles in the guard. - Preserve support for both handler-level and controller-level metadata when updating `canActivate()`. - Return `true` only when authorization requirements are satisfied; use NestJS exceptions where the existing authorization convention requires explicit error responses. - Keep role names and user-role property access aligned with the application’s authentication payload contract. ## Relationships - DEPENDS_ON β†’ `Reflector` # TestingInjector **Kind:** Class **Source:** [`packages/testing/testing-injector.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-injector.ts#L23) `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. # 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) 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()` is a route-handler parameter decorator that reads data from `req.body` and injects it into a controller method parameter. It can bind the entire request body or a specific property, and optionally applies pipes for validation or transformation before the handler runs. ## 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 A[HTTP Request] --> B[req.body] B --> C[@Body decorator] C --> D{Property key provided?} D -->|Yes| E[Extract req.body[property]] D -->|No| F[Use entire req.body] E --> G[Apply pipes] F --> G G --> H[Controller handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; class CreateUserDto { email: string; role: string; } @Controller('users') export class UsersController { @Post() create( @Body(new ValidationPipe()) body: CreateUserDto, @Body('role', new ValidationPipe()) role: string, ) { return { email: body.email, role, }; } } ``` ## AI Coding Instructions - Use `@Body()` when a handler needs the complete request payload, and `@Body('property')` when it needs only one body field. - Pass pipes after the property name, such as `@Body('email', ValidationPipe)`, so validation and transformation run on the bound value. - Ensure the request body parser for the active HTTP adapter is configured; `@Body()` depends on `req.body` being populated. - Keep DTO validation at the body or field boundary rather than manually validating extracted values inside controller methods. - Avoid using a property key when nested or complete payload validation is required; bind the full DTO and validate its structure instead. # create **Kind:** API Endpoint **Source:** [`sample/10-fastify/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/cats.controller.ts#L14) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # CUSTOM_ROUTE_ARGS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L19) ## Definition ```ts '__customRouteArgs__' ``` ## Value ```ts '__customRouteArgs__' ``` # 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) `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. # HelloModule **Kind:** Module **Source:** [`integration/scopes/src/circular-transient/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/hello.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_DECLARES β†’ `testcontroller` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # 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) ## Definition ```ts | ForwardReference | Type | DynamicModule | Promise ``` # RMQBroadcastController **Kind:** Controller **Source:** [`integration/microservices/src/rmq/rmq-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq-broadcast.controller.ts#L11) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RMQBroadcastController client->>+p1: RMQBroadcastController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `multicats` # RolesGuard **Kind:** Service **Source:** [`sample/01-cats-app/src/common/guards/roles.guard.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/guards/roles.guard.ts#L5) `RolesGuard` is a NestJS authorization guard that determines whether the current request can access a route based on role metadata. It runs after authentication, reads the roles required by a controller or handler, and compares them against the authenticated user's assigned roles. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean` | ## Dependencies - `Reflector` ## Where it refuses work - `RolesGuard` stops the work with an early return when `!roles`. ## Diagram ```mermaid sequenceDiagram participant Client participant Guard as RolesGuard participant Reflector participant Request participant Handler Client->>Guard: Request protected route Guard->>Reflector: Read @Roles() metadata Reflector-->>Guard: Required roles Guard->>Request: Read request.user Request-->>Guard: Authenticated user roles alt User has a required role Guard-->>Handler: true Handler-->>Client: Return response else User lacks required role Guard-->>Client: Deny request (403 Forbidden) end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Roles } from './common/decorators/roles.decorator'; import { RolesGuard } from './common/guards/roles.guard'; import { AuthGuard } from './common/guards/auth.guard'; @Controller('admin') @UseGuards(AuthGuard, RolesGuard) export class AdminController { @Get('reports') @Roles('admin') getReports() { return { message: 'Admin-only report data' }; } } ``` ## AI Coding Instructions - Apply `RolesGuard` after an authentication guard so `request.user` is available before role validation. - Define required roles with the `@Roles()` decorator on route handlers or controllers; ensure the metadata key matches the guard's reflector lookup. - Return `true` from `canActivate()` for routes without role metadata when they should remain accessible to authenticated users. - Ensure the authenticated user object includes a consistent roles field, such as `user.roles: string[]`. - Keep authorization logic in guards rather than duplicating role checks inside controllers or services. ## Relationships - DEPENDS_ON β†’ `Reflector` # 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) `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) # AbstractWsAdapter **Kind:** Class **Source:** [`packages/websockets/adapters/ws-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/adapters/ws-adapter.ts#L13) `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. # 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) 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()` is a route-handler parameter decorator that reads data from `req.body` and injects it into a controller method parameter. It can bind the entire request body or a specific property, and optionally applies pipes for validation or transformation before the handler runs. ## 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 A[HTTP Request] --> B[req.body] B --> C[@Body decorator] C --> D{Property key provided?} D -->|Yes| E[Extract req.body[property]] D -->|No| F[Use entire req.body] E --> G[Apply pipes] F --> G G --> H[Controller handler parameter] ``` ## Usage ```typescript import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; class CreateUserDto { email: string; role: string; } @Controller('users') export class UsersController { @Post() create( @Body(new ValidationPipe()) body: CreateUserDto, @Body('role', new ValidationPipe()) role: string, ) { return { email: body.email, role, }; } } ``` ## AI Coding Instructions - Use `@Body()` when a handler needs the complete request payload, and `@Body('property')` when it needs only one body field. - Pass pipes after the property name, such as `@Body('email', ValidationPipe)`, so validation and transformation run on the bound value. - Ensure the request body parser for the active HTTP adapter is configured; `@Body()` depends on `req.body` being populated. - Keep DTO validation at the body or field boundary rather than manually validating extracted values inside controller methods. - Avoid using a property key when nested or complete payload validation is required; bind the full DTO and validate its structure instead. # create **Kind:** API Endpoint **Source:** [`sample/36-hmr-esm/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/cats.controller.ts#L14) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) ## Definition ```ts 'create' ``` ## Value ```ts 'create' ``` # 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) `HandlerMetadata` stores the precomputed metadata required to invoke and serialize the result of a request handler. It combines parameter-resolution details, HTTP response configuration, SSE behavior, and the response handling function so the runtime can execute handlers consistently. ## 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/Route Handler] Handler --> ResponseHandler[fnHandleResponse] Metadata --> Status[httpStatusCode] Metadata --> Headers[responseHeaders] Metadata --> SSE[isSseHandler] ResponseHandler --> Response[HTTP or SSE Response] ``` ## Usage ```ts import type { HandlerMetadata } from '@nestjs/core/helpers/handler-metadata-storage'; const handlerMetadata: HandlerMetadata = { argsLength: 2, isSseHandler: false, paramtypes: [String, Number], httpStatusCode: 200, responseHeaders: [{ name: 'Cache-Control', value: 'no-store' }], hasCustomHeaders: true, getParamsMetadata: (moduleKey, contextId, inquirerId) => { // Resolve parameter metadata for the current DI/request context. return [ { index: 0, type: 0, data: 'id', metatype: String }, { index: 1, type: 3, metatype: Number }, ]; }, fnHandleResponse: async (result, response) => { response.status(200).send(result); }, }; // The runtime uses this metadata to resolve arguments and write the response. console.log(handlerMetadata.httpStatusCode); ``` ## AI Coding Instructions - Populate `argsLength` and `paramtypes` from the handler method signature so argument resolution remains aligned with the target function. - Use `getParamsMetadata()` to resolve request-scoped parameter metadata; preserve `contextId` and `inquirerId` when working with scoped providers. - Set `isSseHandler` only for Server-Sent Events handlers, and ensure `fnHandleResponse` uses SSE-compatible response behavior in that case. - Keep `httpStatusCode`, `responseHeaders`, and `hasCustomHeaders` synchronized with route-level response decorators and metadata. - Treat `fnHandleResponse` as the final response serialization integration point; avoid writing to the response twice. # HelloModule **Kind:** Module **Source:** [`integration/scopes/src/transient/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/hello.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_DECLARES β†’ `testcontroller` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # NatsEvents **Kind:** Type **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L25) 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. # RMQFanoutExchangeProducerController **Kind:** Controller **Source:** [`integration/microservices/src/rmq/fanout-exchange-producer-rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/fanout-exchange-producer-rmq.controller.ts#L9) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RMQFanoutExchangeProducerController client->>+p1: RMQFanoutExchangeProducerController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `topicExchange` # RolesGuard **Kind:** Service **Source:** [`sample/10-fastify/src/common/guards/roles.guard.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/common/guards/roles.guard.ts#L4) `RolesGuard` is a NestJS authorization guard that determines whether an incoming request can access a route based on role metadata. It runs after authentication, reads the roles required by the controller or handler, and compares them with the authenticated user's assigned roles. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean` | ## Dependencies - `Reflector` ## Where it refuses work - `RolesGuard` stops the work with an early return when `!roles`. ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant RolesGuard participant Reflector participant Request Client->>NestJS: Request protected route NestJS->>RolesGuard: canActivate(context) RolesGuard->>Reflector: Read required role metadata Reflector-->>RolesGuard: Required roles RolesGuard->>Request: Read request.user roles Request-->>RolesGuard: Authenticated user RolesGuard-->>NestJS: true / false NestJS-->>Client: Allow request or return 403 ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { RolesGuard } from './common/guards/roles.guard'; import { Roles } from './common/decorators/roles.decorator'; @Controller('admin') @UseGuards(RolesGuard) export class AdminController { @Get('reports') @Roles('admin') getReports() { return { message: 'Admin-only report data' }; } } ``` Ensure an authentication guard runs before `RolesGuard` and attaches a user with roles to the request: ```ts request.user = { id: 'user-123', roles: ['admin'], }; ``` ## AI Coding Instructions - Apply `RolesGuard` to controllers or routes with `@UseGuards(RolesGuard)` and declare required roles through the project’s `@Roles(...)` decorator. - Ensure the authentication layer executes first and populates `request.user`; role checks cannot succeed without authenticated user data. - Keep role names consistent across decorators, JWT payloads, and persisted user role data (for example, use `admin` everywhere rather than mixing `ADMIN` and `admin`). - Preserve the guard’s boolean `canActivate()` contract: return `true` only when authorization is satisfied, otherwise return `false` or throw an appropriate NestJS authorization exception. ## Relationships - DEPENDS_ON β†’ `Reflector` # AudioProcessor **Kind:** Class **Source:** [`sample/26-queues/src/audio/audio.processor.ts`](https://github.com/nestjs/nest/blob/master/sample/26-queues/src/audio/audio.processor.ts#L5) `AudioProcessor` is responsible for consuming audio transcoding jobs from the queue and executing the transcoding workflow. It acts as the worker-side integration point between queued job data, audio processing logic, and job completion or failure handling. ## Methods | Method | Signature | Returns | |---|---|---| | `handleTranscode` | `handleTranscode(job: Job)` | `void` | ## Diagram ```mermaid graph LR A[Audio Job Producer] --> B[Audio Queue] B --> C[AudioProcessor] C --> D[handleTranscode] D --> E[Audio Transcoding Service] E --> F[Processed Audio Output] D --> G[Job Success / Failure Status] ``` ## Usage ```ts import { AudioProcessor } from './audio.processor'; // In typical NestJS/BullMQ usage, the queue invokes the processor // automatically when a matching job is received. const processor = new AudioProcessor(); await processor.handleTranscode({ data: { inputPath: '/uploads/source.wav', outputPath: '/processed/source.mp3', format: 'mp3', }, } as any); ``` ## AI Coding Instructions - Keep `handleTranscode()` focused on processing a single queue job and avoid placing HTTP/controller concerns in the processor. - Validate job payload fields such as source paths, output paths, and requested output format before starting transcoding. - Propagate failures by throwing errors so the queue can apply its configured retry, backoff, and failed-job behavior. - Ensure transcoding output paths are unique and cleanup temporary files when processing succeeds or fails. - When adding job types, align queue job names and payload contracts with the producer that enqueues audio work. ## Referenced By - `AppModule` (MODULE_PROVIDES) - `AudioModule` (MODULE_PROVIDES) # 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) 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. # create **Kind:** API Endpoint **Source:** [`integration/inspector/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/cats.controller.ts#L13) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) ## Definition ```ts 'register' ``` ## Value ```ts 'register' ``` # HelloModule **Kind:** Module **Source:** [`integration/scopes/src/inject-inquirer/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello.module.ts#L8) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_PROVIDES β†’ `HelloRequestService` - MODULE_PROVIDES β†’ `HelloTransientService` - MODULE_PROVIDES β†’ `RequestLogger` - MODULE_PROVIDES β†’ `TransientLogger` - MODULE_PROVIDES β†’ `Logger` # 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) `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. # PartitionAssigner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L184) ## Definition ```ts (config: { cluster: Cluster; groupId: string; logger: Logger; }) => Assigner ``` # RMQTopicExchangeController **Kind:** Controller **Source:** [`integration/microservices/src/rmq/topic-exchange-rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/topic-exchange-rmq.controller.ts#L12) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RMQTopicExchangeController client->>+p1: RMQTopicExchangeController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `topicExchange` # RolesGuard **Kind:** Service **Source:** [`sample/36-hmr-esm/src/common/guards/roles.guard.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/guards/roles.guard.ts#L5) `RolesGuard` is a NestJS authorization guard that determines whether an incoming request is allowed to access a protected route. Its `canActivate()` method runs before the route handler, inspecting the request context and returning `true` to continue or `false` to deny access. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean` | ## Dependencies - `Reflector` ## Where it refuses work - `RolesGuard` stops the work with an early return when `!roles`. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant RolesGuard participant Handler Client->>Controller: HTTP request Controller->>RolesGuard: canActivate(context) RolesGuard->>RolesGuard: Inspect request/user roles alt Access allowed RolesGuard-->>Controller: true Controller->>Handler: Execute route handler Handler-->>Client: Response else Access denied RolesGuard-->>Controller: false Controller-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { RolesGuard } from './common/guards/roles.guard'; @Controller('admin') @UseGuards(RolesGuard) export class AdminController { @Get() getAdminDashboard() { return { message: 'Admin-only content' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` focused on authorization decisions and always return a boolean result. - Access request-specific data through NestJS's `ExecutionContext`, typically using `context.switchToHttp().getRequest()`. - Ensure authentication middleware or guards populate `request.user` before `RolesGuard` executes. - Apply the guard with `@UseGuards(RolesGuard)` at the controller or route-handler level. - Do not rely on client-provided role values; validate roles from trusted authenticated user data. ## Relationships - DEPENDS_ON β†’ `Reflector` # 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) 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. # ContextCreator **Kind:** Class **Source:** [`packages/core/helpers/context-creator.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-creator.ts#L5) `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. # create **Kind:** API Endpoint **Source:** [`integration/inspector/src/database/database.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.controller.ts#L18) ## Endpoint `POST /database` ## Referenced By - `DatabaseController` (MODULE_DECLARES) # 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) 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. # InjectSameNameModule **Kind:** Module **Source:** [`integration/injector/src/inject/inject-same-name.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/inject/inject-same-name.module.ts#L8) # 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) `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. # ReflectableDecorator **Kind:** Type **Source:** [`packages/core/services/reflector.service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/services/reflector.service.ts#L31) ## Definition ```ts (( opts?: TParam, ) => CustomDecorator) & { KEY: string; } ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/scopes/src/hello/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/users/user-by-id.pipe.ts#L9) `UserByIdPipe` is a NestJS pipe that transforms an incoming user ID parameter into a user domain object or validated value. It is intended for controller boundaries, keeping user lookup and parameter validation logic out of route handlers. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Dependencies - `UsersService` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant UserByIdPipe participant UserService Client->>Controller: GET /users/:id Controller->>UserByIdPipe: transform(id) UserByIdPipe->>UserService: Find user by ID UserService-->>UserByIdPipe: User or not found UserByIdPipe-->>Controller: Resolved user Controller-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':id') getUser(@Param('id', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Use `UserByIdPipe` at controller parameter boundaries with `@Param('id', UserByIdPipe)`. - Keep user lookup, ID validation, and not-found error handling inside `transform()`, not in controllers. - Ensure `transform()` returns a consistent user representation expected by downstream handlers. - Throw appropriate NestJS HTTP exceptions when the supplied ID is invalid or no matching user exists. - Preserve dependency injection patterns when adding repositories or user services to the pipe. ## Relationships - DEPENDS_ON β†’ `usersservice` # UsersController **Kind:** Controller **Source:** [`integration/inspector/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ UsersController client->>+p1: UsersController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `update` - MODULE_DECLARES β†’ `remove` - DEPENDS_ON β†’ `usersservice` # 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) 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()`. # create **Kind:** API Endpoint **Source:** [`integration/inspector/src/dogs/dogs.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.controller.ts#L18) ## Endpoint `POST /dogs` ## Referenced By - `DogsController` (MODULE_DECLARES) # DISCONNECT_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L13) ## Definition ```ts 'disconnect' ``` ## Value ```ts 'disconnect' ``` # 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) `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. # IntegrationModule **Kind:** Module **Source:** [`integration/module-utils/src/integration.module.ts`](https://github.com/nestjs/nest/blob/master/integration/module-utils/src/integration.module.ts#L8) # KafkaConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L60) `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. # 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) ## Definition ```ts ( req: TRequest, res: TResponse, next?: Function, ) => any ``` # UsersController **Kind:** Controller **Source:** [`integration/repl/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ UsersController client->>+p1: UsersController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `update` - MODULE_DECLARES β†’ `remove` - DEPENDS_ON β†’ `usersservice` # UsersService **Kind:** Service **Source:** [`sample/07-sequelize/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.service.ts#L6) `UsersService` encapsulates user persistence operations for the Sequelize-backed NestJS application. It provides the application layer for creating, retrieving, and removing `User` records while keeping database access logic out of controllers. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createUserDto: CreateUserDto)` | `Promise` | | `findAll` | `findAll()` | `Promise` | | `findOne` | `findOne(id: string)` | `Promise` | | `remove` | `remove(id: string)` | `Promise` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as UsersController participant Service as UsersService participant Model as Sequelize User Model participant DB as Database Client->>Controller: Request user operation Controller->>Service: create() / findAll() / findOne() / remove() Service->>Model: Execute Sequelize query Model->>DB: Run SQL operation DB-->>Model: Return records/result Model-->>Service: Return User or User[] Service-->>Controller: Return operation result Controller-->>Client: Send HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users.service'; import { User } from './user.entity'; @Injectable() export class UsersController { constructor(private readonly usersService: UsersService) {} async listUsers(): Promise { return this.usersService.findAll(); } async getUser(): Promise { return this.usersService.findOne(); } async createUser(): Promise { return this.usersService.create(); } async deleteUser(): Promise { await this.usersService.remove(); } } ``` ## AI Coding Instructions - Keep database operations inside `UsersService`; controllers should delegate to service methods rather than querying Sequelize models directly. - Preserve the asynchronous return contracts: `create()` and `findOne()` return `Promise`, `findAll()` returns `Promise`, and `remove()` returns `Promise`. - Use the injected Sequelize `User` model for persistence so the service remains compatible with NestJS dependency injection. - Add validation and meaningful not-found handling before updating or deleting records when extending the service. - Update related controller, module, DTO, and model definitions together when adding new user fields or service operations. # 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) 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()` is a class decorator that marks a class as a NestJS controller. It establishes the controller's route prefix and metadata, allowing Nest to discover its HTTP route handlers or microservice message/event handlers during application startup. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[Nest Application] --> B[Controller decorator] B --> C[Controller class metadata] C --> D[HTTP route handlers] C --> E[Microservice message handlers] D --> F[Inbound HTTP requests] E --> G[Inbound messages and events] F --> H[Responses] G --> I[Message results or event processing] ``` ## Usage ```ts import { Controller, Get, Param, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id, name: 'Ada Lovelace' }; } @Post() create(@Body() payload: { name: string }) { return { id: crypto.randomUUID(), ...payload, }; } } // Routes: // GET /users/:id // POST /users ``` ## AI Coding Instructions - Apply `@Controller()` only to classes that group related HTTP routes or microservice handlers. - Use a route prefix such as `@Controller('users')` to keep handler paths concise and consistently scoped. - Define request-method decorators such as `@Get()`, `@Post()`, or message-pattern decorators on methods inside the controller class. - Keep controllers focused on transport concerns; delegate business logic and data access to injected providers/services. - Ensure the controller is registered in the appropriate Nest module's `controllers` array. # create **Kind:** API Endpoint **Source:** [`integration/inspector/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.controller.ts#L18) ## Endpoint `POST /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # DISCONNECTED_RMQ_MESSAGE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L58) ## Definition ```ts `Disconnected from RMQ. Trying to reconnect.` ``` ## Value ```ts `Disconnected from RMQ. Trying to reconnect.` ``` # 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) `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. # ModuleRefGetOrResolveOpts **Kind:** Interface **Source:** [`packages/core/injector/module-ref.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/module-ref.ts#L12) `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. # MyDynamicModule **Kind:** Module **Source:** [`sample/18-context/src/my-dynamic.module.ts`](https://github.com/nestjs/nest/blob/master/sample/18-context/src/my-dynamic.module.ts#L3) # RequestQueueSizeEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L432) ## Definition ```ts InstrumentationEvent<{ broker: string; clientId: string; queueSize: number; }> ``` # UsersController **Kind:** Controller **Source:** [`sample/05-sql-typeorm/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.controller.ts#L14) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ UsersController client->>+p1: UsersController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `remove` - DEPENDS_ON β†’ `usersservice` # UsersService **Kind:** Service **Source:** [`integration/repl/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.service.ts#L6) `UsersService` provides the backend business-logic layer for user resource operations in the REPL integration application. It exposes standard CRUD methods that are typically called by a users controller and delegates persistence or external integration work to the appropriate data layer. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createUserDto: CreateUserDto)` | `unknown` | | `findAll` | `findAll()` | `unknown` | | `findOne` | `findOne(id: number)` | `unknown` | | `update` | `update(id: number, updateUserDto: UpdateUserDto)` | `unknown` | | `remove` | `remove(id: number)` | `unknown` | ## Dependencies - `UsersRepository` ## Diagram ```mermaid sequenceDiagram participant Client participant UsersController participant UsersService participant DataStore Client->>UsersController: Request user operation UsersController->>UsersService: create/findAll/findOne/update/remove UsersService->>DataStore: Perform user data operation DataStore-->>UsersService: Return result UsersService-->>UsersController: Return user data or status UsersController-->>Client: Send HTTP response ``` ## Usage ```ts import { UsersService } from './users.service'; async function manageUsers(usersService: UsersService) { // Create a user const createdUser = await usersService.create(); // List users const users = await usersService.findAll(); // Retrieve one user const user = await usersService.findOne(); // Update a user const updatedUser = await usersService.update(); // Remove a user await usersService.remove(); return { createdUser, users, user, updatedUser }; } ``` ## AI Coding Instructions - Keep controller code focused on HTTP request handling; place user-related business logic in `UsersService`. - Preserve the existing CRUD method structure: `create`, `findAll`, `findOne`, `update`, and `remove`. - Define explicit DTOs and return types when implementing methods instead of leaving production code typed as `unknown`. - Inject repositories, databases, or external clients through NestJS dependency injection rather than constructing them directly in service methods. - Add validation, not-found handling, and authorization checks before performing update or delete operations. ## Relationships - DEPENDS_ON β†’ `UsersRepository` # 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) 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()` is a class decorator that marks a class as a NestJS controller. It establishes the controller's route prefix and metadata, allowing Nest to discover its HTTP route handlers or microservice message/event handlers during application startup. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[Nest Application] --> B[Controller decorator] B --> C[Controller class metadata] C --> D[HTTP route handlers] C --> E[Microservice message handlers] D --> F[Inbound HTTP requests] E --> G[Inbound messages and events] F --> H[Responses] G --> I[Message results or event processing] ``` ## Usage ```ts import { Controller, Get, Param, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id, name: 'Ada Lovelace' }; } @Post() create(@Body() payload: { name: string }) { return { id: crypto.randomUUID(), ...payload, }; } } // Routes: // GET /users/:id // POST /users ``` ## AI Coding Instructions - Apply `@Controller()` only to classes that group related HTTP routes or microservice handlers. - Use a route prefix such as `@Controller('users')` to keep handler paths concise and consistently scoped. - Define request-method decorators such as `@Get()`, `@Post()`, or message-pattern decorators on methods inside the controller class. - Keep controllers focused on transport concerns; delegate business logic and data access to injected providers/services. - Ensure the controller is registered in the appropriate Nest module's `controllers` array. # create **Kind:** API Endpoint **Source:** [`integration/mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/cats.controller.ts#L10) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # DYNAMIC_TOKEN **Kind:** Constant **Source:** [`integration/injector/src/dynamic/dynamic.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/dynamic/dynamic.module.ts#L3) ## Definition ```ts 'DYNAMIC_TOKEN' ``` ## Value ```ts 'DYNAMIC_TOKEN' ``` # NestDynamicModule **Kind:** Module **Source:** [`integration/injector/src/dynamic/dynamic.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/dynamic/dynamic.module.ts#L11) # 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) 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. # RouterProxyCallback **Kind:** Type **Source:** [`packages/core/router/router-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-proxy.ts#L4) ## Definition ```ts ( req: TRequest, res: TResponse, next: () => void, ) => void | Promise ``` # TestingModule **Kind:** Class **Source:** [`packages/testing/testing-module.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-module.ts#L26) `TestingModule` is the compiled test application context returned by Nest's testing utilities. It resolves providers for tests and can create either an HTTP Nest application or a Nest microservice using the configured module metadata. **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[TestingModule.compile()] B --> C[TestingModule] C --> D[Resolve test providers] C --> E[createNestApplication()] C --> F[createNestMicroservice()] E --> G[INestApplication] F --> H[INestMicroservice] ``` ## Usage ```ts import { Test } from '@nestjs/testing'; import { AppModule } from '../src/app.module'; import { AppService } from '../src/app.service'; describe('App', () => { let testingModule; let app; beforeAll(async () => { testingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = testingModule.createNestApplication(); await app.init(); }); it('resolves application providers', () => { const appService = testingModule.get(AppService); expect(appService).toBeDefined(); }); afterAll(async () => { await app.close(); }); }); ``` ## AI Coding Instructions - Create a `TestingModule` through `Test.createTestingModule(...).compile()` before resolving providers or creating an application. - Use `testingModule.get()` to retrieve providers and `overrideProvider()` on the testing module builder when replacing dependencies with mocks. - Call `await app.init()` after `createNestApplication()` before sending HTTP requests to the application. - Close created applications or microservices in teardown hooks to release transports, database connections, and open handles. - Use `createNestMicroservice()` when testing message-based transport behavior instead of HTTP controller routes. ## How it works ## `TestingModule` `TestingModule` is a public class that extends `NestApplicationContext`. It holds a Nest container, graph inspector, root context module, application configuration, and an optional module-selection scope supplied at construction. Its constructor passes an empty context-options object to the parent context and stores the graph inspector. [packages/testing/testing-module.ts:23-40] A `TestingModuleBuilder.compile()` constructs this class after scanning the configured module, applying overrides, creating dependency instances, applying application providers, and locating the root module. [packages/testing/testing-module.builder.ts:97-131] Because it extends `NestApplicationContext`, a `TestingModule` also has inherited context operations such as `get()` and `select()`. `get()` searches globally by default, or restricts lookup to the selected context module when `strict` is set; `select()` throws `UnknownModuleException` if its requested module is absent. [packages/core/nest-application-context.ts:92-129] [packages/core/nest-application-context.ts:165-175] ## Creating an HTTP application `createNestApplication()` has two call forms: - `createNestApplication(httpAdapter, options?)` - `createNestApplication(options?)` [packages/testing/testing-module.ts:52-66] At runtime, the method treats its first argument as an HTTP server or adapter only when it is truthy and has a truthy `patch` property. Otherwise, it treats that argument as application options and creates a default adapter. [packages/testing/testing-module.ts:42-50] [packages/testing/testing-module.ts:67-69] For either form, it: 1. Applies `options.logger` when that property is not `undefined`. [packages/testing/testing-module.ts:71] [packages/testing/testing-module.ts:110-115] 2. Stores the selected adapter in the Nest container; if an internal HTTP-adapter host already exists, this also assigns the adapter to that host. [packages/testing/testing-module.ts:72] [packages/core/injector/container.ts:74-82] 3. Creates a `NestApplication` with the shared container, adapter, application configuration, graph inspector, and application options. [packages/testing/testing-module.ts:74-80] 4. Returns a proxy around that application. For a property absent from the `NestApplication` target but present on the adapter, the proxy returns the adapter’s property; otherwise, it returns the application’s property. [packages/testing/testing-module.ts:81] [packages/testing/testing-module.ts:117-125] Constructing the underlying `NestApplication` selects its context module and registers an HTTP server. Server registration calls the adapter’s `initHttpServer()` with application options, then obtains the underlying HTTP server. [packages/core/nest-application.ts:74-96] [packages/core/nest-application.ts:115-137] When no adapter is passed, the default-adapter path dynamically loads `@nestjs/platform-express` and creates an `ExpressAdapter`. If that package cannot be loaded, `loadPackage()` logs that the dependency is missing, flushes logs, and exits the process with status `1`. [packages/testing/testing-module.ts:67-69] [packages/testing/testing-module.ts:101-108] [packages/common/utils/load-package.util.ts:8-19] ## Creating a microservice `createNestMicroservice(options)` dynamically loads `NestMicroservice` from `@nestjs/microservices`, applies the logger option, and returns a new microservice constructed with the module’s container, options, graph inspector, and application configuration. [packages/testing/testing-module.ts:84-99] The `options` parameter is typed as `NestMicroserviceOptions & T`; `NestMicroserviceOptions` is an alias of `NestApplicationContextOptions`. [packages/testing/testing-module.ts:84-86] [packages/common/interfaces/microservices/nest-microservice-options.interface.ts:1-7] If `@nestjs/microservices` cannot be loaded, the shared package loader logs the missing-dependency message, flushes logs, and exits the process with status `1`. [packages/testing/testing-module.ts:87-91] [packages/common/utils/load-package.util.ts:8-19] ## Logger side effect For either application or microservice creation, no logger change occurs when options are absent or `options.logger` is `undefined`. Otherwise, the class calls the static `Logger.overrideLogger()`. [packages/testing/testing-module.ts:110-115] `Logger.overrideLogger()` sets global log levels for an array, installs an object logger as the static logger reference, or clears that static reference for non-object values such as `false`. It throws when passed a subclass of `Logger` rather than `Logger` itself. [packages/common/services/logger.service.ts:312-327] # UsersController **Kind:** Controller **Source:** [`sample/07-sequelize/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ UsersController client->>+p1: UsersController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `findOne` - MODULE_DECLARES β†’ `remove` - DEPENDS_ON β†’ `usersservice` # UsersService **Kind:** Service **Source:** [`sample/05-sql-typeorm/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.service.ts#L7) `UsersService` encapsulates user persistence operations for the NestJS application using TypeORM. It provides the application’s user creation, retrieval, and deletion behavior while keeping database access logic out of controllers. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createUserDto: CreateUserDto)` | `Promise` | | `findAll` | `findAll()` | `Promise` | | `findOne` | `findOne(id: number)` | `Promise` | | `remove` | `remove(id: string)` | `Promise` | ## Dependencies - `Repository` ## Diagram ```mermaid sequenceDiagram participant Controller as UsersController participant Service as UsersService participant Repository as TypeORM User Repository participant DB as Database Controller->>Service: create/createUserDto Service->>Repository: create(dto) Service->>Repository: save(user) Repository->>DB: INSERT users DB-->>Repository: persisted user Repository-->>Service: User Service-->>Controller: User Controller->>Service: findAll() Service->>Repository: find() Repository->>DB: SELECT users DB-->>Repository: user records Repository-->>Service: User[] Service-->>Controller: User[] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class UsersController { constructor(private readonly usersService: UsersService) {} async createUser() { return this.usersService.create({ firstName: 'Ada', lastName: 'Lovelace', email: 'ada@example.com', }); } async listUsers() { return this.usersService.findAll(); } async getUser(id: number) { return this.usersService.findOne(id); } async deleteUser(id: number): Promise { await this.usersService.remove(id); } } ``` ## AI Coding Instructions - Inject the TypeORM `Repository` through NestJS dependency injection rather than creating database connections directly. - Keep controller methods thin; delegate user persistence and lookup logic to `UsersService`. - Ensure `findOne()` and `remove()` handle missing users consistently, typically by throwing `NotFoundException`. - Use DTOs for create and update inputs instead of accepting raw request bodies or entity instances directly. - Update the related NestJS module to register the `User` entity with `TypeOrmModule.forFeature([User])`. ## Relationships - DEPENDS_ON β†’ `repository` # 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) `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. # AdditionalHeaders **Kind:** Type **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L38) ## Definition ```ts Record< string, string[] | string | number | undefined > ``` # AppController **Kind:** Controller **Source:** [`sample/21-serializer/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/app.controller.ts#L10) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `findOne` # 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) 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()` is a class decorator that marks a class as a NestJS controller. It establishes the controller's route prefix and metadata, allowing Nest to discover its HTTP route handlers or microservice message/event handlers during application startup. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[Nest Application] --> B[Controller decorator] B --> C[Controller class metadata] C --> D[HTTP route handlers] C --> E[Microservice message handlers] D --> F[Inbound HTTP requests] E --> G[Inbound messages and events] F --> H[Responses] G --> I[Message results or event processing] ``` ## Usage ```ts import { Controller, Get, Param, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id, name: 'Ada Lovelace' }; } @Post() create(@Body() payload: { name: string }) { return { id: crypto.randomUUID(), ...payload, }; } } // Routes: // GET /users/:id // POST /users ``` ## AI Coding Instructions - Apply `@Controller()` only to classes that group related HTTP routes or microservice handlers. - Use a route prefix such as `@Controller('users')` to keep handler paths concise and consistently scoped. - Define request-method decorators such as `@Get()`, `@Post()`, or message-pattern decorators on methods inside the controller class. - Keep controllers focused on transport concerns; delegate business logic and data access to injected providers/services. - Ensure the controller is registered in the appropriate Nest module's `controllers` array. # create **Kind:** API Endpoint **Source:** [`integration/repl/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.controller.ts#L18) ## Endpoint `POST /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # DYNAMIC_VALUE **Kind:** Constant **Source:** [`integration/injector/src/dynamic/dynamic.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/dynamic/dynamic.module.ts#L4) ## Definition ```ts {} ``` ## Value ```ts {} ``` # NestedTransientModule **Kind:** Module **Source:** [`integration/scopes/src/nested-transient/nested-transient.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/nested-transient/nested-transient.module.ts#L8) ## Relationships - MODULE_DECLARES β†’ `NestedTransientController` - MODULE_PROVIDES β†’ `FirstRequestService` - MODULE_PROVIDES β†’ `SecondRequestService` - MODULE_PROVIDES β†’ `TransientLoggerService` - MODULE_PROVIDES β†’ `NestedTransientService` # 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) `RedisOptions` configures a Redis-based microservice transport. It combines NestJS Redis transport settings with `IORedisOptions`, including connection details, retry behavior, optional wildcard subscriptions, and custom message serialization. ## Properties | Property | Type | |---|---| | `transport` | `Transport.REDIS` | | `options` | `{ host?: string; port?: number; retryAttempts?: number; retryDelay?: number; /** * Use `psubscribe`/`pmessage` to enable wildcards in the patterns */ wildcards?: boolean; serializer?: Serializer; deserializer?: Deserializer; } & IORedisOptions` | ## Diagram ```mermaid graph LR A[RedisOptions] --> B[transport: Transport.REDIS] A --> C[options] C --> D[Redis connection settings] C --> E[Retry settings] C --> F[wildcards] C --> G[serializer / deserializer] C --> H[IORedisOptions] F --> I[psubscribe / pmessage] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { Transport, type RedisOptions } from '@nestjs/microservices'; import { AppModule } from './app.module'; const redisConfig: RedisOptions = { transport: Transport.REDIS, options: { host: 'localhost', port: 6379, retryAttempts: 5, retryDelay: 3000, wildcards: true, // Any supported ioredis options can also be provided. password: process.env.REDIS_PASSWORD, }, }; async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, redisConfig); await app.listen(); } bootstrap(); ``` ## AI Coding Instructions - Always set `transport` to `Transport.REDIS`; this interface is intended specifically for Redis microservices. - Put Redis connection and `ioredis` configuration inside `options`, including `host`, `port`, authentication, TLS, and reconnect settings. - Enable `wildcards: true` only when message patterns require wildcard matching, as it uses Redis `psubscribe` and `pmessage`. - Configure `retryAttempts` and `retryDelay` to match deployment reliability requirements and avoid overly aggressive reconnect loops. - Provide custom `serializer` and `deserializer` only when both communicating services agree on the same message format. ## How it works - `RedisOptions` is a public TypeScript interface for selecting the Redis microservice transport. Its optional `transport` field is typed as `Transport.REDIS`, and its optional `options` field holds Redis and message-processing configuration. It is one member of the `MicroserviceOptions` union. [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:120-137](packages/microservices/interfaces/microservice-configuration.interface.ts#L120-L137) - When a client configuration has `transport: Transport.REDIS`, `ClientProxyFactory` constructs a `ClientRedis`; if `options` is omitted, that factory passes `{}`. When a microservice configuration has that transport, `ServerFactory` constructs a `ServerRedis`. [packages/microservices/client/client-proxy-factory.ts:48-53](packages/microservices/client/client-proxy-factory.ts#L48-L53) [packages/microservices/server/server-factory.ts:21-40](packages/microservices/server/server-factory.ts#L21-L40) - `options.host` and `options.port` are optional connection settings. Both Redis client and server create their two Redis connections with `localhost` and `6379` first, then spread the configured options afterward, so configured `host` or `port` overrides those values. [packages/microservices/interfaces/microservice-configuration.interface.ts:125-129](packages/microservices/interfaces/microservice-configuration.interface.ts#L125-L129) [packages/microservices/constants.ts:5-6](packages/microservices/constants.ts#L5-L6) [packages/microservices/client/client-redis.ts:99-107](packages/microservices/client/client-redis.ts#L99-L107) [packages/microservices/server/server-redis.ts:115-123](packages/microservices/server/server-redis.ts#L115-L123) - The options object intersects its Nest-specific fields with `IORedisOptions`; therefore it also accepts the Redis connection settings declared there, including authentication (`username`, `password`), database selection (`db`), TLS (`tls`), connection timeouts, command timeouts, offline-queue settings, Sentinel settings, and other listed properties. [packages/microservices/interfaces/microservice-configuration.interface.ts:125-136](packages/microservices/interfaces/microservice-configuration.interface.ts#L125-L136) [packages/microservices/external/redis.interface.ts:8-16](packages/microservices/external/redis.interface.ts#L8-L16) [packages/microservices/external/redis.interface.ts:45-61](packages/microservices/external/redis.interface.ts#L45-L61) [packages/microservices/external/redis.interface.ts:110-180](packages/microservices/external/redis.interface.ts#L110-L180) [packages/microservices/external/redis.interface.ts:193-221](packages/microservices/external/redis.interface.ts#L193-L221) - Both runtime classes spread the supplied options into the constructor call for `ioredis`, set `lazyConnect: true`, and create separate publishing and subscribing clients. They load `ioredis` during construction. [packages/microservices/client/client-redis.ts:41-53](packages/microservices/client/client-redis.ts#L41-L53) [packages/microservices/client/client-redis.ts:76-94](packages/microservices/client/client-redis.ts#L76-L94) [packages/microservices/client/client-redis.ts:99-107](packages/microservices/client/client-redis.ts#L99-L107) [packages/microservices/server/server-redis.ts:42-50](packages/microservices/server/server-redis.ts#L42-L50) [packages/microservices/server/server-redis.ts:115-123](packages/microservices/server/server-redis.ts#L115-L123) - `retryAttempts` and `retryDelay` control the retry strategy installed by the Nest Redis classes. A missing or falsy `retryAttempts` logs that retry attempts were not specified and stops retrying; retries also stop after `times > retryAttempts`. When `retryDelay` is absent, the retry strategy returns `5000`; manual closure stops retries. The Nest-generated retry strategy replaces any `IORedisOptions.retryStrategy` supplied in `options`. [packages/microservices/interfaces/microservice-configuration.interface.ts:127-129](packages/microservices/interfaces/microservice-configuration.interface.ts#L127-L129) [packages/microservices/external/redis.interface.ts:8-10](packages/microservices/external/redis.interface.ts#L8-L10) [packages/microservices/client/client-redis.ts:197-204](packages/microservices/client/client-redis.ts#L197-L204) [packages/microservices/client/client-redis.ts:227-242](packages/microservices/client/client-redis.ts#L227-L242) [packages/microservices/server/server-redis.ts:253-277](packages/microservices/server/server-redis.ts#L253-L277) - `wildcards` affects server-side subscriptions only: when truthy, the server listens for Redis `pmessage` events and subscribes with `psubscribe`; otherwise it listens for `message` and calls `subscribe`. The declared comment describes this as enabling wildcard patterns. [packages/microservices/interfaces/microservice-configuration.interface.ts:130-133](packages/microservices/interfaces/microservice-configuration.interface.ts#L130-L133) [packages/microservices/server/server-redis.ts:87-105](packages/microservices/server/server-redis.ts#L87-L105) [packages/microservices/server/server-redis.ts:126-131](packages/microservices/server/server-redis.ts#L126-L131) - `serializer` and `deserializer` accept objects with `serialize` and `deserialize` methods. If omitted, Redis clients use `IdentitySerializer` and `IncomingResponseDeserializer`; Redis servers use `IdentitySerializer` and `IncomingRequestDeserializer`. [packages/microservices/interfaces/microservice-configuration.interface.ts:134-135](packages/microservices/interfaces/microservice-configuration.interface.ts#L134-L135) [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) [packages/microservices/client/client-proxy.ts:208-231](packages/microservices/client/client-proxy.ts#L208-L231) [packages/microservices/server/server.ts:297-320](packages/microservices/server/server.ts#L297-L320) - On the client, outgoing requests and events are serialized and JSON-stringified before publication. Request responses are received from `.reply`; the client subscribes to that channel before the first request and tracks subscriptions per reply channel. [packages/microservices/client/client-redis.ts:55-61](packages/microservices/client/client-redis.ts#L55-L61) [packages/microservices/client/client-redis.ts:286-324](packages/microservices/client/client-redis.ts#L286-L324) [packages/microservices/client/client-redis.ts:327-344](packages/microservices/client/client-redis.ts#L327-L344) - On the server, received payloads are JSON-parsed when possible, deserialized with `{ channel }`, and routed as an event when no request `id` exists. Requests without a matching handler result in a reply containing the request `id`, `status: 'error'`, and `NO_MESSAGE_HANDLER`; replies are serialized, JSON-stringified, and published to `.reply`. [packages/microservices/server/server-redis.ts:134-185](packages/microservices/server/server-redis.ts#L134-L185) [packages/microservices/server/server-redis.ts:189-203](packages/microservices/server/server-redis.ts#L189-L203) - The interface itself contains no runtime validation. Visible runtime error paths include: client publication catches synchronous failures and passes `{ err }` to its callback; connection errors are logged; retry exhaustion is logged; and calling `unwrap()` before initialization throws an `Error` on either client or server. [packages/microservices/client/client-redis.ts:110-113](packages/microservices/client/client-redis.ts#L110-L113) [packages/microservices/client/client-redis.ts:227-242](packages/microservices/client/client-redis.ts#L227-L242) [packages/microservices/client/client-redis.ts:218-225](packages/microservices/client/client-redis.ts#L218-L225) [packages/microservices/client/client-redis.ts:321-324](packages/microservices/client/client-redis.ts#L321-L324) [packages/microservices/server/server-redis.ts:205-207](packages/microservices/server/server-redis.ts#L205-L207) [packages/microservices/server/server-redis.ts:262-285](packages/microservices/server/server-redis.ts#L262-L285) # UsersService **Kind:** Service **Source:** [`integration/inspector/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.service.ts#L5) `UsersService` encapsulates user-related business logic for the Inspector integration backend. It provides the standard create, read, update, and delete operations consumed by the users controller or other NestJS providers. Keep transport concerns in controllers and place validation, persistence, and domain-specific user rules in this service. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createUserDto: CreateUserDto)` | `unknown` | | `findAll` | `findAll()` | `unknown` | | `findOne` | `findOne(id: number)` | `unknown` | | `update` | `update(id: number, updateUserDto: UpdateUserDto)` | `unknown` | | `remove` | `remove(id: number)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as UsersController participant Service as UsersService participant Store as User Repository/Store Client->>Controller: Request user operation Controller->>Service: create/findAll/findOne/update/remove Service->>Store: Read or modify user data Store-->>Service: User data or operation result Service-->>Controller: Return result Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class UserProfileService { constructor(private readonly usersService: UsersService) {} async loadUser(id: string) { return this.usersService.findOne(id); } async listUsers() { return this.usersService.findAll(); } async registerUser(payload: { email: string; name: string }) { return this.usersService.create(payload); } } ``` ## AI Coding Instructions - Follow NestJS dependency injection patterns: inject `UsersService` through constructors rather than instantiating it directly. - Keep HTTP request parsing, status codes, and response formatting in the controller; place user domain logic in this service. - Ensure `findOne`, `update`, and `remove` handle missing users consistently, typically by throwing an appropriate NestJS exception. - Validate create and update payloads with DTOs and `class-validator` before passing data into service operations. - Update dependent controllers, repositories, and tests when changing method signatures or user data contracts. # AppController **Kind:** Controller **Source:** [`sample/20-cache/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/20-cache/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `findAll` # 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) ## Definition ```ts { inject: InjectionToken[]; useFactory: (...args: any[]) => MicroserviceOptions; } ``` # 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) `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. # 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) 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()` is a class decorator that marks a class as a NestJS controller. It establishes the controller's route prefix and metadata, allowing Nest to discover its HTTP route handlers or microservice message/event handlers during application startup. ## Signature ```ts function Controller(prefixOrOptions: string | string[] | ControllerOptions): ClassDecorator ``` ## Parameters | Name | Type | |---|---| | `prefixOrOptions` | `string | string[] | ControllerOptions` | **Returns:** `ClassDecorator` ## Diagram ```mermaid graph LR A[Nest Application] --> B[Controller decorator] B --> C[Controller class metadata] C --> D[HTTP route handlers] C --> E[Microservice message handlers] D --> F[Inbound HTTP requests] E --> G[Inbound messages and events] F --> H[Responses] G --> I[Message results or event processing] ``` ## Usage ```ts import { Controller, Get, Param, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return { id, name: 'Ada Lovelace' }; } @Post() create(@Body() payload: { name: string }) { return { id: crypto.randomUUID(), ...payload, }; } } // Routes: // GET /users/:id // POST /users ``` ## AI Coding Instructions - Apply `@Controller()` only to classes that group related HTTP routes or microservice handlers. - Use a route prefix such as `@Controller('users')` to keep handler paths concise and consistently scoped. - Define request-method decorators such as `@Get()`, `@Post()`, or message-pattern decorators on methods inside the controller class. - Keep controllers focused on transport concerns; delegate business logic and data access to injected providers/services. - Ensure the controller is registered in the appropriate Nest module's `controllers` array. # create **Kind:** API Endpoint **Source:** [`integration/typeorm/src/photo/photo.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/photo/photo.controller.ts#L14) ## Endpoint `POST /photo` ## Referenced By - `PhotoController` (MODULE_DECLARES) # EADDRINUSE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L30) ## Definition ```ts 'EADDRINUSE' ``` ## Value ```ts 'EADDRINUSE' ``` # PostsModule **Kind:** Module **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/posts/posts.module.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/posts/posts.module.ts#L13) ## Relationships - MODULE_PROVIDES β†’ `postsservice` - MODULE_PROVIDES β†’ `postsresolver` - MODULE_PROVIDES β†’ `usersresolver` # 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) `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] # UsersService **Kind:** Service **Source:** [`sample/19-auth-jwt/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/users/users.service.ts#L6) `UsersService` provides user lookup functionality for the JWT authentication flow. Its primary responsibility is to retrieve a user by username so authentication components can validate credentials and generate access tokens. ## Methods | Method | Signature | Returns | |---|---|---| | `findOne` | `findOne(username: string)` | `Promise` | ## Diagram ```mermaid sequenceDiagram participant Auth as AuthService participant Users as UsersService participant Store as User Data Store Auth->>Users: findOne(username) Users->>Store: Search for matching user Store-->>Users: User | undefined Users-->>Auth: User | undefined ``` ## Usage ```ts import { Injectable, UnauthorizedException } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class AuthService { constructor(private readonly usersService: UsersService) {} async validateUser(username: string, password: string) { const user = await this.usersService.findOne(username); if (!user || user.password !== password) { throw new UnauthorizedException('Invalid credentials'); } const { password: _, ...result } = user; return result; } } ``` ## AI Coding Instructions - Use `findOne()` for username-based user retrieval in authentication and authorization workflows. - Always handle the `undefined` result before accessing user properties or issuing JWT tokens. - Do not expose password fields in API responses; remove them after validating credentials. - Keep user lookup concerns in `UsersService`; place token generation and credential validation in `AuthService`. # AppController **Kind:** Controller **Source:** [`integration/nest-application/get-url/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - DEPENDS_ON β†’ `appservice` # 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) ## Definition ```ts { inject: InjectionToken[]; useFactory: (...args: any[]) => T; } ``` # 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) `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. # create **Kind:** API Endpoint **Source:** [`sample/05-sql-typeorm/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.controller.ts#L18) ## Endpoint `POST /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # ECONNREFUSED **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L28) ## Definition ```ts 'ECONNREFUSED' ``` ## Value ```ts 'ECONNREFUSED' ``` # 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) ## Signature ```ts function flattenRoutePaths(routes: Routes) ``` ## Parameters | Name | Type | |---|---| | `routes` | `Routes` | # PostsModule **Kind:** Module **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.module.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.module.ts#L11) ## Relationships - MODULE_PROVIDES β†’ `postsservice` - MODULE_PROVIDES β†’ `postsresolver` - MODULE_PROVIDES β†’ `usersresolver` # 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) 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. # ValidationPipe **Kind:** Service **Source:** [`sample/01-cats-app/src/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/pipes/validation.pipe.ts#L11) `ValidationPipe` is a NestJS pipe that validates incoming request data against DTO validation rules before it reaches a controller handler. It transforms payloads into the expected DTO shape and rejects invalid input with an HTTP validation error, keeping controllers focused on application logic. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: any, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ValidationPipe` stops the work with `BadRequestException` when `errors.length > 0` β€” β€œValidation failed”. - `ValidationPipe` stops the work with an early return when `!metatype || !this.toValidate(metatype)`. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant ValidationPipe participant DTO as DTO / class-validator participant Handler as Controller Handler Client->>Controller: HTTP request with payload Controller->>ValidationPipe: transform(value, metadata) ValidationPipe->>DTO: Create DTO instance and validate alt Payload is valid DTO-->>ValidationPipe: Valid transformed object ValidationPipe-->>Handler: Pass validated payload Handler-->>Client: Success response else Payload is invalid DTO-->>ValidationPipe: Validation errors ValidationPipe-->>Client: BadRequestException end ``` ## Usage ```ts import { Body, Controller, Post, UsePipes } from '@nestjs/common'; import { IsNotEmpty, IsString } from 'class-validator'; import { ValidationPipe } from '../common/pipes/validation.pipe'; class CreateCatDto { @IsString() @IsNotEmpty() name: string; } @Controller('cats') export class CatsController { @Post() @UsePipes(new ValidationPipe()) create(@Body() createCatDto: CreateCatDto) { return { message: `Created cat: ${createCatDto.name}`, }; } } ``` ## AI Coding Instructions - Keep DTO validation rules in DTO classes using `class-validator` decorators; do not duplicate validation logic in controllers. - Apply `ValidationPipe` at the route, controller, or global application level depending on the required validation scope. - Ensure request DTOs are classes rather than TypeScript interfaces, since runtime validation requires class metadata. - Preserve the pipe’s exception behavior so invalid payloads consistently return NestJS `BadRequestException` responses. - When extending `transform()`, account for primitive parameter types and skip class validation when no DTO metatype is available. # AppController **Kind:** Controller **Source:** [`integration/nest-application/listen/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/listen/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - DEPENDS_ON β†’ `appservice` # 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) `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. # ConsumerDeserializer **Kind:** Type **Source:** [`packages/microservices/interfaces/deserializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/deserializer.interface.ts#L18) ## Definition ```ts Deserializer< any, IncomingRequest | IncomingEvent > ``` # create **Kind:** API Endpoint **Source:** [`sample/06-mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.controller.ts#L11) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # ENOTFOUND **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L31) ## Definition ```ts 'ENOTFOUND' ``` ## Value ```ts 'ENOTFOUND' ``` # mapToExcludeRoute **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L15) ## Signature ```ts function mapToExcludeRoute(routes: (string | RouteInfo)[]): ExcludeRouteMetadata[] ``` ## Parameters | Name | Type | |---|---| | `routes` | `(string | RouteInfo)[]` | **Returns:** `ExcludeRouteMetadata[]` # PropertiesModule **Kind:** Module **Source:** [`integration/injector/src/properties/properties.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/properties/properties.module.ts#L5) ## Relationships - MODULE_PROVIDES β†’ `dependencyservice` - MODULE_PROVIDES β†’ `propertiesservice` # 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) 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. # ValidationPipe **Kind:** Service **Source:** [`sample/10-fastify/src/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/common/pipes/validation.pipe.ts#L11) `ValidationPipe` is a NestJS pipe that validates incoming request data before it reaches route handlers. It transforms payloads into DTO instances when applicable, runs class-validator rules, and rejects invalid input with an HTTP validation error. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: any, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ValidationPipe` stops the work with `BadRequestException` when `errors.length > 0` β€” β€œValidation failed”. - `ValidationPipe` stops the work with an early return when `!metatype || !this.toValidate(metatype)`. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant ValidationPipe participant DTO as DTO / class-validator participant Handler as Route Handler Client->>Controller: Send request payload Controller->>ValidationPipe: transform(value, metadata) ValidationPipe->>DTO: Convert payload to DTO instance ValidationPipe->>DTO: Validate DTO constraints alt Payload is valid DTO-->>ValidationPipe: No validation errors ValidationPipe-->>Controller: Validated DTO value Controller->>Handler: Invoke handler with DTO else Payload is invalid DTO-->>ValidationPipe: Validation errors ValidationPipe-->>Controller: Throw BadRequestException Controller-->>Client: 400 Bad Request end ``` ## Usage ```ts import { Body, Controller, Post, UsePipes } from '@nestjs/common'; import { IsEmail, IsString, MinLength } from 'class-validator'; import { ValidationPipe } from '../common/pipes/validation.pipe'; class CreateUserDto { @IsEmail() email: string; @IsString() @MinLength(8) password: string; } @Controller('users') @UsePipes(new ValidationPipe()) export class UsersController { @Post() create(@Body() payload: CreateUserDto) { // payload has passed DTO validation before this handler runs. return { email: payload.email }; } } ``` ## AI Coding Instructions - Apply `ValidationPipe` at the controller, route, or global application level so DTO validation runs before handlers execute. - Define request DTOs as classes and use `class-validator` decorators; interfaces cannot be validated at runtime. - Ensure controller parameters include an explicit DTO type, otherwise the pipe may not have runtime metadata to validate. - Preserve the pipe’s error behavior when extending it so invalid payloads consistently return appropriate `400 Bad Request` responses. - Keep transformation and validation concerns in the pipe; route handlers should assume their DTO inputs are already validated. # AppController **Kind:** Controller **Source:** [`integration/nest-application/use-body-parser/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/use-body-parser/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `index` # ConsumerRebalancingEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L977) ## Definition ```ts InstrumentationEvent<{ groupId: string; memberId: string; }> ``` # create **Kind:** API Endpoint **Source:** [`sample/07-sequelize/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.controller.ts#L10) ## Endpoint `POST /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) `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. # ENTRY_PROVIDER_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L47) ## Definition ```ts '__entryProvider__' ``` ## Value ```ts '__entryProvider__' ``` # 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) `MessageBody()` is a WebSockets parameter decorator that injects the incoming socket message payload into a gateway handler parameter. It can optionally select a specific property from the payload and apply NestJS pipes, such as `ValidationPipe`, 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] --> Payload[Incoming Message Payload] Payload --> Decorator["@MessageBody()"] Decorator --> Pipes[Optional 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({ transform: true })) createCatDto: CreateCatDto, ) { return { event: 'catCreated', data: createCatDto, }; } @SubscribeMessage('updateCatName') updateName(@MessageBody('name') name: string) { return { name }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only in WebSocket gateway message handlers, typically methods decorated with `@SubscribeMessage()`. - Pass a property name, such as `@MessageBody('id')`, when only one field from the incoming payload is needed. - Attach validation or transformation pipes directly to the decorator when validating message payloads. - Ensure DTOs and payload shapes match the client message contract; validation pipes only work correctly when the expected type is defined. - Prefer DTO-based payloads for complex messages instead of manually reading and validating untyped object properties. # PropertiesModule **Kind:** Module **Source:** [`integration/inspector/src/properties/properties.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/properties/properties.module.ts#L5) ## Relationships - MODULE_PROVIDES β†’ `dependencyservice` - MODULE_PROVIDES β†’ `propertiesservice` # 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) `TcpClientOptions` configures a NestJS microservices client that communicates over the TCP transport. It defines the remote host and port, optional message serialization behavior, TLS settings, socket implementation, and a maximum inbound message buffer size to protect against memory exhaustion. ## Properties | Property | Type | |---|---| | `transport` | `Transport.TCP` | | `options` | `{ host?: string; port?: number; serializer?: Serializer; deserializer?: Deserializer; tlsOptions?: ConnectionOptions; socketClass?: Type; /** * Maximum buffer size in characters (default: 128MB in characters, i.e., (512 * 1024 * 1024) / 4). * This limit prevents memory exhaustion when receiving large TCP messages. */ maxBufferSize?: number; }` | ## Diagram ```mermaid graph LR Client[TCP Client] --> Options[TcpClientOptions] Options --> Transport[transport: Transport.TCP] Options --> Connection[host + port] Options --> Serialization[serializer + deserializer] Options --> Security[tlsOptions] Options --> Socket[socketClass] Options --> Buffer[maxBufferSize] Connection --> Server[TCP Microservice Server] ``` ## Usage ```ts import { ClientProxyFactory, Transport } from '@nestjs/microservices'; const client = ClientProxyFactory.create({ transport: Transport.TCP, options: { host: 'localhost', port: 3001, // Optional protection for large incoming TCP payloads. maxBufferSize: 1024 * 1024, // Optional TLS configuration for secure connections. // tlsOptions: { // rejectUnauthorized: true, // ca: [process.env.TLS_CA_CERT], // }, }, }); const result = await client.send('users.findOne', { id: 'user-123' }); ``` ## AI Coding Instructions - Always set `transport: Transport.TCP`; this interface is specific to TCP microservice clients. - Configure `host` and `port` to match the target TCP microservice listener, using environment variables for deployment-specific values. - Set `maxBufferSize` deliberately when handling large payloads; avoid increasing it unnecessarily because larger limits increase memory-exhaustion risk. - Provide matching `serializer` and `deserializer` implementations when the client and server use a custom TCP message format. - Use `tlsOptions` for encrypted TCP connections and ensure certificate settings are compatible with the remote server. ## How it works `TcpClientOptions` is a public TypeScript configuration interface for a TCP microservice client. Its required discriminator is `transport: Transport.TCP`; its optional `options` object configures connection, packet transformation, TLS, socket wrapping, and buffering. 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-51](packages/microservices/interfaces/client-metadata.interface.ts#L34-L51) - `host?: string` and `port?: number` select the TCP endpoint. `ClientTCP` defaults omitted properties to `localhost` and `3000`, respectively. [client-metadata.interface.ts:39-42](packages/microservices/interfaces/client-metadata.interface.ts#L39-L42) [client-tcp.ts:30-34](packages/microservices/client/client-tcp.ts#L30-L34) [constants.ts:3-4](packages/microservices/constants.ts#L3-L4) - `serializer?: Serializer` is used to serialize outgoing request and event packets; if absent, the client selects `IdentitySerializer`. `Serializer` has a `serialize(value, options?)` method. [client-metadata.interface.ts:42-43](packages/microservices/interfaces/client-metadata.interface.ts#L42-L43) [client-proxy.ts:208-219](packages/microservices/client/client-proxy.ts#L208-L219) [client-tcp.ts:189-214](packages/microservices/client/client-tcp.ts#L189-L214) [serializer.interface.ts:10-12](packages/microservices/interfaces/serializer.interface.ts#L10-L12) - `deserializer?: Deserializer` handles incoming response data. If absent, the client selects `IncomingResponseDeserializer`; the deserializer may return its result synchronously or as a promise. [client-metadata.interface.ts:43-44](packages/microservices/interfaces/client-metadata.interface.ts#L43-L44) [client-proxy.ts:221-231](packages/microservices/client/client-proxy.ts#L221-L231) [client-tcp.ts:79-97](packages/microservices/client/client-tcp.ts#L79-L97) [deserializer.interface.ts:10-15](packages/microservices/interfaces/deserializer.interface.ts#L10-L15) - `tlsOptions?: ConnectionOptions` switches socket creation from `net.Socket` to `tls.connect`. The client spreads these options into `tls.connect` and overwrites its `host` and `port` with the configured endpoint; it does not separately call `socket.connect()` for TLS. [client-metadata.interface.ts:44-45](packages/microservices/interfaces/client-metadata.interface.ts#L44-L45) [client-tcp.ts:65-68](packages/microservices/client/client-tcp.ts#L65-L68) [client-tcp.ts:99-120](packages/microservices/client/client-tcp.ts#L99-L120) - `socketClass?: Type` selects the `TcpSocket` subclass used to wrap the underlying network or TLS socket. The default is `JsonSocket`. A custom class receives only the socket constructor argument. [client-metadata.interface.ts:45-46](packages/microservices/interfaces/client-metadata.interface.ts#L45-L46) [client-tcp.ts:32-36](packages/microservices/client/client-tcp.ts#L32-L36) [client-tcp.ts:113-120](packages/microservices/client/client-tcp.ts#L113-L120) - `maxBufferSize?: number` is passed only when the selected socket class is exactly `JsonSocket`; it is not passed to a custom socket class. `JsonSocket` defaults it to `(512 * 1024 * 1024) / 4` characters when omitted. When its accumulated input exceeds the limit, it clears that buffer and throws `MaxPacketLengthExceededException`; `TcpSocket` converts exceptions from incoming-data handling into an error event and ends the socket. [client-metadata.interface.ts:46-50](packages/microservices/interfaces/client-metadata.interface.ts#L46-L50) [client-tcp.ts:113-120](packages/microservices/client/client-tcp.ts#L113-L120) [json-socket.ts:7-24](packages/microservices/helpers/json-socket.ts#L7-L24) [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) Passing this object to `ClientProxyFactory.create()` causes the factory to construct `ClientTCP` for the TCP/default switch branch, with an empty options object when `options` is omitted. [client-proxy-factory.ts:41-48](packages/microservices/client/client-proxy-factory.ts#L41-L48) [client-proxy-factory.ts:68-74](packages/microservices/client/client-proxy-factory.ts#L68-L74) The interface itself contains no runtime validation. In the TCP client path, values are read directly from `options`; visible runtime failures include connection-close callbacks receiving `Error('Connection closed')`, and `unwrap()` throwing until `connect()` has initialized a socket. [client-tcp.ts:30-40](packages/microservices/client/client-tcp.ts#L30-L40) [client-tcp.ts:156-166](packages/microservices/client/client-tcp.ts#L156-L166) [client-tcp.ts:180-187](packages/microservices/client/client-tcp.ts#L180-L187) # ValidationPipe **Kind:** Service **Source:** [`sample/36-hmr-esm/src/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/pipes/validation.pipe.ts#L11) `ValidationPipe` is a NestJS pipe that validates incoming request data against the DTO type declared by a controller handler. It bypasses primitive values, validates class-based payloads, and throws a `BadRequestException` when validation errors are found. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: any, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ValidationPipe` stops the work with `BadRequestException` when `errors.length > 0` β€” β€œValidation failed”. - `ValidationPipe` stops the work with an early return when `!metatype || !this.toValidate(metatype)`. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant ValidationPipe participant DTO participant Handler Client->>Controller: Send request payload Controller->>ValidationPipe: transform(value, metadata) ValidationPipe->>ValidationPipe: Check request metatype alt DTO/class type requires validation ValidationPipe->>DTO: Create DTO instance from payload ValidationPipe->>DTO: Run class-validator rules alt Validation errors exist ValidationPipe-->>Client: 400 Bad Request else Payload is valid ValidationPipe->>Handler: Pass validated payload end else Primitive or unsupported type ValidationPipe->>Handler: Pass original value end ``` ## Usage ```ts import { Body, Controller, Post, UsePipes } from '@nestjs/common'; import { IsEmail, IsString } from 'class-validator'; import { ValidationPipe } from '../common/pipes/validation.pipe'; class CreateUserDto { @IsString() name: string; @IsEmail() email: string; } @Controller('users') export class UsersController { @Post() @UsePipes(new ValidationPipe()) create(@Body() createUserDto: CreateUserDto) { return { message: 'User payload is valid', user: createUserDto, }; } } ``` ## AI Coding Instructions - Apply `ValidationPipe` to controller routes or register it globally when DTO validation should be enforced consistently. - Define validation rules with `class-validator` decorators on DTO classes; plain interfaces cannot be validated at runtime. - Keep controller parameters typed with DTO classes so Nest can provide the runtime metatype required by `transform()`. - Do not expect primitive route parameters or values without a class metatype to be validated by this pipe. - Preserve `BadRequestException` behavior so invalid payloads continue to return standard NestJS HTTP 400 responses. # AppController **Kind:** Controller **Source:** [`sample/08-webpack/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/08-webpack/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - DEPENDS_ON β†’ `appservice` # AppService **Kind:** Service **Source:** [`sample/25-dynamic-modules/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/app.service.ts#L4) `AppService` is a NestJS provider responsible for supplying the application's basic greeting response. It exposes `getHello()`, which is typically consumed by a controller to produce a response for an HTTP endpoint. In the dynamic modules sample, it serves as a simple injectable service within the application module. ## Methods | Method | Signature | Returns | |---|---|---| | `getHello` | `getHello()` | `string` | ## Dependencies - `ConfigService` ## Diagram ```mermaid sequenceDiagram participant Client participant AppController participant AppService Client->>AppController: HTTP request AppController->>AppService: getHello() AppService-->>AppController: greeting string AppController-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { return this.appService.getHello(); } } ``` ## AI Coding Instructions - Inject `AppService` through NestJS constructor dependency injection; do not instantiate it manually with `new`. - Keep `getHello()` synchronous and return a `string` unless callers are updated to handle an asynchronous API. - Register the service in the relevant module's `providers` array before injecting it into controllers or other providers. - Keep HTTP-specific concerns, such as request parsing and status codes, in controllers rather than this service. ## Relationships - DEPENDS_ON β†’ `configservice` # ConsumerSubscribeTopics **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1038) ## Definition ```ts { topics: (string | RegExp)[]; fromBeginning?: boolean; } ``` # create **Kind:** API Endpoint **Source:** [`sample/14-mongoose-base/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/cats.controller.ts#L10) ## Endpoint `POST /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # ERROR_EVENT **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L15) ## Definition ```ts 'error' ``` ## Value ```ts 'error' ``` # 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) `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. # 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) `MessageBody()` is a WebSockets parameter decorator that injects the incoming socket message payload into a gateway handler parameter. It can optionally select a specific property from the payload and apply NestJS pipes, such as `ValidationPipe`, 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] --> Payload[Incoming Message Payload] Payload --> Decorator["@MessageBody()"] Decorator --> Pipes[Optional 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({ transform: true })) createCatDto: CreateCatDto, ) { return { event: 'catCreated', data: createCatDto, }; } @SubscribeMessage('updateCatName') updateName(@MessageBody('name') name: string) { return { name }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only in WebSocket gateway message handlers, typically methods decorated with `@SubscribeMessage()`. - Pass a property name, such as `@MessageBody('id')`, when only one field from the incoming payload is needed. - Attach validation or transformation pipes directly to the decorator when validating message payloads. - Ensure DTOs and payload shapes match the client message contract; validation pipes only work correctly when the expected type is defined. - Prefer DTO-based payloads for complex messages instead of manually reading and validating untyped object properties. # RecipesModule **Kind:** Module **Source:** [`integration/graphql-code-first/src/recipes/recipes.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/recipes/recipes.module.ts#L8) ## Relationships - MODULE_PROVIDES β†’ `recipesresolver` - MODULE_PROVIDES β†’ `recipesservice` - MODULE_PROVIDES β†’ `datescalar` # 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) 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. # AppController **Kind:** Controller **Source:** [`sample/25-dynamic-modules/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - DEPENDS_ON β†’ `appservice` # AppService **Kind:** Service **Source:** [`sample/35-use-esm-package-after-node22/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/sample/35-use-esm-package-after-node22/src/app.service.ts#L4) `AppService` is a NestJS backend service that exposes a JSON-string example through `getJsonStringExample()`. It acts as a small application-level abstraction for retrieving data produced or consumed by the ESM package integration in this sample. ## Methods | Method | Signature | Returns | |---|---|---| | `getJsonStringExample` | `getJsonStringExample()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Controller as NestJS Controller participant Service as AppService participant Package as ESM Package Controller->>Service: getJsonStringExample() Service->>Package: Retrieve or generate JSON example Package-->>Service: JSON-compatible value Service-->>Controller: unknown result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { AppService } from './app.service'; @Injectable() export class AppController { constructor(private readonly appService: AppService) {} getExample() { const result = this.appService.getJsonStringExample(); return { example: result, }; } } ``` ## AI Coding Instructions - Keep `AppService` injectable with NestJS's `@Injectable()` decorator so it can be provided and consumed through dependency injection. - Call `getJsonStringExample()` through an injected `AppService`; avoid manually instantiating the service in controllers or other providers. - Treat the return value as `unknown` until it is validated, narrowed, or serialized for the consuming endpoint. - Preserve ESM-compatible imports and package usage patterns when modifying integrations in this Node.js 22+ sample. # create **Kind:** API Endpoint **Source:** [`sample/30-event-emitter/src/orders/orders.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/orders.controller.ts#L9) ## Endpoint `POST /orders` ## Referenced By - `OrdersController` (MODULE_DECLARES) # 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) ## Definition ```ts MethodDecorator & ClassDecorator & { KEY: TKey; } ``` # EXCEPTION_FILTERS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L25) ## Definition ```ts '__exceptionFilters__' ``` ## Value ```ts '__exceptionFilters__' ``` # 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) `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. # 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) `MessageBody()` is a WebSockets parameter decorator that injects the incoming socket message payload into a gateway handler parameter. It can optionally select a specific property from the payload and apply NestJS pipes, such as `ValidationPipe`, 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] --> Payload[Incoming Message Payload] Payload --> Decorator["@MessageBody()"] Decorator --> Pipes[Optional 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({ transform: true })) createCatDto: CreateCatDto, ) { return { event: 'catCreated', data: createCatDto, }; } @SubscribeMessage('updateCatName') updateName(@MessageBody('name') name: string) { return { name }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only in WebSocket gateway message handlers, typically methods decorated with `@SubscribeMessage()`. - Pass a property name, such as `@MessageBody('id')`, when only one field from the incoming payload is needed. - Attach validation or transformation pipes directly to the decorator when validating message payloads. - Ensure DTOs and payload shapes match the client message contract; validation pipes only work correctly when the expected type is defined. - Prefer DTO-based payloads for complex messages instead of manually reading and validating untyped object properties. # ScopedModule **Kind:** Module **Source:** [`integration/injector/src/scoped/scoped.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/scoped.module.ts#L12) ## Relationships - MODULE_DECLARES β†’ `ScopedController` - MODULE_PROVIDES β†’ `ScopedService` - MODULE_PROVIDES β†’ `transientservice` - MODULE_PROVIDES β†’ `Transient2Service` - MODULE_PROVIDES β†’ `Transient3Service` # 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) # AppController **Kind:** Controller **Source:** [`sample/34-using-esm-packages/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/34-using-esm-packages/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - DEPENDS_ON β†’ `appservice` # AppService **Kind:** Service **Source:** [`integration/nest-application/get-url/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/src/app.service.ts#L3) `AppService` is a NestJS service that provides a simple application-level greeting through `sayHello()`. It is intended to be injected into controllers or other providers that need to return a basic response, such as a health check or root endpoint. ## Methods | Method | Signature | Returns | |---|---|---| | `sayHello` | `sayHello()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant AppService Client->>Controller: Request application URL Controller->>AppService: sayHello() AppService-->>Controller: string greeting Controller-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { return this.appService.sayHello(); } } ``` ## AI Coding Instructions - Inject `AppService` through NestJS constructor dependency injection rather than instantiating it directly. - Keep `sayHello()` synchronous and return a `string` unless callers require asynchronous behavior. - Register `AppService` in the relevant NestJS module's `providers` array before injecting it elsewhere. - Use controllers as the HTTP boundary; keep response-generation logic in this service where appropriate. # 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) 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. # delete **Kind:** API Endpoint **Source:** [`sample/06-mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.controller.ts#L31) ## Endpoint `DELETE /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) ## Definition ```ts '__fastify_route_config__' ``` ## Value ```ts '__fastify_route_config__' ``` # 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) `MessageBody()` is a WebSockets parameter decorator that injects the incoming socket message payload into a gateway handler parameter. It can optionally select a specific property from the payload and apply NestJS pipes, such as `ValidationPipe`, 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] --> Payload[Incoming Message Payload] Payload --> Decorator["@MessageBody()"] Decorator --> Pipes[Optional 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({ transform: true })) createCatDto: CreateCatDto, ) { return { event: 'catCreated', data: createCatDto, }; } @SubscribeMessage('updateCatName') updateName(@MessageBody('name') name: string) { return { name }; } } ``` ## AI Coding Instructions - Use `@MessageBody()` only in WebSocket gateway message handlers, typically methods decorated with `@SubscribeMessage()`. - Pass a property name, such as `@MessageBody('id')`, when only one field from the incoming payload is needed. - Attach validation or transformation pipes directly to the decorator when validating message payloads. - Ensure DTOs and payload shapes match the client message contract; validation pipes only work correctly when the expected type is defined. - Prefer DTO-based payloads for complex messages instead of manually reading and validating untyped object properties. # 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) `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. # SelfInjectionProviderCustomTokenModule **Kind:** Module **Source:** [`integration/injector/src/self-injection/self-injection-provider.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/self-injection/self-injection-provider.module.ts#L31) ## Relationships - MODULE_PROVIDES β†’ `ServiceInjectingItselfViaCustomToken` # 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) 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. # 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) `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. # AppController **Kind:** Controller **Source:** [`sample/35-use-esm-package-after-node22/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/35-use-esm-package-after-node22/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` - DEPENDS_ON β†’ `appservice` # AppService **Kind:** Service **Source:** [`integration/nest-application/listen/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/listen/src/app.service.ts#L3) `AppService` is a NestJS provider responsible for supplying the application's basic greeting response. It is typically injected into a controller, allowing HTTP endpoints or other services to delegate simple application-level behavior to a reusable service. ## Methods | Method | Signature | Returns | |---|---|---| | `sayHello` | `sayHello()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as AppController participant Service as AppService Client->>Controller: Request greeting endpoint Controller->>Service: sayHello() Service-->>Controller: string greeting Controller-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() sayHello(): string { return this.appService.sayHello(); } } ``` ## AI Coding Instructions - Keep `AppService` focused on reusable application logic; controllers should handle routing and delegate work to the service. - Inject `AppService` through NestJS constructor injection rather than creating it with `new`. - Preserve the `sayHello(): string` return contract when updating callers or tests. - Ensure `AppService` remains registered in the relevant NestJS module's `providers` array. # 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) ## Definition ```ts ( data: TData, context: ExecutionContext, ) => TOutput ``` # echo **Kind:** API Endpoint **Source:** [`integration/scopes/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.controller.ts#L17) ## Endpoint `GET /durable/echo` ## Referenced By - `DurableController` (MODULE_DECLARES) # 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) ## Definition ```ts '__fastify_route_schema__' ``` ## Value ```ts '__fastify_route_schema__' ``` # 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) 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()` is a route handler parameter decorator that reads route parameters from the incoming request's `req.params` object. Use it without arguments to inject all parameters, or provide a parameter name to inject a single value; optional pipes can transform or validate the extracted value before it reaches the handler. ## 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 A[Incoming HTTP Request] --> B[Router matches route] B --> C[req.params] C --> D[@Param decorator] D -->|No key| E[Inject all params] D -->|Parameter key| F[Extract named value] F --> G[Optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { // GET /users/42 @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id }; } // GET /users/42/posts/10 @Get(':userId/posts/:postId') findPost(@Param() params: { userId: string; postId: string }) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one route parameter; use `@Param()` only when the full `req.params` object is needed. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom pipes directly after the parameter name to validate or transform values. - Ensure the parameter name exactly matches the route token, such as `@Get(':id')` with `@Param('id')`. - Treat route parameter values as strings unless a pipe explicitly converts them to another type. - Keep parameter extraction in controller handlers; place business logic and data access in injected services. # SocketModule **Kind:** Class **Source:** [`packages/websockets/socket-module.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/socket-module.ts#L27) `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) # UsersModule **Kind:** Module **Source:** [`sample/31-graphql-federation-code-first/users-application/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/users-application/src/users/users.module.ts#L11) ## Relationships - MODULE_PROVIDES β†’ `usersresolver` - MODULE_PROVIDES β†’ `usersservice` # AppController **Kind:** Controller **Source:** [`sample/15-mvc/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/15-mvc/src/app.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `root` # AppService **Kind:** Service **Source:** [`sample/08-webpack/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/sample/08-webpack/src/app.service.ts#L3) `AppService` is a NestJS backend service responsible for providing the application's greeting message through its `getHello()` method. It is typically injected into a controller, such as `AppController`, which exposes the returned value through an HTTP endpoint. ## Methods | Method | Signature | Returns | |---|---|---| | `getHello` | `getHello()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as AppController participant Service as AppService Client->>Controller: GET / Controller->>Service: getHello() Service-->>Controller: greeting message Controller-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): unknown { return this.appService.getHello(); } } ``` ## AI Coding Instructions - Inject `AppService` through NestJS constructor dependency injection rather than creating it with `new`. - Keep `getHello()` focused on service-level business logic; HTTP request and response handling belongs in controllers. - Ensure `AppService` remains registered in the module's `providers` array before injecting it elsewhere. - Preserve the method's return contract when changing `getHello()`, and update consuming controllers or tests accordingly. # 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) 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. # echo **Kind:** API Endpoint **Source:** [`integration/inspector/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/durable/durable.controller.ts#L13) ## Endpoint `GET /durable/echo` ## Referenced By - `DurableController` (MODULE_DECLARES) # 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) ## Definition ```ts { file?: IFile; config: TConfig; } ``` # FILTER_CATCH_EXCEPTIONS **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L20) ## Definition ```ts '__filterCatchExceptions__' ``` ## Value ```ts '__filterCatchExceptions__' ``` # 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) 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()` is a route handler parameter decorator that reads route parameters from the incoming request's `req.params` object. Use it without arguments to inject all parameters, or provide a parameter name to inject a single value; optional pipes can transform or validate the extracted value before it reaches the handler. ## 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 A[Incoming HTTP Request] --> B[Router matches route] B --> C[req.params] C --> D[@Param decorator] D -->|No key| E[Inject all params] D -->|Parameter key| F[Extract named value] F --> G[Optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { // GET /users/42 @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id }; } // GET /users/42/posts/10 @Get(':userId/posts/:postId') findPost(@Param() params: { userId: string; postId: string }) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one route parameter; use `@Param()` only when the full `req.params` object is needed. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom pipes directly after the parameter name to validate or transform values. - Ensure the parameter name exactly matches the route token, such as `@Get(':id')` with `@Param('id')`. - Treat route parameter values as strings unless a pipe explicitly converts them to another type. - Keep parameter extraction in controller handlers; place business logic and data access in injected services. # SseStream **Kind:** Class **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L75) 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` converts structured message objects into W3C Server-Sent Events (SSE) wire format. It can optimize an incoming HTTP request for streaming and, when piped to an HTTP response, configures the response headers required for an SSE connection. **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 -->|SSE-formatted event stream| D[HTTP Response] D --> E[EventSource client] ``` ## AI Coding Instructions - Send SSE payloads as message objects; use `data` for strings or JSON-serializable objects, and `type`, `id`, `retry`, or `comment` for SSE metadata. - Construct the stream with the incoming HTTP request when available so the socket can be optimized for long-lived streaming. - Pipe `SseStream` directly to the HTTP response instead of manually setting SSE headers or serializing event lines. - Do not write ordinary response bodies after piping the SSE stream; all client output should flow through `SseStream`. - Keep streams open for ongoing events and call `end()` only when the SSE connection should close. # UsersModule **Kind:** Module **Source:** [`integration/repl/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `userscontroller` - MODULE_PROVIDES β†’ `usersservice` # AppController **Kind:** Controller **Source:** [`sample/17-mvc-fastify/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/17-mvc-fastify/src/app.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `root` # AppService **Kind:** Service **Source:** [`sample/18-context/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/sample/18-context/src/app.service.ts#L3) `AppService` is a NestJS provider responsible for supplying the application's greeting message. It is typically injected into a controller, such as `AppController`, to keep response logic separate from HTTP routing concerns. ## Methods | Method | Signature | Returns | |---|---|---| | `getHello` | `getHello()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as AppController participant Service as AppService Client->>Controller: GET / Controller->>Service: getHello() Service-->>Controller: "Hello World!" Controller-->>Client: Greeting response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { return this.appService.getHello(); } } ``` ## AI Coding Instructions - Keep `AppService` focused on application or business logic; leave HTTP request handling to controllers. - Inject the service through NestJS constructor injection rather than instantiating it with `new`. - Preserve the `getHello(): string` return contract when modifying callers or implementations. - Ensure `AppService` remains registered in the relevant NestJS module's `providers` array. # 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) `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. # execute **Kind:** API Endpoint **Source:** [`sample/03-microservices/src/math/math.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/math/math.controller.ts#L10) ## Endpoint `GET /` ## Referenced By - `MathController` (MODULE_DECLARES) # FORBIDDEN_MESSAGE **Kind:** Constant **Source:** [`packages/core/guards/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/guards/constants.ts#L1) ## Definition ```ts 'Forbidden resource' ``` ## Value ```ts 'Forbidden resource' ``` # GroupMemberAssignment **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L236) ## Definition ```ts { memberId: string; memberAssignment: Buffer; } ``` # 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) 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()` is a route handler parameter decorator that reads route parameters from the incoming request's `req.params` object. Use it without arguments to inject all parameters, or provide a parameter name to inject a single value; optional pipes can transform or validate the extracted value before it reaches the handler. ## 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 A[Incoming HTTP Request] --> B[Router matches route] B --> C[req.params] C --> D[@Param decorator] D -->|No key| E[Inject all params] D -->|Parameter key| F[Extract named value] F --> G[Optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { // GET /users/42 @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id }; } // GET /users/42/posts/10 @Get(':userId/posts/:postId') findPost(@Param() params: { userId: string; postId: string }) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one route parameter; use `@Param()` only when the full `req.params` object is needed. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom pipes directly after the parameter name to validate or transform values. - Ensure the parameter name exactly matches the route token, such as `@Get(':id')` with `@Param('id')`. - Treat route parameter values as strings unless a pipe explicitly converts them to another type. - Keep parameter extraction in controller handlers; place business logic and data access in injected services. # SettlementSignal **Kind:** Class **Source:** [`packages/core/injector/settlement-signal.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/settlement-signal.ts#L6) 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. # UsersModule **Kind:** Module **Source:** [`sample/32-graphql-federation-schema-first/users-application/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/users-application/src/users/users.module.ts#L10) ## Relationships - MODULE_PROVIDES β†’ `usersresolver` - MODULE_PROVIDES β†’ `usersservice` # AModule **Kind:** Module **Source:** [`integration/testing-module-override/circular-dependency/a.module.ts`](https://github.com/nestjs/nest/blob/master/integration/testing-module-override/circular-dependency/a.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `AProvider` - MODULE_EXPORTS β†’ `AProvider` # AppController **Kind:** Controller **Source:** [`integration/cors/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/cors/src/app.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getGlobals` # AppService **Kind:** Service **Source:** [`sample/29-file-upload/src/app.service.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.service.ts#L3) `AppService` is a NestJS provider responsible for supplying the application's basic response data through `getHello()`. It is typically injected into a controller, which exposes the returned value through an HTTP endpoint. ## Methods | Method | Signature | Returns | |---|---|---| | `getHello` | `getHello()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as AppController participant Service as AppService Client->>Controller: HTTP request Controller->>Service: getHello() Service-->>Controller: response value Controller-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): unknown { return this.appService.getHello(); } } ``` ## AI Coding Instructions - Keep `AppService` focused on application-level business logic; controllers should delegate work rather than contain service logic. - Inject the service through the controller constructor instead of creating it manually with `new AppService()`. - Preserve the return type contract of `getHello()` when updating consumers; prefer a more specific type than `unknown` when the response shape is known. - Ensure `AppService` remains registered in the corresponding NestJS module's `providers` array. # 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) `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. # 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) `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. # findAll **Kind:** API Endpoint **Source:** [`sample/20-cache/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/20-cache/src/app.controller.ts#L7) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # GATEWAY_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L6) ## Definition ```ts 'websockets:is_gateway' ``` ## Value ```ts 'websockets:is_gateway' ``` # GroupOverview **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L899) ## Definition ```ts { groupId: string; protocolType: string; } ``` # 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) 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()` is a route handler parameter decorator that reads route parameters from the incoming request's `req.params` object. Use it without arguments to inject all parameters, or provide a parameter name to inject a single value; optional pipes can transform or validate the extracted value before it reaches the handler. ## 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 A[Incoming HTTP Request] --> B[Router matches route] B --> C[req.params] C --> D[@Param decorator] D -->|No key| E[Inject all params] D -->|Parameter key| F[Extract named value] F --> G[Optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { // GET /users/42 @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id }; } // GET /users/42/posts/10 @Get(':userId/posts/:postId') findPost(@Param() params: { userId: string; postId: string }) { return params; } } ``` ## AI Coding Instructions - Use `@Param('name')` when a handler needs one route parameter; use `@Param()` only when the full `req.params` object is needed. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom pipes directly after the parameter name to validate or transform values. - Ensure the parameter name exactly matches the route token, such as `@Get(':id')` with `@Param('id')`. - Treat route parameter values as strings unless a pipe explicitly converts them to another type. - Keep parameter extraction in controller handlers; place business logic and data access in injected services. # AppController **Kind:** Controller **Source:** [`integration/nest-application/app-locals/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/app-locals/src/app.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getGlobals` # ApplicationModule **Kind:** Module **Source:** [`integration/mongoose/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # AuthGuard **Kind:** Service **Source:** [`integration/graphql-code-first/src/common/guards/auth.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/common/guards/auth.guard.ts#L9) `AuthGuard` is a NestJS guard that controls access to protected GraphQL operations before their resolvers execute. Its `canActivate()` method evaluates the incoming request context and returns a `Promise` indicating whether the current user is authorized to continue. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `Promise` | ## Where it refuses work - `AuthGuard` stops the work with `UnauthorizedException` when `gqlContext`. ## Diagram ```mermaid sequenceDiagram participant Client participant GraphQL as GraphQL Resolver participant Guard as AuthGuard participant Context as GraphQL Request Context Client->>GraphQL: Execute protected query or mutation GraphQL->>Guard: canActivate(context) Guard->>Context: Read request/authentication data Context-->>Guard: User or credentials Guard-->>GraphQL: true / false alt Authorized GraphQL-->>Client: Resolver response else Unauthorized GraphQL-->>Client: Authorization error end ``` ## Usage ```ts import { UseGuards } from '@nestjs/common'; import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { AuthGuard } from '../common/guards/auth.guard'; @Resolver() export class ProfileResolver { @Mutation(() => Boolean) @UseGuards(AuthGuard) async updateProfile(@Args('displayName') displayName: string): Promise { // This resolver runs only when AuthGuard.canActivate() returns true. return true; } } ``` ## AI Coding Instructions - Apply `@UseGuards(AuthGuard)` to GraphQL resolvers or individual operations that require an authenticated user. - Keep authentication extraction logic compatible with the GraphQL execution context; HTTP request assumptions may not work directly in code-first resolvers. - Ensure the GraphQL context is configured to expose request and authenticated-user data expected by `canActivate()`. - Return `true` only for valid authenticated requests; reject or throw an appropriate authorization exception for invalid credentials. - Keep authorization rules separate from authentication when possible, using additional guards or decorators for role- and permission-based checks. # 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) # findAll **Kind:** API Endpoint **Source:** [`integration/inspector/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/cats.controller.ts#L18) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # GATEWAY_OPTIONS **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L9) ## Definition ```ts 'websockets:gateway_options' ``` ## Value ```ts 'websockets:gateway_options' ``` # MetadataScanner **Kind:** Class **Source:** [`packages/core/metadata-scanner.ts`](https://github.com/nestjs/nest/blob/master/packages/core/metadata-scanner.ts#L8) `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. # ModuleDebugEntry **Kind:** Type **Source:** [`packages/core/repl/repl-context.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-context.ts#L22) ## Definition ```ts { controllers: Record; providers: Record; } ``` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) `@Payload()` is a parameter decorator for NestJS microservice message handlers. It injects the incoming message payload into the decorated method parameter and can apply pipes, such as `ValidationPipe`, to validate or transform the payload before the handler runs. ## 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 A[Microservice Client] -->|Send message pattern + payload| B[Message Handler] B --> C[@Payload decorator] C --> D[Pipes / ValidationPipe] D --> E[Handler parameter] E --> F[Business logic] ``` ## 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({ transform: true })) createCatDto: CreateCatDto, ) { return { id: 'cat-1', ...createCatDto, }; } } ``` ## AI Coding Instructions - Use `@Payload()` only on parameters of microservice message-pattern handlers, such as methods decorated with `@MessagePattern()` or `@EventPattern()`. - Pass validation or transformation pipes directly to `@Payload(...)` when payload-specific processing is needed. - Ensure DTO classes define the expected message body shape; use class-validator decorators when using `ValidationPipe`. - Do not use `@Payload()` for HTTP controller request bodies; use `@Body()` in HTTP routes instead. - Keep message patterns and payload DTOs aligned between microservice clients and consumers. # AppController **Kind:** Controller **Source:** [`sample/24-serve-static/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/24-serve-static/src/app.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `getHello` # ApplicationModule **Kind:** Module **Source:** [`integration/injector/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `ExportsModule` # BarService **Kind:** Service **Source:** [`integration/auto-mock/src/bar.service.ts`](https://github.com/nestjs/nest/blob/master/integration/auto-mock/src/bar.service.ts#L4) `BarService` is a NestJS injectable service located in the auto-mock integration fixture. It exposes a `bar()` method that can be consumed by other providers or controllers and is typically used to validate service resolution and mocking behavior in tests. ## Methods | Method | Signature | Returns | |---|---|---| | `bar` | `bar()` | `unknown` | ## Dependencies - `FooService` ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Service participant BarService participant Mock as Auto-mock Test Setup Consumer->>BarService: bar() BarService-->>Consumer: unknown result Mock-->>BarService: Replace or configure dependency in tests ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { BarService } from './bar.service'; @Injectable() export class ExampleService { constructor(private readonly barService: BarService) {} execute() { return this.barService.bar(); } } // Test setup example const barServiceMock = { bar: jest.fn().mockReturnValue('mocked result'), }; ``` ## AI Coding Instructions - Inject `BarService` through NestJS constructor injection rather than creating instances manually. - Treat the return value of `bar()` as `unknown`; validate or narrow its type before using it in application logic. - When testing consumers, mock `bar()` with `jest.fn()` and provide deterministic return values. - Keep this service registered in the appropriate NestJS module provider list so it can be resolved by dependent providers. ## Relationships - DEPENDS_ON β†’ `FooService` # DescribeConfigResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L365) `DescribeConfigResponse` represents the result of a Kafka configuration describe request. It contains configuration entries for one or more Kafka resources, along with resource-level errors and broker throttling information. ## Properties | Property | Type | |---|---| | `resources` | `{ configEntries: ConfigEntries[]; errorCode: number; errorMessage: string; resourceName: string; resourceType: ConfigResourceTypes; }[]` | | `throttleTime` | `number` | ## Diagram ```mermaid graph LR Response[DescribeConfigResponse] Response --> Resources[resources[]] Response --> Throttle[throttleTime] Resources --> ResourceName[resourceName] Resources --> ResourceType[resourceType: ConfigResourceTypes] Resources --> ConfigEntries[configEntries: ConfigEntries[]] Resources --> ErrorCode[errorCode] Resources --> ErrorMessage[errorMessage] ``` ## Usage ```ts import type { DescribeConfigResponse } from './kafka.interface'; function logTopicConfig(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); } } } ``` ## AI Coding Instructions - Treat each item in `resources` independently, since a single describe request can return results for multiple Kafka resources. - Check `errorCode` before consuming `configEntries`; a non-zero code indicates the resource configuration could not be retrieved. - Preserve `throttleTime` when exposing Kafka client results so callers can monitor broker-side throttling. - Use `resourceType` with `resourceName` to identify resources accurately, especially when handling topics, brokers, or other configurable Kafka entities. ## How it works `DescribeConfigResponse` is an exported TypeScript interface that describes the result type of `Admin.describeConfigs(...)`. That admin method returns `Promise`. [packages/microservices/external/kafka.interface.ts:548-551] Its required fields are: - `resources`: an array of per-resource configuration results. Each result contains: - `configEntries`: an array of `ConfigEntries`; - `errorCode`: a number; - `errorMessage`: a string; - `resourceName`: a string; - `resourceType`: a `ConfigResourceTypes` enum value. [packages/microservices/external/kafka.interface.ts:365-372] - `throttleTime`: a number. [packages/microservices/external/kafka.interface.ts:373-374] Each `configEntries` item contains the configuration name and value, default-status flag, source enum value, sensitivity flag, read-only flag, and an array of configuration synonyms. [packages/microservices/external/kafka.interface.ts:349-357] A synonym records its name, value, and source. [packages/microservices/external/kafka.interface.ts:359-363] `ConfigResourceTypes` allows `UNKNOWN`, `TOPIC`, `BROKER`, and `BROKER_LOGGER` values. [packages/microservices/external/kafka.interface.ts:295-300] `ConfigSource` identifies sources including topic, dynamic broker, static broker, default, and dynamic broker-logger configuration. [packages/microservices/external/kafka.interface.ts:302-310] This is a type-only interface: it declares no runtime validation, thrown errors, or side effects. The request accepted by `Admin.describeConfigs` requires a `resources` array of `ResourceConfigQuery` items and an `includeSynonyms` boolean. [packages/microservices/external/kafka.interface.ts:343-347][packages/microservices/external/kafka.interface.ts:548-551] # findAll **Kind:** API Endpoint **Source:** [`integration/inspector/src/database/database.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.controller.ts#L23) ## Endpoint `GET /database` ## Referenced By - `DatabaseController` (MODULE_DECLARES) # GATEWAY_SERVER_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L5) ## Definition ```ts 'websockets:is_socket' ``` ## Value ```ts 'websockets:is_socket' ``` # MiddlewareBuilder **Kind:** Class **Source:** [`packages/core/middleware/builder.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/builder.ts#L17) `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. # 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) ## Definition ```ts Omit< Parameters[1], 'parseAs' > ``` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) `@Payload()` is a parameter decorator for NestJS microservice message handlers. It injects the incoming message payload into the decorated method parameter and can apply pipes, such as `ValidationPipe`, to validate or transform the payload before the handler runs. ## 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 A[Microservice Client] -->|Send message pattern + payload| B[Message Handler] B --> C[@Payload decorator] C --> D[Pipes / ValidationPipe] D --> E[Handler parameter] E --> F[Business logic] ``` ## 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({ transform: true })) createCatDto: CreateCatDto, ) { return { id: 'cat-1', ...createCatDto, }; } } ``` ## AI Coding Instructions - Use `@Payload()` only on parameters of microservice message-pattern handlers, such as methods decorated with `@MessagePattern()` or `@EventPattern()`. - Pass validation or transformation pipes directly to `@Payload(...)` when payload-specific processing is needed. - Ensure DTO classes define the expected message body shape; use class-validator decorators when using `ValidationPipe`. - Do not use `@Payload()` for HTTP controller request bodies; use `@Body()` in HTTP routes instead. - Keep message patterns and payload DTOs aligned between microservice clients and consumers. # AppController **Kind:** Controller **Source:** [`tools/benchmarks/src/frameworks/nest/app.controller.ts`](https://github.com/nestjs/nest/blob/master/tools/benchmarks/src/frameworks/nest/app.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppController client->>+p1: AppController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `root` # ApplicationModule **Kind:** Module **Source:** [`integration/scopes/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/app.module.ts#L4) # CatsGuard **Kind:** Service **Source:** [`integration/graphql-schema-first/src/cats/cats.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.guard.ts#L4) `CatsGuard` is a NestJS guard used by the GraphQL schema-first Cats module to control whether an incoming request may access a protected resolver or route. Its `canActivate()` method returns a boolean decision that NestJS uses to continue or deny execution of the handler. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant CatsGuard participant CatsResolver Client->>NestJS: GraphQL request NestJS->>CatsGuard: canActivate(context) CatsGuard-->>NestJS: true / false alt Access allowed NestJS->>CatsResolver: Execute resolver CatsResolver-->>Client: GraphQL response else Access denied NestJS-->>Client: Forbidden response end ``` ## Usage ```ts import { UseGuards } from '@nestjs/common'; import { Resolver, Query } from '@nestjs/graphql'; import { CatsGuard } from './cats.guard'; @Resolver('Cat') @UseGuards(CatsGuard) export class CatsResolver { @Query('cats') findAll() { return [ { id: 1, name: 'Milo' }, { id: 2, name: 'Luna' }, ]; } } ``` ## AI Coding Instructions - Keep `canActivate()` synchronous and return a boolean unless authentication or authorization requires asynchronous validation. - Apply `CatsGuard` with `@UseGuards(CatsGuard)` at the resolver, query, mutation, or controller level as appropriate. - For GraphQL-specific request data, use NestJS GraphQL execution context utilities rather than assuming an HTTP request context. - Return `false` or throw an appropriate NestJS authorization exception when access should be denied. - Avoid placing Cats business logic in the guard; keep it focused on request authorization and delegate domain operations to services. # EachBatchPayload **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1002) `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) # findAll **Kind:** API Endpoint **Source:** [`integration/inspector/src/dogs/dogs.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.controller.ts#L23) ## Endpoint `GET /dogs` ## Referenced By - `DogsController` (MODULE_DECLARES) # GatewayMetadataExplorer **Kind:** Class **Source:** [`packages/websockets/gateway-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/gateway-metadata-explorer.ts#L22) `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`. # 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) 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. # 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) ## Definition ```ts { id: string; label: string; } & (ClassNode | ModuleNode) ``` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) `@Payload()` is a parameter decorator for NestJS microservice message handlers. It injects the incoming message payload into the decorated method parameter and can apply pipes, such as `ValidationPipe`, to validate or transform the payload before the handler runs. ## 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 A[Microservice Client] -->|Send message pattern + payload| B[Message Handler] B --> C[@Payload decorator] C --> D[Pipes / ValidationPipe] D --> E[Handler parameter] E --> F[Business logic] ``` ## 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({ transform: true })) createCatDto: CreateCatDto, ) { return { id: 'cat-1', ...createCatDto, }; } } ``` ## AI Coding Instructions - Use `@Payload()` only on parameters of microservice message-pattern handlers, such as methods decorated with `@MessagePattern()` or `@EventPattern()`. - Pass validation or transformation pipes directly to `@Payload(...)` when payload-specific processing is needed. - Ensure DTO classes define the expected message body shape; use class-validator decorators when using `ValidationPipe`. - Do not use `@Payload()` for HTTP controller request bodies; use `@Body()` in HTTP routes instead. - Keep message patterns and payload DTOs aligned between microservice clients and consumers. # ApplicationModule **Kind:** Module **Source:** [`integration/websockets/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/app.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `ApplicationGateway` # AppV1Controller **Kind:** Controller **Source:** [`integration/inspector/src/app-v1.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app-v1.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppV1Controller client->>+p1: AppV1Controller p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `helloWorldV1` - MODULE_DECLARES β†’ `paramV1` # CatsGuard **Kind:** Service **Source:** [`sample/12-graphql-schema-first/src/cats/cats.guard.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.guard.ts#L4) `CatsGuard` is a NestJS guard responsible for deciding whether a request can access protected Cats-related GraphQL operations. It implements Nest's `CanActivate` pattern and returns a boolean value to allow or deny execution before the resolver runs. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean` | ## Diagram ```mermaid sequenceDiagram participant Client participant GraphQL as GraphQL Resolver participant Guard as CatsGuard participant Resolver as Cats Resolver Client->>GraphQL: Execute Cats query or mutation GraphQL->>Guard: canActivate() Guard-->>GraphQL: true / false alt Access allowed GraphQL->>Resolver: Execute resolver method Resolver-->>Client: Return result else Access denied GraphQL-->>Client: Return authorization error end ``` ## Usage ```ts import { UseGuards } from '@nestjs/common'; import { Resolver, Query } from '@nestjs/graphql'; import { CatsGuard } from './cats.guard'; @Resolver() @UseGuards(CatsGuard) export class CatsResolver { @Query(() => String) cats(): string { return 'Cats data'; } } ``` ## AI Coding Instructions - Keep `canActivate()` focused on authorization decisions and return `true` only when access should be granted. - Apply `@UseGuards(CatsGuard)` to individual resolver methods or the resolver class, depending on the desired protection scope. - For GraphQL-specific request data, use `GqlExecutionContext.create(context)` when extending the guard with authentication or user checks. - Avoid placing business logic or database-heavy operations directly in the guard; delegate those concerns to dedicated services. # 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) 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()`. # findAll **Kind:** API Endpoint **Source:** [`integration/inspector/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.controller.ts#L23) ## Endpoint `GET /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # GLOBAL_MODULE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L8) ## Definition ```ts '__module:global__' ``` ## Value ```ts '__module:global__' ``` # 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) `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. # 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) ## Definition ```ts { token: InjectionToken; optional: boolean; } ``` # Payload **Kind:** Function **Source:** [`packages/microservices/decorators/payload.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/payload.decorator.ts#L54) `@Payload()` is a parameter decorator for NestJS microservice message handlers. It injects the incoming message payload into the decorated method parameter and can apply pipes, such as `ValidationPipe`, to validate or transform the payload before the handler runs. ## 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 A[Microservice Client] -->|Send message pattern + payload| B[Message Handler] B --> C[@Payload decorator] C --> D[Pipes / ValidationPipe] D --> E[Handler parameter] E --> F[Business logic] ``` ## 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({ transform: true })) createCatDto: CreateCatDto, ) { return { id: 'cat-1', ...createCatDto, }; } } ``` ## AI Coding Instructions - Use `@Payload()` only on parameters of microservice message-pattern handlers, such as methods decorated with `@MessagePattern()` or `@EventPattern()`. - Pass validation or transformation pipes directly to `@Payload(...)` when payload-specific processing is needed. - Ensure DTO classes define the expected message body shape; use class-validator decorators when using `ValidationPipe`. - Do not use `@Payload()` for HTTP controller request bodies; use `@Body()` in HTTP routes instead. - Keep message patterns and payload DTOs aligned between microservice clients and consumers. # AppModule **Kind:** Module **Source:** [`sample/06-mongoose/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # AppV1Controller **Kind:** Controller **Source:** [`integration/versioning/src/app-v1.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app-v1.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppV1Controller client->>+p1: AppV1Controller p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `helloWorldV1` - MODULE_DECLARES β†’ `paramV1` # CatsService **Kind:** Service **Source:** [`integration/mongoose/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/cats.service.ts#L7) `CatsService` provides the application’s persistence layer for cat records in the Mongoose integration. It encapsulates creating new `Cat` documents and retrieving all stored cats, allowing controllers or other services to interact with the database through a focused NestJS service API. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createCatDto: CreateCatDto)` | `Promise` | | `findAll` | `findAll()` | `Promise` | ## Dependencies - `Model` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as CatsController participant Service as CatsService participant Model as Mongoose Cat Model participant DB as MongoDB Client->>Controller: POST /cats (create cat data) Controller->>Service: create(createCatDto) Service->>Model: create(cat data) Model->>DB: Insert Cat document DB-->>Model: Persisted document Model-->>Service: Cat Service-->>Controller: Cat Controller-->>Client: Created cat response Client->>Controller: GET /cats Controller->>Service: findAll() Service->>Model: find() Model->>DB: Query Cat collection DB-->>Model: Cat documents Model-->>Service: Cat[] Service-->>Controller: Cat[] Controller-->>Client: Cat list response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsService } from './cats.service'; @Injectable() export class CatsController { constructor(private readonly catsService: CatsService) {} async createCat() { const cat = await this.catsService.create(); return cat; } async getCats() { const cats = await this.catsService.findAll(); return cats; } } ``` ## AI Coding Instructions - Keep database access inside `CatsService`; controllers should delegate persistence operations rather than querying Mongoose models directly. - Ensure `CatsService` remains registered in the relevant NestJS module and receives its Mongoose `Cat` model through dependency injection. - Preserve the asynchronous `Promise` and `Promise` return contracts when adding logic around `create()` or `findAll()`. - Add validation and DTO handling at the controller boundary before passing user-provided data to service persistence methods. - When extending query behavior, use Mongoose query methods consistently and account for empty result sets from `findAll()`. ## Relationships - DEPENDS_ON β†’ `model` # 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) 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. # findAll **Kind:** API Endpoint **Source:** [`integration/mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/cats.controller.ts#L15) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # GRPC_DEFAULT_PROTO_LOADER **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L53) ## Definition ```ts '@grpc/proto-loader' ``` ## Value ```ts '@grpc/proto-loader' ``` # InterceptorsConsumer **Kind:** Class **Source:** [`packages/core/interceptors/interceptors-consumer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/interceptors/interceptors-consumer.ts#L13) `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. # ProducerSerializer **Kind:** Type **Source:** [`packages/microservices/interfaces/serializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/serializer.interface.ts#L14) ## Definition ```ts Serializer< OutgoingEvent | OutgoingRequest, any > ``` # 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) 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 extracts values from the incoming request's `req.query` object. It can bind the entire query object or a specific query parameter to a controller method argument, optionally applying pipes for parsing or validation. ## 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 A[HTTP Request] --> B[req.query] B --> C[@Query decorator] C --> D{Property specified?} D -->|No| E[Bind entire query object] D -->|Yes| F[Extract named query value] F --> G[Apply optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Query, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll( @Query('search') search?: string, @Query('page', ParseIntPipe) page = 1, @Query() filters?: Record, ) { return { search, page, filters, }; } } ``` For a request such as `GET /users?search=alex&page=2&role=admin`, `search` receives `"alex"`, `page` receives `2`, and `filters` contains the full query object. ## AI Coding Instructions - Use `@Query()` without a property name when the handler needs access to all query parameters; use `@Query('key')` for a single value. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom transformation pipes when query values require parsing or validation. - Remember that query parameters are typically strings unless transformed by a pipe. - Keep query extraction in controller route handlers; pass normalized values to services rather than exposing request-specific objects downstream. - Ensure property names passed to `@Query('property')` match the expected HTTP query parameter names. # AppModule **Kind:** Module **Source:** [`sample/08-webpack/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/08-webpack/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # AppV2Controller **Kind:** Controller **Source:** [`integration/versioning/src/app-v2.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app-v2.controller.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ AppV2Controller client->>+p1: AppV2Controller p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `helloWorldV2` - MODULE_DECLARES β†’ `paramV1` # CatsService **Kind:** Service **Source:** [`sample/11-swagger/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/cats.service.ts#L5) `CatsService` encapsulates the core cat-related business logic for the Swagger sample application. It provides operations to create a cat record and retrieve an individual cat, acting as the service layer between controllers and the underlying data source. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: CreateCatDto)` | `Cat` | | `findOne` | `findOne(id: number)` | `Cat` | ## Diagram ```mermaid sequenceDiagram participant Client participant CatsController participant CatsService participant DataStore Client->>CatsController: POST /cats CatsController->>CatsService: create() CatsService->>DataStore: Persist cat data DataStore-->>CatsService: Cat CatsService-->>CatsController: Cat CatsController-->>Client: Created cat response Client->>CatsController: GET /cats/:id CatsController->>CatsService: findOne() CatsService->>DataStore: Look up cat DataStore-->>CatsService: Cat CatsService-->>CatsController: Cat CatsController-->>Client: Cat response ``` ## Usage ```ts import { CatsService } from './cats.service'; const catsService = new CatsService(); // Create a cat through the service layer. const createdCat = catsService.create(); // Retrieve a cat by delegating to the service. const cat = catsService.findOne(); console.log({ createdCat, cat }); ``` ## AI Coding Instructions - Keep cat-related business logic in `CatsService`; controllers should remain focused on request handling and API documentation. - Ensure `create()` and `findOne()` continue to return values compatible with the `Cat` model/interface. - When adding persistence, inject a repository or database provider rather than accessing storage directly from controllers. - Add validation and explicit not-found handling when `findOne()` begins accepting an identifier. - Update Swagger DTOs and controller decorators alongside any changes to service method inputs or return types. # 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) 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. # findAll **Kind:** API Endpoint **Source:** [`integration/repl/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.controller.ts#L23) ## Endpoint `GET /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # GRPC_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L9) ## Definition ```ts 'localhost:5000' ``` ## Value ```ts 'localhost:5000' ``` # 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) `LegacyRouteConverter` converts legacy route definitions into the current router-compatible string format. It centralizes conversion logic and exposes diagnostic helpers for reporting conversion errors and warnings during route migration. ## 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[Converted route string] B --> E[printWarning()] B --> F[printError()] ``` ## Usage ```ts import { LegacyRouteConverter } from '@project/core/router/legacy-route-converter'; // Provide the legacy route data expected by the converter. const converter = new LegacyRouteConverter(/* legacy route input */); const convertedRoute = converter.tryConvert(); if (convertedRoute) { console.log(`Converted route: ${convertedRoute}`); } else { converter.printError(); } // Call when conversion succeeds with compatibility concerns. converter.printWarning(); ``` ## AI Coding Instructions - Use `tryConvert()` as the primary conversion entry point and consume its returned route string before registering the route with the current router. - Keep legacy-format parsing and migration rules inside `LegacyRouteConverter`; avoid duplicating compatibility logic at router call sites. - Use `printError()` for unrecoverable conversion failures and `printWarning()` for supported-but-deprecated legacy patterns. - Preserve the converter's diagnostic behavior when adding new legacy route formats so migrations remain observable. # 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) 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 extracts values from the incoming request's `req.query` object. It can bind the entire query object or a specific query parameter to a controller method argument, optionally applying pipes for parsing or validation. ## 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 A[HTTP Request] --> B[req.query] B --> C[@Query decorator] C --> D{Property specified?} D -->|No| E[Bind entire query object] D -->|Yes| F[Extract named query value] F --> G[Apply optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Query, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll( @Query('search') search?: string, @Query('page', ParseIntPipe) page = 1, @Query() filters?: Record, ) { return { search, page, filters, }; } } ``` For a request such as `GET /users?search=alex&page=2&role=admin`, `search` receives `"alex"`, `page` receives `2`, and `filters` contains the full query object. ## AI Coding Instructions - Use `@Query()` without a property name when the handler needs access to all query parameters; use `@Query('key')` for a single value. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom transformation pipes when query values require parsing or validation. - Remember that query parameters are typically strings unless transformed by a pipe. - Keep query extraction in controller route handlers; pass normalized values to services rather than exposing request-specific objects downstream. - Ensure property names passed to `@Query('property')` match the expected HTTP query parameter names. # SaslAuthenticateArgs **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L41) ## Definition ```ts { request: SaslAuthenticationRequest; response?: SaslAuthenticationResponse; } ``` # AppModule **Kind:** Module **Source:** [`sample/15-mvc/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/15-mvc/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # CatsController **Kind:** Controller **Source:** [`integration/mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/cats.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - DEPENDS_ON β†’ `catsservice` # CatsService **Kind:** Service **Source:** [`sample/14-mongoose-base/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/cats.service.ts#L6) `CatsService` encapsulates persistence operations for cat records in the NestJS application. It provides methods to create new cats and retrieve all stored cats, acting as the boundary between controllers and the Mongoose model layer. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createCatDto: CreateCatDto)` | `Promise` | | `findAll` | `findAll()` | `Promise` | ## Dependencies - `Model` ## Diagram ```mermaid sequenceDiagram participant Client participant CatsController participant CatsService participant CatModel as Mongoose Cat Model participant Database as MongoDB Client->>CatsController: POST /cats or GET /cats CatsController->>CatsService: create(createCatDto) / findAll() alt Create cat CatsService->>CatModel: new CatModel(createCatDto) CatsService->>CatModel: save() CatModel->>Database: insert document Database-->>CatModel: saved cat CatModel-->>CatsService: Cat else Find all cats CatsService->>CatModel: find().exec() CatModel->>Database: query cats collection Database-->>CatModel: cat documents CatModel-->>CatsService: Cat[] end CatsService-->>CatsController: Cat or Cat[] CatsController-->>Client: HTTP response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsService } from './cats.service'; import { CreateCatDto } from './dto/create-cat.dto'; @Injectable() export class CatsController { constructor(private readonly catsService: CatsService) {} async createCat(createCatDto: CreateCatDto) { return this.catsService.create(createCatDto); } async getCats() { return this.catsService.findAll(); } } ``` ## AI Coding Instructions - Keep database access inside `CatsService`; controllers should delegate persistence work rather than using Mongoose models directly. - Use the injected Mongoose `Cat` model to construct and save new documents in `create()`. - Call `.exec()` on Mongoose query builders in `findAll()` to return a proper promise. - Ensure DTOs and the Mongoose schema remain aligned when adding or changing cat properties. - Add validation and error handling at the controller or service boundary when introducing required fields or uniqueness constraints. ## Relationships - DEPENDS_ON β†’ `model` # findAll **Kind:** API Endpoint **Source:** [`integration/typeorm/src/photo/photo.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/photo/photo.controller.ts#L9) ## Endpoint `GET /photo` ## Referenced By - `PhotoController` (MODULE_DECLARES) # 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) 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. # HostComponentInfo **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L25) `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. # ListenerMetadataExplorer **Kind:** Class **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L35) `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. # 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) 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 extracts values from the incoming request's `req.query` object. It can bind the entire query object or a specific query parameter to a controller method argument, optionally applying pipes for parsing or validation. ## 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 A[HTTP Request] --> B[req.query] B --> C[@Query decorator] C --> D{Property specified?} D -->|No| E[Bind entire query object] D -->|Yes| F[Extract named query value] F --> G[Apply optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Query, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll( @Query('search') search?: string, @Query('page', ParseIntPipe) page = 1, @Query() filters?: Record, ) { return { search, page, filters, }; } } ``` For a request such as `GET /users?search=alex&page=2&role=admin`, `search` receives `"alex"`, `page` receives `2`, and `filters` contains the full query object. ## AI Coding Instructions - Use `@Query()` without a property name when the handler needs access to all query parameters; use `@Query('key')` for a single value. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom transformation pipes when query values require parsing or validation. - Remember that query parameters are typically strings unless transformed by a pipe. - Keep query extraction in controller route handlers; pass normalized values to services rather than exposing request-specific objects downstream. - Ensure property names passed to `@Query('property')` match the expected HTTP query parameter names. # ServersChangedEvent **Kind:** Type **Source:** [`packages/microservices/events/nats.events.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/events/nats.events.ts#L3) ## Definition ```ts { added: string[]; deleted: string[]; } ``` # AppModule **Kind:** Module **Source:** [`sample/17-mvc-fastify/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/17-mvc-fastify/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # CatsController **Kind:** Controller **Source:** [`sample/14-mongoose-base/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/cats.controller.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ CatsController client->>+p1: CatsController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `create` - MODULE_DECLARES β†’ `findAll` - DEPENDS_ON β†’ `catsservice` # CatsService **Kind:** Service **Source:** [`integration/inspector/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/cats.service.ts#L4) `CatsService` is a NestJS service responsible for managing cat-related application logic. It provides operations to create a cat record and retrieve the current collection of `Cat` entities, typically acting as the boundary between controllers and persistence or in-memory data sources. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `unknown` | | `findAll` | `findAll()` | `Cat[]` | ## Diagram ```mermaid sequenceDiagram participant Client participant CatsController participant CatsService participant CatStore as Cat Repository/Store Client->>CatsController: POST /cats CatsController->>CatsService: create() CatsService->>CatStore: Create or persist cat CatStore-->>CatsService: Created result CatsService-->>CatsController: Result CatsController-->>Client: Response Client->>CatsController: GET /cats CatsController->>CatsService: findAll() CatsService->>CatStore: Retrieve cats CatStore-->>CatsService: Cat[] CatsService-->>CatsController: Cat[] CatsController-->>Client: 200 OK ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsService } from './cats.service'; @Injectable() export class CatsController { constructor(private readonly catsService: CatsService) {} createCat() { return this.catsService.create(); } getCats() { return this.catsService.findAll(); } } ``` ## AI Coding Instructions - Keep `CatsService` focused on business logic; delegate HTTP request handling and response formatting to controllers. - Preserve the `findAll(): Cat[]` return contract when changing retrieval logic or adding a repository integration. - Update `create()` with explicit input and return types when introducing cat creation DTOs or persistence behavior. - Register the service in its NestJS module's `providers` array before injecting it into controllers or other services. - Avoid exposing mutable internal cat collections directly; return immutable copies if the service manages in-memory state. # 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) `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. # findAll **Kind:** API Endpoint **Source:** [`sample/01-cats-app/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.controller.ts#L20) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # GUARDS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L23) ## Definition ```ts '__guards__' ``` ## Value ```ts '__guards__' ``` # 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) 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. # 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) 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 extracts values from the incoming request's `req.query` object. It can bind the entire query object or a specific query parameter to a controller method argument, optionally applying pipes for parsing or validation. ## 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 A[HTTP Request] --> B[req.query] B --> C[@Query decorator] C --> D{Property specified?} D -->|No| E[Bind entire query object] D -->|Yes| F[Extract named query value] F --> G[Apply optional pipes] E --> H[Route handler parameter] G --> H ``` ## Usage ```typescript import { Controller, Get, Query, ParseIntPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Get() findAll( @Query('search') search?: string, @Query('page', ParseIntPipe) page = 1, @Query() filters?: Record, ) { return { search, page, filters, }; } } ``` For a request such as `GET /users?search=alex&page=2&role=admin`, `search` receives `"alex"`, `page` receives `2`, and `filters` contains the full query object. ## AI Coding Instructions - Use `@Query()` without a property name when the handler needs access to all query parameters; use `@Query('key')` for a single value. - Apply pipes such as `ParseIntPipe`, validation pipes, or custom transformation pipes when query values require parsing or validation. - Remember that query parameters are typically strings unless transformed by a pipe. - Keep query extraction in controller route handlers; pass normalized values to services rather than exposing request-specific objects downstream. - Ensure property names passed to `@Query('property')` match the expected HTTP query parameter names. # TestingModuleOptions **Kind:** Type **Source:** [`packages/testing/testing-module.builder.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-module.builder.ts#L29) ## Definition ```ts Pick< NestApplicationContextOptions, 'moduleIdGeneratorAlgorithm' > ``` # AppModule **Kind:** Module **Source:** [`sample/19-auth-jwt/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `AuthModule` - MODULE_IMPORTS β†’ `usersmodule` # CatsService **Kind:** Service **Source:** [`sample/01-cats-app/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.service.ts#L4) `CatsService` encapsulates the business logic for managing cats in the NestJS application. It provides methods for creating cats and retrieving the current collection, acting as the service layer between controllers and cat data storage. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `unknown` | | `findAll` | `findAll()` | `Promise` | ## Diagram ```mermaid sequenceDiagram participant Client participant CatsController participant CatsService participant CatStore Client->>CatsController: POST /cats CatsController->>CatsService: create(createCatDto) CatsService->>CatStore: Save cat data CatStore-->>CatsService: Created cat CatsService-->>CatsController: Created cat CatsController-->>Client: Response Client->>CatsController: GET /cats CatsController->>CatsService: findAll() CatsService->>CatStore: Retrieve cats CatStore-->>CatsService: Cat[] CatsService-->>CatsController: Promise CatsController-->>Client: Cat list ``` ## Usage ```ts import { CatsService } from './cats.service'; async function listCats(catsService: CatsService) { const cats = await catsService.findAll(); console.log(`Found ${cats.length} cats`); return cats; } // In a NestJS controller: @Get() findAll() { return this.catsService.findAll(); } ``` ## AI Coding Instructions - Keep `CatsService` focused on cat-related business logic; controllers should only handle HTTP request and response concerns. - Preserve the asynchronous `Promise` contract of `findAll()` when adding database or repository integrations. - Validate incoming cat data through DTOs and NestJS validation pipes before passing it to `create()`. - Inject persistence dependencies, such as a repository or database client, through the constructor rather than creating them directly in service methods. - Update controller endpoints and related tests when changing method signatures or return types. # DurableController **Kind:** Controller **Source:** [`integration/inspector/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/durable/durable.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ DurableController client->>+p1: DurableController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - MODULE_DECLARES β†’ `echo` - DEPENDS_ON β†’ `durableservice` # 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) 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. # findAll **Kind:** API Endpoint **Source:** [`sample/05-sql-typeorm/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.controller.ts#L23) ## Endpoint `GET /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) ## Definition ```ts Symbol.for('handler_metadata:cache') ``` ## Value ```ts Symbol.for('handler_metadata:cache') ``` # 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) `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. # TopicPartition **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L876) ## Definition ```ts { topic: string; partition: number; } ``` # 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) 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 extracts the uploaded `file` object from an incoming HTTP request. It is intended for Express applications using Multer middleware, which parses multipart form-data and attaches the uploaded file to `request.file`. ## 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/form-data request] --> Multer[Multer middleware] Multer --> Request[Express request.file] Request --> UploadedFile[@UploadedFile() decorator] UploadedFile --> Handler[Route handler file 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, originalName: file.originalname, size: file.size, }; } } ``` ## AI Coding Instructions - Use `@UploadedFile()` only on route handler parameters that receive a single uploaded file. - Configure Multer-compatible middleware or a `FileInterceptor` before expecting `request.file` to be populated. - Ensure the multipart form field name passed to `FileInterceptor('file')` matches the client upload field name. - Validate file presence, size, and MIME type before processing or persisting uploaded content. - Use `@UploadedFiles()` instead when the endpoint accepts multiple files. # AppModule **Kind:** Module **Source:** [`sample/25-dynamic-modules/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/app.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # CatsService **Kind:** Service **Source:** [`sample/10-fastify/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/cats.service.ts#L4) `CatsService` provides the core application logic for managing cat records in the Fastify-based NestJS sample. It exposes methods to create a cat entry and retrieve the current collection of cats, acting as the data-access boundary used by controllers or other application services. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `unknown` | | `findAll` | `findAll()` | `Cat[]` | ## Diagram ```mermaid sequenceDiagram participant Client participant CatsController participant CatsService participant CatsStore as In-Memory Cat Store Client->>CatsController: POST /cats (create cat) CatsController->>CatsService: create() CatsService->>CatsStore: Add cat record CatsStore-->>CatsService: Created result CatsService-->>CatsController: Return result CatsController-->>Client: Created response Client->>CatsController: GET /cats CatsController->>CatsService: findAll() CatsService->>CatsStore: Read cat records CatsStore-->>CatsService: Cat[] CatsService-->>CatsController: Cat[] CatsController-->>Client: 200 OK with cats ``` ## Usage ```ts import { CatsService } from './cats.service'; async function listCats(catsService: CatsService) { await catsService.create(); const cats = catsService.findAll(); console.log(cats); } ``` ## AI Coding Instructions - Keep business and persistence-oriented logic inside `CatsService`; controllers should delegate to `create()` and `findAll()` rather than managing cat state directly. - Preserve the `findAll(): Cat[]` contract when changing storage implementations or adding filtering logic. - Update `create()` to accept a typed DTO if cat creation needs request-provided fields; validate input at the controller/DTO boundary. - When replacing in-memory storage with a database, keep the service API stable and introduce repository or ORM dependencies through NestJS dependency injection. # findAll **Kind:** API Endpoint **Source:** [`sample/06-mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.controller.ts#L16) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) 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. # InstanceLoader **Kind:** Class **Source:** [`packages/core/injector/instance-loader.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-loader.ts#L11) `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`. # 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) # PhotoController **Kind:** Controller **Source:** [`integration/typeorm/src/photo/photo.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/photo/photo.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ PhotoController client->>+p1: PhotoController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `findAll` - MODULE_DECLARES β†’ `create` - DEPENDS_ON β†’ `photoservice` # 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) 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 extracts the uploaded `file` object from an incoming HTTP request. It is intended for Express applications using Multer middleware, which parses multipart form-data and attaches the uploaded file to `request.file`. ## 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/form-data request] --> Multer[Multer middleware] Multer --> Request[Express request.file] Request --> UploadedFile[@UploadedFile() decorator] UploadedFile --> Handler[Route handler file 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, originalName: file.originalname, size: file.size, }; } } ``` ## AI Coding Instructions - Use `@UploadedFile()` only on route handler parameters that receive a single uploaded file. - Configure Multer-compatible middleware or a `FileInterceptor` before expecting `request.file` to be populated. - Ensure the multipart form field name passed to `FileInterceptor('file')` matches the client upload field name. - Validate file presence, size, and MIME type before processing or persisting uploaded content. - Use `@UploadedFiles()` instead when the endpoint accepts multiple files. # 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) ## Definition ```ts | string | typeof VERSION_NEUTRAL | Array ``` # AppModule **Kind:** Module **Source:** [`sample/27-scheduling/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/27-scheduling/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `TasksModule` # CatsService **Kind:** Service **Source:** [`sample/36-hmr-esm/src/cats/cats.service.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/cats.service.ts#L4) `CatsService` encapsulates the backend logic for creating and retrieving cat records. It is used by the cats module to provide a focused service layer between controllers and cat data or domain models. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: Cat)` | `unknown` | | `findAll` | `findAll()` | `Promise` | ## Diagram ```mermaid sequenceDiagram participant Client participant CatsController participant CatsService participant CatData as Cat Data Source Client->>CatsController: POST /cats CatsController->>CatsService: create() CatsService->>CatData: Create cat record CatData-->>CatsService: Created result CatsService-->>CatsController: Return result CatsController-->>Client: Response Client->>CatsController: GET /cats CatsController->>CatsService: findAll() CatsService->>CatData: Fetch all cats CatData-->>CatsService: Cat[] CatsService-->>CatsController: Promise CatsController-->>Client: Cat[] ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { CatsService } from './cats.service'; @Injectable() export class CatsController { constructor(private readonly catsService: CatsService) {} createCat() { return this.catsService.create(); } async getCats() { const cats = await this.catsService.findAll(); return cats; } } ``` ## AI Coding Instructions - Keep controller handlers thin; delegate cat-related business logic to `CatsService`. - Preserve the asynchronous `Promise` contract of `findAll()` when changing its implementation. - Define and use the shared `Cat` type consistently for all returned cat collections. - Add input DTOs and validation before expanding `create()` to accept request data. - Register the service in its NestJS module providers before injecting it into controllers or other services. # findAll **Kind:** API Endpoint **Source:** [`sample/07-sequelize/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.controller.ts#L15) ## Endpoint `GET /users` ## Referenced By - `UsersController` (MODULE_DECLARES) # HEADERS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L39) ## Definition ```ts '__headers__' ``` ## Value ```ts '__headers__' ``` # KafkaParser **Kind:** Class **Source:** [`packages/microservices/helpers/kafka-parser.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/kafka-parser.ts#L4) `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. # MatchingAcl **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L479) `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. # PhotoController **Kind:** Controller **Source:** [`sample/13-mongo-typeorm/src/photo/photo.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/13-mongo-typeorm/src/photo/photo.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ PhotoController client->>+p1: PhotoController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `findAll` - DEPENDS_ON β†’ `photoservice` # 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) 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 extracts the uploaded `file` object from an incoming HTTP request. It is intended for Express applications using Multer middleware, which parses multipart form-data and attaches the uploaded file to `request.file`. ## 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/form-data request] --> Multer[Multer middleware] Multer --> Request[Express request.file] Request --> UploadedFile[@UploadedFile() decorator] UploadedFile --> Handler[Route handler file 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, originalName: file.originalname, size: file.size, }; } } ``` ## AI Coding Instructions - Use `@UploadedFile()` only on route handler parameters that receive a single uploaded file. - Configure Multer-compatible middleware or a `FileInterceptor` before expecting `request.file` to be populated. - Ensure the multipart form field name passed to `FileInterceptor('file')` matches the client upload field name. - Validate file presence, size, and MIME type before processing or persisting uploaded content. - Use `@UploadedFiles()` instead when the endpoint accepts multiple files. # 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) ## Definition ```ts { port: number; message: unknown; } ``` # AppModule **Kind:** Module **Source:** [`sample/28-sse/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/28-sse/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # CircularService **Kind:** Service **Source:** [`integration/injector/src/circular/circular.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular/circular.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CircularService client->>+p1: CircularService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `inputservice` # 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) ## Definition ```ts ClientProvider & { name: string | symbol; } ``` # findAll **Kind:** API Endpoint **Source:** [`sample/10-fastify/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/cats.controller.ts#L20) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # HOST_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L9) ## Definition ```ts 'host' ``` ## Value ```ts 'host' ``` # 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) `MessageHandler` defines the callable contract used by the microservices layer to process incoming messages. Its `next` function receives typed input and optional context, then resolves to either a result value or an `Observable` result; metadata fields identify event handlers and allow additional transport-specific configuration. ## Properties | Property | Type | |---|---| | `next` | `( data: TInput, ctx?: TContext, ) => Promise> | Promise` | | `isEventHandler` | `boolean` | | `extras` | `Record` | ## Diagram ```mermaid graph LR A[Incoming Message] --> B[MessageHandler.next] B --> C[data: TInput] B --> D[ctx?: TContext] B --> E{Handler result} E --> F[Promise] E --> G[Promise>] H[isEventHandler] --> B I[extras] --> B ``` ## Usage ```ts import { Observable, of } from 'rxjs'; import { MessageHandler } from './interfaces/message-handler.interface'; interface CreateUserInput { email: string; } interface RequestContext { requestId: string; } interface UserResult { id: string; email: string; } const createUserHandler: MessageHandler< CreateUserInput, UserResult, RequestContext > = { isEventHandler: false, extras: { pattern: 'users.create', }, async next(data, ctx) { console.log(`Creating user for request ${ctx?.requestId}`); return { id: 'user_123', email: data.email, }; }, }; const userCreatedEventHandler: MessageHandler< CreateUserInput, UserResult, RequestContext > = { isEventHandler: true, extras: { pattern: 'users.created', }, async next(data): Promise> { return of({ id: 'user_123', email: data.email, }); }, }; ``` ## AI Coding Instructions - Implement `next` as an asynchronous function that accepts `TInput` and an optional `TContext`. - Return either `Promise` for a single response or `Promise>` when streaming results. - Set `isEventHandler` to `true` for event-driven handlers that do not follow request-response semantics. - Use `extras` for transport, routing, or framework metadata rather than placing infrastructure details in the message payload. - Preserve the generic input, result, and context types when registering or wrapping handlers. # MiddlewareContainer **Kind:** Class **Source:** [`packages/core/middleware/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/container.ts#L8) `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. # RequestChainController **Kind:** Controller **Source:** [`integration/inspector/src/request-chain/request-chain.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/request-chain.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RequestChainController client->>+p1: RequestChainController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `requestchainservice` # 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) 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 extracts the uploaded `file` object from an incoming HTTP request. It is intended for Express applications using Multer middleware, which parses multipart form-data and attaches the uploaded file to `request.file`. ## 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/form-data request] --> Multer[Multer middleware] Multer --> Request[Express request.file] Request --> UploadedFile[@UploadedFile() decorator] UploadedFile --> Handler[Route handler file 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, originalName: file.originalname, size: file.size, }; } } ``` ## AI Coding Instructions - Use `@UploadedFile()` only on route handler parameters that receive a single uploaded file. - Configure Multer-compatible middleware or a `FileInterceptor` before expecting `request.file` to be populated. - Ensure the multipart form field name passed to `FileInterceptor('file')` matches the client upload field name. - Validate file presence, size, and MIME type before processing or persisting uploaded content. - Use `@UploadedFiles()` instead when the endpoint accepts multiple files. # AppModule **Kind:** Module **Source:** [`sample/30-event-emitter/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `OrdersModule` # CircularService **Kind:** Service **Source:** [`integration/injector/src/circular-modules/circular.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-modules/circular.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CircularService client->>+p1: CircularService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `inputservice` # ConsumerEndBatchProcessEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L969) ## Definition ```ts InstrumentationEvent< IBatchProcessEvent & { duration: number } > ``` # findAll **Kind:** API Endpoint **Source:** [`sample/13-mongo-typeorm/src/photo/photo.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/13-mongo-typeorm/src/photo/photo.controller.ts#L9) ## Endpoint `GET /photo` ## Referenced By - `PhotoController` (MODULE_DECLARES) # HTTP_CODE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L37) ## Definition ```ts '__httpCode__' ``` ## Value ```ts '__httpCode__' ``` # ModuleCompiler **Kind:** Class **Source:** [`packages/core/injector/compiler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/compiler.ts#L14) `ModuleCompiler` resolves a module definition into a normalized `ModuleFactory`. It supports both standard module classes and dynamic module objects, extracting dynamic metadata when present so the injector can register imports, providers, exports, and configuration consistently. ## 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] B --> C{isDynamicModule?} C -->|No| D[Use module class as type] C -->|Yes| E[extractMetadata] E --> F[Module type + dynamic metadata] D --> G[ModuleFactory] F --> G G --> H[Injector / Container registration] ``` ## 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); console.log(staticFactory.type); // AppModule // Compile a dynamic module definition const dynamicFactory = await compiler.compile({ module: AppModule, providers: [ { provide: 'API_URL', useValue: 'https://api.example.com', }, ], exports: ['API_URL'], }); console.log(dynamicFactory.type); // AppModule console.log(dynamicFactory.dynamicMetadata?.providers); ``` ## AI Coding Instructions - Pass either a module class or a valid `DynamicModule` object containing a `module` property. - Use `compile()` when downstream code needs a normalized `ModuleFactory` regardless of module input type. - Keep dynamic module metadata separate from the `module` class; `extractMetadata()` intentionally omits the `module` field from returned dynamic metadata. - Use `isDynamicModule()` for type narrowing before accessing dynamic properties such as `providers`, `imports`, or `exports`. - Preserve the asynchronous `compile()` contract when integrating with container initialization or module scanning flows. # 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) `MulterModuleAsyncOptions` configures Multer asynchronously when registering NestJS's Express platform upload module. It supports resolving `MulterModuleOptions` through an existing provider, a dedicated 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 ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { MulterModule, MulterModuleAsyncOptions, } from '@nestjs/platform-express'; const multerOptions: MulterModuleAsyncOptions = { useFactory: async (configService: ConfigService) => ({ dest: configService.get('UPLOAD_DIRECTORY') ?? './uploads', limits: { fileSize: 5 * 1024 * 1024, }, }), inject: [ConfigService], }; @Module({ imports: [MulterModule.registerAsync(multerOptions)], }) export class UploadModule {} ``` ## AI Coding Instructions - Use exactly one configuration strategy: `useExisting`, `useClass`, or `useFactory`. - Return a valid `MulterModuleOptions` object from `useFactory`; it may be returned synchronously or as a `Promise`. - List every dependency used by `useFactory` in the `inject` array, in the same argument order. - Prefer `useExisting` when a reusable `MulterOptionsFactory` provider already exists; use `useClass` when Nest should instantiate a dedicated factory. - Configure upload size limits, storage, and file filtering in the resolved Multer options rather than directly in controllers. # RequestChainController **Kind:** Controller **Source:** [`integration/scopes/src/request-chain/request-chain.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/request-chain.controller.ts#L5) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RequestChainController client->>+p1: RequestChainController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` - DEPENDS_ON β†’ `requestchainservice` # 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) 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. # 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) 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. # AppModule **Kind:** Module **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `postsmodule` # CircularService **Kind:** Service **Source:** [`integration/inspector/src/circular-modules/circular.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-modules/circular.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CircularService client->>+p1: CircularService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `inputservice` # DescribeAclResource **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L458) ## Definition ```ts AclResource & { acls: Acl[]; } ``` # findAll **Kind:** API Endpoint **Source:** [`sample/14-mongoose-base/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/cats.controller.ts#L15) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # INJECTABLE_WATERMARK **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L44) ## Definition ```ts '__injectable__' ``` ## Value ```ts '__injectable__' ``` # 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) `ParamProperties` describes how a controller method parameter is resolved during route execution. It stores the parameter position, parameter source and metadata, optional transformation pipes, and an `extractValue` function that retrieves the raw value from the request lifecycle objects. ## Properties | Property | Type | |---|---| | `index` | `number` | | `type` | `RouteParamtypes | string` | | `data` | `ParamData` | | `pipes` | `PipeTransform[]` | | `extractValue` | `( req: TRequest, res: TResponse, next: Function, ) => any` | ## Diagram ```mermaid graph LR A[Incoming Request] --> B[extractValue] B --> C[Raw Parameter Value] C --> D[pipes: PipeTransform[]] D --> E[Transformed Value] E --> F[Controller Method Parameter] G[index] --> F H[type: RouteParamtypes | string] --> B I[data: ParamData] --> B ``` ## Usage ```ts import { ParamProperties } from './router-execution-context'; const userIdParam: ParamProperties = { index: 0, type: 'param', data: 'userId', pipes: [ { transform(value: string) { const parsed = Number(value); if (Number.isNaN(parsed)) { throw new Error('userId must be a number'); } return parsed; }, }, ], extractValue: (req) => req.params.userId, }; // Used by the route execution context to call: // controller.getUser(transformedUserId) ``` ## AI Coding Instructions - Keep `index` aligned with the parameter's zero-based position in the controller method signature. - Use `extractValue` only to retrieve the raw value; apply validation and conversion through `pipes`. - Preserve `type` and `data` metadata so route parameter decorators can be resolved consistently. - Ensure custom pipes implement `PipeTransform` and return the value expected by the controller handler. - Avoid assuming a specific request implementation in `extractValue` unless the surrounding HTTP adapter guarantees it. # ReplFunction **Kind:** Class **Source:** [`packages/core/repl/repl-function.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-function.ts#L6) `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] # RMQFanoutExchangeConsumerController **Kind:** Controller **Source:** [`integration/microservices/src/rmq/fanout-exchange-consumer-rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/fanout-exchange-consumer-rmq.controller.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ RMQFanoutExchangeConsumerController client->>+p1: RMQFanoutExchangeConsumerController p1-->client: return response ``` # AppModule **Kind:** Module **Source:** [`sample/31-graphql-federation-code-first/users-application/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/users-application/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `usersmodule` # CircularService **Kind:** Service **Source:** [`integration/injector/src/circular-properties/circular.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-properties/circular.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CircularService client->>+p1: CircularService p1-->client: return response ``` # createPipesRpcParamDecorator **Kind:** Function **Source:** [`packages/microservices/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/utils/param.utils.ts#L25) ## Signature ```ts function createPipesRpcParamDecorator(paramtype: RpcParamtype) ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `RpcParamtype` | # DiscoverableDecorator **Kind:** Type **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L42) ## Definition ```ts ((opts?: T) => CustomDecorator) & { KEY: string; } ``` # findAll **Kind:** API Endpoint **Source:** [`sample/36-hmr-esm/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/cats.controller.ts#L20) ## Endpoint `GET /cats` ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) ## Definition ```ts 'INQUIRER' ``` ## Value ```ts 'INQUIRER' ``` # 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) `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. # 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) `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] # TestController **Kind:** Controller **Source:** [`integration/scopes/src/circular-transient/test.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/test.controller.ts#L12) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ TestController client->>+p1: TestController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` # AppModule **Kind:** Module **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `postsmodule` # ClientOptionService **Kind:** Service **Source:** [`integration/microservices/src/tcp-tls/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.module.ts#L45) `ClientOptionService` provides the TCP/TLS client configuration used by the NestJS microservice integration. Its `createClientOptions()` method centralizes transport, connection, and TLS-related options so clients can be configured consistently within the application module. ## Methods | Method | Signature | Returns | |---|---|---| | `createClientOptions` | `createClientOptions()` | `Promise | ClientOptions` | ## Dependencies - `ConfigService` ## Diagram ```mermaid sequenceDiagram participant App as NestJS Application Module participant Service as ClientOptionService participant Client as Nest Microservice Client participant Server as TCP/TLS Server App->>Service: createClientOptions() Service-->>App: ClientOptions App->>Client: Create client with options Client->>Server: Establish TCP/TLS connection Server-->>Client: Accept secure connection ``` ## Usage ```ts import { ClientProxyFactory } from '@nestjs/microservices'; import { ClientOptionService } from './app.module'; async function createTcpTlsClient() { const clientOptionService = new ClientOptionService(); const options = await clientOptionService.createClientOptions(); const client = ClientProxyFactory.create(options); await client.connect(); return client; } ``` ## AI Coding Instructions - Keep all TCP/TLS client configuration inside `createClientOptions()` rather than duplicating transport options at call sites. - Ensure the returned value conforms to NestJS `ClientOptions`, including the intended microservice transport configuration. - Preserve async compatibility: callers should handle both synchronous and `Promise` implementations with `await`. - When changing TLS settings, validate certificate paths, server hostnames, and local development behavior against the target TCP/TLS server. - Use this service as the integration point when adding environment-specific client connection settings. ## Relationships - DEPENDS_ON β†’ `ConfigService` # createPipesWsParamDecorator **Kind:** Function **Source:** [`packages/websockets/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/utils/param.utils.ts#L25) ## Signature ```ts function createPipesWsParamDecorator(paramtype: WsParamtype) ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `WsParamtype` | # FetchOffsetsPartition **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L440) ## Definition ```ts PartitionOffset & { metadata: string | null; } ``` # findOne **Kind:** API Endpoint **Source:** [`integration/inspector/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/cats.controller.ts#L23) ## Endpoint `GET /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `number` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # 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) ## Definition ```ts Symbol.for('instance_metadata:id') ``` ## Value ```ts Symbol.for('instance_metadata:id') ``` # ProducerConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L110) `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) # 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) `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. # TestController **Kind:** Controller **Source:** [`integration/scopes/src/transient/test.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/test.controller.ts#L12) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as πŸ“¦ TestController client->>+p1: TestController p1-->client: return response ``` ## Relationships - MODULE_DECLARES β†’ `greeting` # AppModule **Kind:** Module **Source:** [`sample/32-graphql-federation-schema-first/users-application/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/users-application/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `usersmodule` # ClientOptionService **Kind:** Service **Source:** [`integration/microservices/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.module.ts#L34) `ClientOptionService` provides NestJS microservice client configuration through its `createClientOptions()` method. It centralizes transport, connection, and client-specific settings so modules can register or initialize microservice clients consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `createClientOptions` | `createClientOptions()` | `Promise | ClientOptions` | ## Dependencies - `ConfigService` ## Diagram ```mermaid sequenceDiagram participant Module as NestJS Module participant Service as ClientOptionService participant Factory as createClientOptions() participant Client as Microservice Client Module->>Service: Inject service Service->>Factory: createClientOptions() Factory-->>Service: ClientOptions Service-->>Module: ClientOptions Module->>Client: Register/create client with options ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ClientsModule } from '@nestjs/microservices'; import { ClientOptionService } from './app.module'; @Module({ imports: [ ClientsModule.registerAsync([ { name: 'ORDERS_CLIENT', inject: [ClientOptionService], useFactory: (clientOptionService: ClientOptionService) => clientOptionService.createClientOptions(), }, ]), ], providers: [ClientOptionService], }) export class OrdersModule {} ``` ## AI Coding Instructions - Keep all microservice client transport and connection settings inside `createClientOptions()` rather than duplicating configuration across modules. - Ensure the returned value conforms to NestJS `ClientOptions`, including the correct transport-specific options. - Use `ClientsModule.registerAsync()` when configuration depends on injected services, environment variables, or application configuration. - Avoid hardcoding credentials, hostnames, or ports; source environment-dependent values through the project configuration pattern. - Update consuming client registrations when changing option structure, transport type, or client identifiers. ## Relationships - DEPENDS_ON β†’ `ConfigService` # 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) ## Signature ```ts function filterLogLevels(parseableString): LogLevel[] ``` ## Parameters | Name | Type | |---|---| | `parseableString` | `any` | **Returns:** `LogLevel[]` # findOne **Kind:** API Endpoint **Source:** [`sample/10-fastify/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/cats.controller.ts#L25) ## Endpoint `GET /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `number` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # GroupDescriptions **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L870) ## Definition ```ts { groups: GroupDescription[]; } ``` # 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) ## Definition ```ts Symbol.for('instance_metadata:cache') ``` ## Value ```ts Symbol.for('instance_metadata:cache') ``` # 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) `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) # 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) **Extends:** `Logger` ## Properties | Property | Type | |---|---| | `log` | `any` | | `error` | `any` | | `warn` | `any` | | `debug` | `any` | | `verbose` | `any` | | `fatal` | `any` | | `setLogLevels` | `any` | # AppModule **Kind:** Module **Source:** [`sample/35-use-esm-package-after-node22/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/35-use-esm-package-after-node22/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # ConfigService **Kind:** Service **Source:** [`sample/25-dynamic-modules/src/config/config.service.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/config/config.service.ts#L8) `ConfigService` is a NestJS provider responsible for exposing configuration values to other parts of the application. Its `get()` method returns a string-based configuration value, allowing dependent services and controllers to access configuration through dependency injection. ## Methods | Method | Signature | Returns | |---|---|---| | `get` | `get(key: string)` | `string` | ## Dependencies - `ConfigOptions` ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Service participant ConfigService participant Config as Configuration Source Consumer->>ConfigService: get() ConfigService->>Config: Read configured value Config-->>ConfigService: string value ConfigService-->>Consumer: string value ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { ConfigService } from './config/config.service'; @Injectable() export class AppService { constructor(private readonly configService: ConfigService) {} getConfigValue(): string { return this.configService.get(); } } ``` ## AI Coding Instructions - Inject `ConfigService` through NestJS constructor injection rather than creating it manually. - Treat `get()` as the public API for retrieving the service's configuration value. - Ensure the module that declares `ConfigService` exports it before using it from another module. - Keep configuration access centralized in this service instead of duplicating environment or module configuration logic in consumers. ## Relationships - DEPENDS_ON β†’ `ConfigOptions` # findOne **Kind:** API Endpoint **Source:** [`integration/inspector/src/database/database.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.controller.ts#L28) ## Endpoint `GET /database/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `DatabaseController` (MODULE_DECLARES) # INTERCEPTORS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L24) ## Definition ```ts '__interceptors__' ``` ## Value ```ts '__interceptors__' ``` # 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) ## Signature ```ts function INVALID_CLASS_SCOPE_MESSAGE(text: TemplateStringsArray, name: string | undefined) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `name` | `string | undefined` | # 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) 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`. # SocketsContainer **Kind:** Class **Source:** [`packages/websockets/sockets-container.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/sockets-container.ts#L4) `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] # TopicPartitionOffset **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L880) ## Definition ```ts TopicPartition & { offset: string; } ``` # AppModule **Kind:** Module **Source:** [`integration/discovery/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/app.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `MyWebhookModule` - MODULE_IMPORTS β†’ `DiscoveryModule` - MODULE_PROVIDES β†’ `WebhooksExplorer` # Barrier **Kind:** Class **Source:** [`packages/core/helpers/barrier.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/barrier.ts#L4) 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. # ConfigService **Kind:** Service **Source:** [`integration/graphql-schema-first/src/config.service.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/config.service.ts#L5) `ConfigService` centralizes GraphQL module configuration for the schema-first integration. Its `createGqlOptions()` method produces the `GqlModuleOptions` consumed by NestJS GraphQL module setup, keeping schema and runtime settings consistent. ## Methods | Method | Signature | Returns | |---|---|---| | `createGqlOptions` | `createGqlOptions()` | `GqlModuleOptions` | ## Diagram ```mermaid sequenceDiagram participant AppModule participant ConfigService participant GraphQLModule participant GraphQLRuntime AppModule->>ConfigService: createGqlOptions() ConfigService-->>AppModule: GqlModuleOptions AppModule->>GraphQLModule: forRoot(options) GraphQLModule->>GraphQLRuntime: Initialize schema-first GraphQL server ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { ConfigService } from './config.service'; @Module({ imports: [ GraphQLModule.forRootAsync({ inject: [ConfigService], useFactory: (configService: ConfigService) => configService.createGqlOptions(), }), ], providers: [ConfigService], }) export class AppModule {} ``` ## AI Coding Instructions - Keep GraphQL configuration logic inside `ConfigService.createGqlOptions()` rather than duplicating options across modules. - Return a valid `GqlModuleOptions` object compatible with the installed `@nestjs/graphql` version. - Preserve schema-first configuration conventions, including schema file paths and resolver integration settings. - Register `ConfigService` as a provider before injecting it into `GraphQLModule.forRootAsync()`. - When adding GraphQL features such as playground, context, or subscriptions, update the centralized options factory. # findOne **Kind:** API Endpoint **Source:** [`integration/inspector/src/dogs/dogs.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.controller.ts#L28) ## Endpoint `GET /dogs/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `DogsController` (MODULE_DECLARES) # INVALID_EXCEPTION_FILTER **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L262) ## Definition ```ts `Invalid exception filters (@UseFilters()).` ``` ## Value ```ts `Invalid exception filters (@UseFilters()).` ``` # isPlainObject **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L7) ## Signature ```ts function isPlainObject(fn: any): fn is object ``` ## Parameters | Name | Type | |---|---| | `fn` | `any` | **Returns:** `fn is object` # 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) `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] # TopicPartitionOffsetAndMetadata **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L883) ## Definition ```ts TopicPartitionOffset & { metadata?: string | null; } ``` # AppModule **Kind:** Module **Source:** [`integration/nest-application/get-url/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # ConsumerStartBatchProcessEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L967) ## Definition ```ts InstrumentationEvent ``` # DataInterceptor **Kind:** Service **Source:** [`integration/graphql-code-first/src/common/interceptors/data.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/common/interceptors/data.interceptor.ts#L10) `DataInterceptor` is a NestJS interceptor that participates in the request/response lifecycle for the code-first GraphQL integration. Its `intercept()` method delegates execution to the next handler and can observe or transform the resulting `Observable` before the resolver response is returned. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant GraphQL as GraphQL Resolver participant Interceptor as DataInterceptor participant Handler as Resolver Handler Client->>GraphQL: Execute query or mutation GraphQL->>Interceptor: intercept(context, next) Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable result Interceptor-->>GraphQL: Transformed/observed result GraphQL-->>Client: GraphQL response ``` ## Usage ```ts import { UseInterceptors } from '@nestjs/common'; import { Resolver, Query } from '@nestjs/graphql'; import { DataInterceptor } from '../common/interceptors/data.interceptor'; @Resolver() @UseInterceptors(DataInterceptor) export class UsersResolver { @Query(() => String) currentUser(): string { return 'Ada Lovelace'; } } ``` ## AI Coding Instructions - Keep `intercept()` non-blocking: return the `Observable` from `next.handle()` and use RxJS operators such as `map` or `tap` for response processing. - Apply `DataInterceptor` at the resolver, method, or global NestJS scope depending on whether the behavior should affect all GraphQL operations. - Do not subscribe to `next.handle()` inside the interceptor; NestJS manages the observable subscription lifecycle. - Preserve GraphQL-compatible return shapes and avoid wrapping results in a structure that conflicts with the schema. - Use `ExecutionContext` carefully when adding request-specific behavior, since GraphQL context access differs from standard HTTP request access. # findOne **Kind:** API Endpoint **Source:** [`integration/inspector/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.controller.ts#L28) ## Endpoint `GET /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # GuardsConsumer **Kind:** Class **Source:** [`packages/core/guards/guards-consumer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/guards/guards-consumer.ts#L7) `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. # INVALID_MIDDLEWARE_CONFIGURATION **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L260) ## 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.` ``` # optionalRequire **Kind:** Function **Source:** [`packages/core/helpers/optional-require.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/optional-require.ts#L1) ## Signature ```ts function optionalRequire(packageName: string, loaderFn: Function) ``` ## Parameters | Name | Type | |---|---| | `packageName` | `string` | | `loaderFn` | `Function` | # 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) 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. # AppModule **Kind:** Module **Source:** [`integration/nest-application/listen/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/listen/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # DefaultsService **Kind:** Service **Source:** [`integration/injector/src/defaults/defaults.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/defaults/defaults.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ DefaultsService client->>+p1: DefaultsService p1-->client: return response ``` # EnhancerSubtype **Kind:** Type **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L33) ## Definition ```ts (typeof ENHANCER_KEY_TO_SUBTYPE_MAP)[keyof typeof ENHANCER_KEY_TO_SUBTYPE_MAP] ``` # findOne **Kind:** API Endpoint **Source:** [`integration/repl/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.controller.ts#L28) ## Endpoint `GET /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # IS_PUBLIC_KEY **Kind:** Constant **Source:** [`sample/19-auth-jwt/src/auth/decorators/public.decorator.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/decorators/public.decorator.ts#L3) ## Definition ```ts 'isPublic' ``` ## Value ```ts 'isPublic' ``` # JsonSocket **Kind:** Class **Source:** [`packages/microservices/helpers/json-socket.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/json-socket.ts#L13) `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. # 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) ## Signature ```ts function RequestMapping(metadata: RequestMappingMetadata): MethodDecorator ``` ## Parameters | Name | Type | |---|---| | `metadata` | `RequestMappingMetadata` | **Returns:** `MethodDecorator` # 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) 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. # AppModule **Kind:** Module **Source:** [`integration/send-files/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # DefaultsService **Kind:** Service **Source:** [`integration/inspector/src/defaults/defaults.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/defaults/defaults.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ DefaultsService client->>+p1: DefaultsService p1-->client: return response ``` # findOne **Kind:** API Endpoint **Source:** [`sample/05-sql-typeorm/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.controller.ts#L28) ## Endpoint `GET /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `number` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # KAFKA_DEFAULT_BROKER **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L11) ## Definition ```ts 'localhost:9092' ``` ## Value ```ts 'localhost:9092' ``` # 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) `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. # 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) 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. # RunOptions **Kind:** Type **Source:** [`tools/benchmarks/src/autocannon/run.ts`](https://github.com/nestjs/nest/blob/master/tools/benchmarks/src/autocannon/run.ts#L3) ## Definition ```ts autocannon.Options & { /** * When true, prints live progress to stdout via `autocannon.track(instance)`. * Default: false (quiet) */ verbose?: boolean; } ``` # 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) `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] # AclEntry **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L456) ## Definition ```ts Acl & AclResource ``` # AppModule **Kind:** Module **Source:** [`sample/18-context/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/18-context/src/app.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `dynamicModule` - MODULE_PROVIDES β†’ `appservice` # 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) `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. # DurableGuard **Kind:** Service **Source:** [`integration/scopes/src/durable/durable.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.guard.ts#L9) `DurableGuard` is a NestJS guard responsible for determining whether a request or execution context can proceed through a durable-scoped integration. It implements asynchronous activation logic through `canActivate()`, allowing it to perform context-aware validation before the protected handler runs. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `Promise` | ## Dependencies - `DurableService` ## Where it refuses work - `DurableGuard` stops the work with `Error` when `typeof this.durableService === 'undefined'` β€” β€œDurable service is undefined”. ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant DurableGuard participant Handler Client->>NestJS: Request / execution context NestJS->>DurableGuard: canActivate(context) DurableGuard->>DurableGuard: Perform async validation alt Access allowed DurableGuard-->>NestJS: true NestJS->>Handler: Execute protected handler Handler-->>Client: Response else Access denied DurableGuard-->>NestJS: false / exception NestJS-->>Client: Access denied end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { DurableGuard } from './durable/durable.guard'; @Controller('durable') @UseGuards(DurableGuard) export class DurableController { @Get('status') getStatus() { return { status: 'available', }; } } ``` ## AI Coding Instructions - Keep `canActivate()` asynchronous and return a `Promise` so durable validation can safely perform async work. - Use NestJS `ExecutionContext` patterns when adding request, handler, or class-level metadata checks. - Apply `DurableGuard` with `@UseGuards(DurableGuard)` at the controller or route level where durable access rules are required. - Return `false` or throw an appropriate NestJS exception when access should be denied; do not allow protected handlers to perform authorization checks themselves. - Preserve dependency-injection compatibility when adding collaborators such as configuration, authentication, or durable execution services. ## Relationships - DEPENDS_ON β†’ `durableservice` # findOne **Kind:** API Endpoint **Source:** [`sample/06-mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.controller.ts#L21) ## Endpoint `GET /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # KAFKA_DEFAULT_CLIENT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L12) ## Definition ```ts 'nestjs-consumer' ``` ## Value ```ts 'nestjs-consumer' ``` # 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) # 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) 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. # AppModule **Kind:** Module **Source:** [`sample/20-cache/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/20-cache/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # Assignment **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L232) ## Definition ```ts { [topic: string]: number[] } ``` # createRpcParamDecorator **Kind:** Function **Source:** [`packages/microservices/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/utils/param.utils.ts#L8) ## Signature ```ts function createRpcParamDecorator(paramtype: RpcParamtype): (...pipes: (Type | PipeTransform)[]) => ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `RpcParamtype` | **Returns:** `(...pipes: (Type | PipeTransform)[]) => ParameterDecorator` # DurableService **Kind:** Service **Source:** [`integration/inspector/src/durable/durable.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/durable/durable.service.ts#L4) `DurableService` is a NestJS service located in the inspector integration module. It exposes a `greeting()` method that provides a durable-service response for consumers within the application, typically through dependency injection from a controller or another provider. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Consumer as Controller/Provider participant DurableService Client->>Consumer: Request durable greeting Consumer->>DurableService: greeting() DurableService-->>Consumer: Greeting response Consumer-->>Client: Return response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { DurableService } from './durable/durable.service'; @Injectable() export class InspectorService { constructor(private readonly durableService: DurableService) {} getGreeting() { return this.durableService.greeting(); } } ``` ## AI Coding Instructions - Inject `DurableService` through NestJS constructor injection instead of creating instances with `new`. - Keep `greeting()` focused on its service responsibility; place HTTP-specific concerns in controllers. - Ensure `DurableService` is registered in the appropriate NestJS module's `providers` array before injecting it. - Preserve the method's return contract when extending or refactoring callers, since it is currently typed as `unknown`. # findOne **Kind:** API Endpoint **Source:** [`sample/07-sequelize/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.controller.ts#L20) ## Endpoint `GET /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) `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. # KAFKA_DEFAULT_GROUP **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L13) ## Definition ```ts 'nestjs-group' ``` ## Value ```ts 'nestjs-group' ``` # 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) `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) # AppModule **Kind:** Module **Source:** [`sample/29-file-upload/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `appcontroller` - MODULE_PROVIDES β†’ `appservice` # BrokersFunction **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L27) ## Definition ```ts () => string[] | Promise ``` # createWsParamDecorator **Kind:** Function **Source:** [`packages/websockets/utils/param.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/utils/param.utils.ts#L8) ## Signature ```ts function createWsParamDecorator(paramtype: WsParamtype): (...pipes: (Type | PipeTransform)[]) => ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `paramtype` | `WsParamtype` | **Returns:** `(...pipes: (Type | PipeTransform)[]) => ParameterDecorator` # ErrorsInterceptor **Kind:** Service **Source:** [`sample/01-cats-app/src/common/interceptors/exception.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/interceptors/exception.interceptor.ts#L12) `ErrorsInterceptor` is a NestJS interceptor that wraps controller execution and observes the resulting `Observable`. It provides a centralized extension point for handling, transforming, logging, or rethrowing exceptions before they are returned through NestJS's HTTP exception layer. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Interceptor as ErrorsInterceptor participant Handler as Controller Handler participant Filter as Exception Filter Client->>Nest: HTTP request Nest->>Interceptor: intercept(context, next) Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable response or error alt Successful response Interceptor-->>Nest: Return response Observable Nest-->>Client: HTTP response else Exception thrown Interceptor->>Interceptor: Catch/log/transform error Interceptor-->>Filter: Rethrow mapped exception Filter-->>Client: Formatted error response end ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { ErrorsInterceptor } from './common/interceptors/exception.interceptor'; @Controller('cats') @UseInterceptors(ErrorsInterceptor) export class CatsController { @Get() findAll() { // Errors thrown here can be handled or transformed // by ErrorsInterceptor. return [{ id: 1, name: 'Milo' }]; } } ``` Register it globally when error behavior should apply to every route: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ErrorsInterceptor } from './common/interceptors/exception.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new ErrorsInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Keep `intercept()` compatible with NestJS's `CallHandler` contract: return the `Observable` produced by `next.handle()`. - Use RxJS operators such as `catchError`, `tap`, or `map` inside the interceptor rather than eagerly subscribing to the response stream. - Preserve existing `HttpException` status codes and response payloads unless there is an explicit API error-formatting requirement. - Register the interceptor with `@UseInterceptors()` for route/controller scope or `useGlobalInterceptors()` for application-wide behavior. - Avoid exposing stack traces, database details, or internal error messages in production responses; log sensitive diagnostic details server-side instead. # getBuffer **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L15) ## Endpoint `GET /file/buffer` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # ModulesContainer **Kind:** Class **Source:** [`packages/core/injector/modules-container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/modules-container.ts#L5) `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. # ValidationPipeOptions **Kind:** Interface **Source:** [`packages/common/pipes/validation.pipe.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/validation.pipe.ts#L26) `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`. # AppModule **Kind:** Module **Source:** [`tools/benchmarks/src/frameworks/nest/app.module.ts`](https://github.com/nestjs/nest/blob/master/tools/benchmarks/src/frameworks/nest/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # CatDocument **Kind:** Type **Source:** [`sample/06-mongoose/src/cats/schemas/cat.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/schemas/cat.schema.ts#L4) ## Definition ```ts HydratedDocument ``` # ErrorsInterceptor **Kind:** Service **Source:** [`sample/36-hmr-esm/src/common/interceptors/exception.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/interceptors/exception.interceptor.ts#L12) `ErrorsInterceptor` is a NestJS interceptor that wraps request handler execution and observes the returned `Observable`. It provides a centralized integration point for handling, transforming, or logging exceptions before they propagate through the application's HTTP exception layer. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Interceptor as ErrorsInterceptor participant Handler as Route Handler participant Filter as Exception Filter Client->>Nest: HTTP request Nest->>Interceptor: intercept(context, next) Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable response or error alt Handler succeeds Interceptor-->>Nest: Observable response Nest-->>Client: HTTP response else Handler throws an error Interceptor->>Interceptor: Handle/log/transform error Interceptor-->>Filter: Propagate exception Filter-->>Client: Error response end ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { ErrorsInterceptor } from './common/interceptors/exception.interceptor'; @Controller('users') @UseInterceptors(ErrorsInterceptor) export class UsersController { @Get() findAll() { return [{ id: 1, name: 'Ada Lovelace' }]; } } ``` Register it globally when exception behavior should apply to all routes: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ErrorsInterceptor } from './common/interceptors/exception.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new ErrorsInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Keep `intercept()` compatible with NestJS's `CallHandler` contract: return the `Observable` produced by `next.handle()`. - Use RxJS operators such as `catchError`, `tap`, or `map` to inspect or transform success and error streams without eagerly subscribing. - Preserve NestJS `HttpException` instances unless there is an explicit requirement to normalize them into another exception type. - Register the interceptor at controller, route, module, or global scope based on the intended error-handling coverage. - Avoid exposing internal error details, stack traces, credentials, or database information in client-facing responses. # getById **Kind:** API Endpoint **Source:** [`sample/04-grpc/src/hero/hero.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/hero/hero.controller.ts#L42) ## Endpoint `GET /hero/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `HeroController` (MODULE_DECLARES) # INVALID_EXECUTION_CONTEXT **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L44) ## Signature ```ts function INVALID_EXECUTION_CONTEXT(methodName: string, currentContext: string) ``` ## Parameters | Name | Type | |---|---| | `methodName` | `string` | | `currentContext` | `string` | # LOGGER_PROVIDER **Kind:** Constant **Source:** [`integration/scopes/src/resolve-scoped/logger.provider.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/resolve-scoped/logger.provider.ts#L3) ## Definition ```ts 'LOGGER_PROVIDER' ``` ## Value ```ts 'LOGGER_PROVIDER' ``` # 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) `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] # 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) `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) # AppModule **Kind:** Module **Source:** [`integration/cors/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/cors/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # 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) ## Definition ```ts ClientOptions | CustomClientOptions ``` # getCount **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L35) ## Endpoint `GET /count` ## Referenced By - `AppController` (MODULE_DECLARES) # Guard **Kind:** Service **Source:** [`integration/inspector/src/circular-hello/guards/request-scoped.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/guards/request-scoped.guard.ts#L9) `Guard` is a NestJS request-scoped guard responsible for deciding whether an incoming request may continue to its target route handler. Its `canActivate()` method can return a synchronous boolean, a `Promise`, or an `Observable`, allowing authorization logic to depend on request-specific or asynchronous services. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean | Promise | Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Guard participant Handler Client->>NestJS: HTTP request NestJS->>Guard: canActivate(context) Guard->>Guard: Evaluate request-scoped rules alt Access granted Guard-->>NestJS: true NestJS->>Handler: Invoke route handler Handler-->>Client: Response else Access denied Guard-->>NestJS: false NestJS-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Guard } from './guards/request-scoped.guard'; @Controller('hello') @UseGuards(Guard) export class HelloController { @Get() getHello() { return { message: 'Hello from a guarded route' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` focused on access decisions; return `true` to continue request processing and `false` to deny access. - Preserve support for synchronous, `Promise`, and `Observable` return values when adding asynchronous authorization checks. - Treat this as a request-scoped component: avoid storing request-specific state in shared static or singleton variables. - Apply the guard with `@UseGuards(Guard)` at the controller or route level where authorization is required. - Use NestJS `ExecutionContext` to safely access request data instead of relying on framework-global request objects. # MATH_SERVICE **Kind:** Constant **Source:** [`sample/03-microservices/src/math/math.constants.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/math/math.constants.ts#L1) ## Definition ```ts 'MATH_SERVICE' ``` ## Value ```ts 'MATH_SERVICE' ``` # 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) ## Signature ```ts function MergeWithValues(data: { [param: string]: any; }) ``` ## Parameters | Name | Type | |---|---| | `data` | `{ [param: string]: any; }` | # 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) `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] # 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) 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. # AclFilter **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L469) `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. # AppModule **Kind:** Module **Source:** [`integration/hello-world/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/app.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `hellomodule` - MODULE_IMPORTS β†’ `HostModule` - MODULE_IMPORTS β†’ `HostArrayModule` # 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) `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. # ConnectEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L406) ## Definition ```ts InstrumentationEvent ``` # getError **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L109) ## Endpoint `GET /exception` ## Referenced By - `NatsController` (MODULE_DECLARES) # Guard **Kind:** Service **Source:** [`integration/scopes/src/circular-hello/guards/request-scoped.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/guards/request-scoped.guard.ts#L9) `Guard` is a NestJS request-scoped guard used by the circular hello integration scope to determine whether an incoming request may proceed. Its `canActivate()` method participates in NestJS's authorization pipeline and can return a synchronous boolean, `Promise`, or `Observable`. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean | Promise | Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Router participant Guard as Request-Scoped Guard participant Controller Client->>Nest: HTTP request Nest->>Guard: canActivate(context) Guard-->>Nest: boolean / Promise / Observable alt Access allowed Nest->>Controller: Invoke route handler Controller-->>Client: Response else Access denied Nest-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Guard } from './guards/request-scoped.guard'; @Controller('hello') @UseGuards(Guard) export class HelloController { @Get() getHello() { return { message: 'Hello from a guarded route' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` compatible with NestJS guard return types: `boolean`, `Promise`, or `Observable`. - Apply `Guard` with `@UseGuards(Guard)` at the controller or route level where request access must be checked. - Preserve request-scoped behavior when adding dependencies; avoid storing request-specific state in static or singleton fields. - Return `false` to deny access, or throw a NestJS exception when a more specific error response is required. - Ensure dependencies used by this guard are available in the module that provides the guarded controller. # MESSAGE_MAPPING_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L3) ## Definition ```ts 'websockets:message_mapping' ``` ## Value ```ts 'websockets:message_mapping' ``` # RQM_NO_EVENT_HANDLER **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L43) ## Signature ```ts function RQM_NO_EVENT_HANDLER(text: TemplateStringsArray, pattern: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `pattern` | `string` | # 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) `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. # AppModule **Kind:** Module **Source:** [`integration/nest-application/app-locals/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/app-locals/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # 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) ## Definition ```ts new (...args: any[]) => T ``` # 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) `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. # getFile **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L10) ## Endpoint `GET /file/stream` ## Referenced By - `AppController` (MODULE_DECLARES) # Guard **Kind:** Service **Source:** [`integration/scopes/src/circular-transient/guards/request-scoped.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/guards/request-scoped.guard.ts#L9) `Guard` is a NestJS request-scoped guard used in the circular transient integration scenario. Its `canActivate()` method determines whether an incoming request may continue through the route handling pipeline, supporting synchronous, asynchronous, and Observable-based authorization results. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean | Promise | Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Router participant Guard participant Controller Client->>Nest: Send HTTP request Nest->>Guard: Create/request scoped instance Nest->>Guard: canActivate(context) Guard-->>Nest: boolean | Promise | Observable alt Access allowed Nest->>Controller: Invoke route handler Controller-->>Client: Return response else Access denied Nest-->>Client: Return forbidden response end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Guard } from './guards/request-scoped.guard'; @Controller('protected') @UseGuards(Guard) export class ProtectedController { @Get() getProtectedResource() { return { message: 'Access granted' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` compatible with NestJS guard return types: `boolean`, `Promise`, or `Observable`. - Preserve the request-scoped provider configuration when modifying this guard, as it is part of the circular/transient dependency integration scenario. - Use `ExecutionContext` to access request, handler, or controller metadata when adding authorization logic. - Return `false` for denied access; throw framework exceptions only when a specific error response is required. - Register the guard through `@UseGuards()` or the NestJS global guard configuration rather than invoking it manually. # MESSAGE_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L4) ## Definition ```ts 'message' ``` ## Value ```ts 'message' ``` # RQM_NO_MESSAGE_HANDLER **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L48) ## Signature ```ts function RQM_NO_MESSAGE_HANDLER(text: TemplateStringsArray, pattern: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `pattern` | `string` | # AppModule **Kind:** Module **Source:** [`integration/nest-application/sse/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # BrokerMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L651) `BrokerMetadata` represents Kafka cluster metadata returned by the microservices Kafka transport. It provides the available broker endpoints and topic-level partition metadata needed to route requests, inspect cluster topology, or validate topic availability. ## 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 Metadata[BrokerMetadata] Metadata --> Brokers[brokers] Metadata --> Topics[topicMetadata] Brokers --> Broker[Broker endpoint] Broker --> NodeId[nodeId] Broker --> Host[host] Broker --> Port[port] Broker --> Rack[rack optional] Topics --> Topic[Topic metadata] Topic --> TopicName[topic] Topic --> ErrorCode[topicErrorCode] Topic --> Partitions[partitionMetadata] ``` ## Usage ```ts import type { BrokerMetadata } from './kafka.interface'; function logClusterMetadata(metadata: BrokerMetadata): void { for (const broker of metadata.brokers) { const address = `${broker.host}:${broker.port}`; console.log(`Broker ${broker.nodeId}: ${address}`); if (broker.rack) { console.log(` Rack: ${broker.rack}`); } } for (const topic of metadata.topicMetadata) { if (topic.topicErrorCode !== 0) { console.warn( `Unable to load metadata for topic "${topic.topic}": ${topic.topicErrorCode}`, ); continue; } console.log( `Topic "${topic.topic}" has ${topic.partitionMetadata.length} partitions`, ); } } ``` ## AI Coding Instructions - Treat `topicErrorCode === 0` as the successful topic metadata response before using partition information. - Use `host` and `port` together when constructing broker connection addresses; `nodeId` identifies the broker within the Kafka cluster. - Handle `rack` as optional, since Kafka deployments may not have rack-aware configuration enabled. - Preserve all `partitionMetadata` entries when transforming metadata, as they contain routing and leadership details required by Kafka consumers and producers. # ConsumerEachBatchPayload **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1023) 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`. # 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) `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] # getFileWithHeaders **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L30) ## Endpoint `GET /file/with/headers` ## Referenced By - `AppController` (MODULE_DECLARES) # Guard **Kind:** Service **Source:** [`integration/scopes/src/transient/guards/request-scoped.guard.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/guards/request-scoped.guard.ts#L9) `Guard` is a NestJS request-scoped guard that controls whether an incoming request may continue to its target route handler. Its `canActivate()` method can return a synchronous boolean, a `Promise`, or an `Observable`, allowing authorization logic to run synchronously or asynchronously within the request lifecycle. ## Methods | Method | Signature | Returns | |---|---|---| | `canActivate` | `canActivate(context: ExecutionContext)` | `boolean | Promise | Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Guard participant Controller Client->>NestJS: HTTP request NestJS->>Guard: canActivate() Guard-->>NestJS: boolean / Promise / Observable alt Access allowed NestJS->>Controller: Invoke route handler Controller-->>Client: Response else Access denied NestJS-->>Client: 403 Forbidden end ``` ## Usage ```ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { Guard } from './request-scoped.guard'; @Controller('protected') @UseGuards(Guard) export class ProtectedController { @Get() getProtectedResource() { return { message: 'Access granted' }; } } ``` ## AI Coding Instructions - Keep `canActivate()` focused on determining access; return `true` to allow the request and `false` to deny it. - Preserve support for synchronous, `Promise`, and `Observable` return values when adding asynchronous authorization checks. - Register the guard through `@UseGuards(Guard)` at the controller or route level, or configure it globally when appropriate. - Treat this as request-scoped code: avoid storing request-specific state in static fields or singleton dependencies. - Use NestJS `ExecutionContext` when request, user, headers, or route metadata are needed for authorization logic. # METHOD_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L17) ## Definition ```ts 'method' ``` ## Value ```ts 'method' ``` # 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) 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. # AppModule **Kind:** Module **Source:** [`integration/nest-application/use-body-parser/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/use-body-parser/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # assignToken **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L113) ## Signature ```ts function assignToken(metatype: Type, token): Type ``` ## Parameters | Name | Type | |---|---| | `metatype` | `Type` | | `token` | `any` | **Returns:** `Type` # ConfigEntries **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L349) `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. # ConsumerEachMessagePayload **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1017) 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. # ExceptionsHandler **Kind:** Class **Source:** [`packages/core/exceptions/exceptions-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/exceptions-handler.ts#L9) `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] # getGlobals **Kind:** API Endpoint **Source:** [`integration/cors/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/cors/src/app.controller.ts#L5) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # HelloService **Kind:** Service **Source:** [`integration/inspector/src/circular-hello/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/hello.service.ts#L3) `HelloService` is a NestJS provider responsible for supplying a simple greeting message through its `greeting()` method. It can be injected into controllers or other services as part of the circular hello integration fixture. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller / Service participant HelloService Consumer->>HelloService: greeting() HelloService-->>Consumer: string greeting ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './hello.service'; @Injectable() export class HelloController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloService` through NestJS constructor injection rather than creating it with `new`. - Keep `greeting()` synchronous and return a plain `string` unless consumers require asynchronous behavior. - Register `HelloService` in the relevant NestJS module's `providers` array before injecting it. - When modifying circular-module dependencies, use NestJS patterns such as `forwardRef()` where required to avoid unresolved provider errors. # 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) ## 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.)` ``` # AppModule **Kind:** Module **Source:** [`integration/repl/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `usersmodule` # 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) 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. # ConsumerFetchStartEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L951) ## Definition ```ts InstrumentationEvent<{ nodeId: number }> ``` # CoordinatorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L190) `CoordinatorMetadata` represents the result of a Kafka group coordinator lookup. It includes the broker-level error code and connection details for the coordinator node responsible for a consumer group or transaction. ## Properties | Property | Type | |---|---| | `errorCode` | `number` | | `coordinator` | `{ nodeId: number; host: string; port: number; }` | ## Diagram ```mermaid graph LR A[Kafka Client] --> B[CoordinatorMetadata] B --> C[errorCode: number] B --> D[coordinator] D --> E[nodeId: number] D --> F[host: string] D --> G[port: number] A --> H[Connect to Coordinator Broker] H --> D ``` ## Usage ```ts import type { CoordinatorMetadata } from './kafka.interface'; function connectToCoordinator(metadata: CoordinatorMetadata): string { if (metadata.errorCode !== 0) { throw new Error( `Unable to locate Kafka coordinator (error code: ${metadata.errorCode})`, ); } const { nodeId, host, port } = metadata.coordinator; console.log(`Connecting to coordinator ${nodeId} at ${host}:${port}`); return `${host}:${port}`; } const metadata: CoordinatorMetadata = { errorCode: 0, coordinator: { nodeId: 1, host: 'kafka-broker.internal', port: 9092, }, }; connectToCoordinator(metadata); ``` ## AI Coding Instructions - Check `errorCode` before using the coordinator host and port; a non-zero value indicates the lookup did not succeed. - Use `coordinator.host` and `coordinator.port` together when creating a broker connection. - Treat `coordinator.nodeId` as the Kafka broker identifier, not a consumer group or partition identifier. - Preserve the nested `coordinator` object shape when mapping Kafka protocol responses into this interface. - Ensure broker hostnames and ports are sourced from Kafka metadata rather than hard-coded when coordinator discovery is available. # 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) `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) # getGlobals **Kind:** API Endpoint **Source:** [`integration/nest-application/app-locals/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/app-locals/src/app.controller.ts#L6) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # HelloService **Kind:** Service **Source:** [`integration/scopes/src/circular-hello/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/hello.service.ts#L3) `HelloService` is a NestJS provider responsible for generating a greeting message through its `greeting()` method. It belongs to the `circular-hello` integration scope and can be injected into controllers or other services that need hello-related behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller / Service participant HelloService Consumer->>HelloService: greeting() HelloService-->>Consumer: string greeting ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './hello.service'; @Injectable() export class GreetingController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Keep `HelloService` injectable through NestJS dependency injection; do not instantiate it directly with `new`. - Use `greeting()` as the public API for retrieving the service's greeting string. - Register `HelloService` in the appropriate NestJS module's `providers` array before injecting it elsewhere. - Preserve circular-scope integration boundaries when adding dependencies or exports. # MIDDLEWARE_PARAM_VALUE **Kind:** Constant **Source:** [`integration/nest-application/global-prefix/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.module.ts#L5) ## Definition ```ts 'middleware_param' ``` ## Value ```ts 'middleware_param' ``` # AppModule **Kind:** Module **Source:** [`sample/01-cats-app/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `coremodule` - MODULE_IMPORTS β†’ `catsmodule` # Client **Kind:** Function **Source:** [`packages/microservices/decorators/client.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/decorators/client.decorator.ts#L12) 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. # ConsumerSerializer **Kind:** Type **Source:** [`packages/microservices/interfaces/serializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/serializer.interface.ts#L18) ## Definition ```ts Serializer ``` # 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) `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. # 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) `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) # getHealth **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L15) ## Endpoint `GET /health` ## Referenced By - `AppController` (MODULE_DECLARES) # HelloService **Kind:** Service **Source:** [`integration/scopes/src/circular-transient/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/hello.service.ts#L3) `HelloService` is a NestJS service located in the circular transient integration scope. It provides a simple `greeting()` method that returns a greeting string, typically serving as a lightweight dependency for validating transient provider creation and circular dependency behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Consumer as NestJS Consumer participant Container as NestJS DI Container participant Hello as HelloService Consumer->>Container: Resolve HelloService Container->>Hello: Create transient instance Consumer->>Hello: greeting() Hello-->>Consumer: Greeting string ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './hello.service'; @Injectable() export class GreetingController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloService` through NestJS constructor dependency injection rather than instantiating it with `new`. - Treat `greeting()` as a synchronous, side-effect-free method that returns a `string`. - Preserve the service's provider scope when modifying its NestJS module configuration, especially in circular transient dependency tests. - When adding dependencies, use NestJS circular-dependency patterns such as `forwardRef()` where required by the surrounding integration scope. # MIDDLEWARE_VALUE **Kind:** Constant **Source:** [`integration/nest-application/global-prefix/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.module.ts#L4) ## Definition ```ts 'middleware' ``` ## Value ```ts 'middleware' ``` # AppModule **Kind:** Module **Source:** [`sample/02-gateways/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/02-gateways/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `eventsmodule` # 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) ## Definition ```ts (info: HostComponentInfo) => ContextId ``` # EventOrMessageListenerDefinition **Kind:** Interface **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L21) `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) # getHello **Kind:** API Endpoint **Source:** [`integration/nest-application/get-url/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/src/app.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # HelloService **Kind:** Service **Source:** [`integration/scopes/src/hello/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/hello.service.ts#L3) `HelloService` is a NestJS provider responsible for supplying a simple greeting message through its `greeting()` method. It can be injected into controllers or other services that need a consistent hello response within the integration scopes application. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant HelloService Client->>Controller: Request greeting endpoint Controller->>HelloService: greeting() HelloService-->>Controller: string greeting Controller-->>Client: Return response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './hello.service'; @Injectable() export class HelloController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloService` through NestJS constructor dependency injection; do not instantiate it manually with `new`. - Keep `greeting()` synchronous and return a plain `string` unless callers require external or asynchronous data. - Register `HelloService` in the appropriate NestJS module's `providers` array before injecting it elsewhere. - Keep controller responsibilities limited to request handling; place greeting-related business logic in this service. # 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) `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. # MINIMUM_AGE **Kind:** Constant **Source:** [`sample/12-graphql-schema-first/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/dto/create-cat.dto.ts#L4) ## Definition ```ts 1 ``` ## Value ```ts 1 ``` # AppModule **Kind:** Module **Source:** [`sample/03-microservices/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `MathModule` # 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) ## Definition ```ts 'http' | 'ws' | 'rpc' ``` # 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) # getHello **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L5) ## Endpoint `GET /hello/:name` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `name` | path | `string` | βœ“ | | ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # HelloService **Kind:** Service **Source:** [`integration/scopes/src/msvc/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/hello.service.ts#L3) `HelloService` is a NestJS service responsible for providing a simple greeting message through its `greeting()` method. It can be injected into controllers or other providers that need a lightweight health-check, demo, or greeting response within the scoped microservice. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant HelloService Client->>Controller: Request greeting endpoint Controller->>HelloService: greeting() HelloService-->>Controller: greeting string Controller-->>Client: Response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './msvc/hello.service'; @Injectable() export class HelloController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloService` through NestJS constructor dependency injection; do not instantiate it with `new`. - Keep `greeting()` synchronous and side-effect free unless its contract is intentionally expanded. - Register the service in the appropriate NestJS module `providers` array before injecting it elsewhere. - Update consuming controllers or integration tests if the greeting return value or method signature changes. # 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) `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`. # MINIMUM_AGE_ERROR **Kind:** Constant **Source:** [`sample/12-graphql-schema-first/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/dto/create-cat.dto.ts#L5) ## Definition ```ts `Age must be greater than ${MINIMUM_AGE}` ``` ## Value ```ts `Age must be greater than ${MINIMUM_AGE}` ``` # AppModule **Kind:** Module **Source:** [`sample/04-grpc/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `HeroModule` # 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) ## Definition ```ts object ``` # 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) `ExternalHandlerMetadata` describes the dependency metadata required to invoke a handler defined outside the standard class constructor flow. It records the handler argument count, reflected parameter types, and a resolver function for obtaining parameter metadata within a specific module and dependency-injection context. This interface is typically used by the core container or injector to resolve handler arguments consistently across module, request, and transient-provider contexts. ## Properties | Property | Type | |---|---| | `argsLength` | `number` | | `paramtypes` | `any[]` | | `getParamsMetadata` | `( moduleKey: string, contextId?: ContextId, inquirerId?: string, ) => ParamPropertiesWithMetatype[]` | ## Diagram ```mermaid graph LR A[External Handler] --> B[ExternalHandlerMetadata] B --> C[argsLength: number] B --> D[paramtypes: any[]] B --> E[getParamsMetadata] E --> F[moduleKey] E --> G[contextId] E --> H[inquirerId] E --> I[ParamPropertiesWithMetatype[]] I --> J[Dependency Injector] ``` ## Usage ```ts import { ContextId } from '@nestjs/core'; import { ExternalHandlerMetadata } from './external-handler-metadata.interface'; const handlerMetadata: ExternalHandlerMetadata = { argsLength: 2, paramtypes: [UserService, RequestContext], getParamsMetadata( moduleKey: string, contextId?: ContextId, inquirerId?: string, ) { return [ { index: 0, metatype: UserService, type: 'custom', }, { index: 1, metatype: RequestContext, type: 'request', }, ]; }, }; // The injector can use the metadata to resolve handler dependencies. const params = handlerMetadata.getParamsMetadata('AppModule'); console.log(`Handler expects ${handlerMetadata.argsLength} arguments`, params); ``` ## AI Coding Instructions - Keep `argsLength` synchronized with the actual number of parameters expected by the external handler. - Populate `paramtypes` with reflected or explicitly known runtime types used by the dependency injector. - Implement `getParamsMetadata` so it respects the provided `moduleKey`, optional `contextId`, and optional `inquirerId`. - Return parameter metadata in the correct parameter-index order to ensure dependencies are injected into the intended handler arguments. - Avoid assuming metadata is global; request-scoped and transient dependencies may require `contextId` and `inquirerId` for correct resolution. # getHello **Kind:** API Endpoint **Source:** [`integration/nest-application/listen/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/listen/src/app.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # HelloService **Kind:** Service **Source:** [`integration/scopes/src/transient/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/hello.service.ts#L3) `HelloService` is a NestJS service that provides a simple greeting value through its `greeting()` method. It is intended for injection into controllers or other providers that need a lightweight, transient-scope greeting dependency. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Provider participant DI as NestJS DI Container participant Hello as HelloService Consumer->>DI: Request HelloService DI->>Hello: Create transient instance Consumer->>Hello: greeting() Hello-->>Consumer: string greeting ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './hello.service'; @Injectable() export class GreetingController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloService` through NestJS constructor injection rather than instantiating it with `new`. - Preserve the `greeting(): string` contract when modifying the service or its consumers. - Account for transient scope: consumers may receive a new `HelloService` instance for each resolution. - Register the service in the appropriate NestJS module's `providers` array before injecting it elsewhere. # 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) 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. # KafkaJSError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1144) **Extends:** `Error` ## Properties | Property | Type | |---|---| | `message` | `Error['message']` | | `name` | `string` | | `retriable` | `boolean` | | `helpUrl` | `string` | | `cause` | `Error` | # 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) 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. # AppModule **Kind:** Module **Source:** [`sample/10-fastify/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` - MODULE_IMPORTS β†’ `coremodule` # DefaultPartitioner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L136) ## Definition ```ts ICustomPartitioner ``` # getHello **Kind:** API Endpoint **Source:** [`sample/08-webpack/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/08-webpack/src/app.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # HelloService **Kind:** Service **Source:** [`integration/hello-world/src/hello/hello.service.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.service.ts#L3) `HelloService` is a NestJS provider responsible for supplying the application's greeting message. It encapsulates simple greeting behavior so controllers or other services can consume it through NestJS dependency injection. ## Methods | Method | Signature | Returns | |---|---|---| | `greeting` | `greeting()` | `string` | ## Diagram ```mermaid sequenceDiagram participant Client participant HelloController participant HelloService Client->>HelloController: Request greeting endpoint HelloController->>HelloService: greeting() HelloService-->>HelloController: "Hello World!" HelloController-->>Client: Greeting response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelloService } from './hello.service'; @Injectable() export class HelloController { constructor(private readonly helloService: HelloService) {} getGreeting(): string { return this.helloService.greeting(); } } ``` ## AI Coding Instructions - Inject `HelloService` through the constructor rather than creating it with `new`. - Keep `greeting()` synchronous and side-effect free unless the service contract is intentionally expanded. - Register `HelloService` in the relevant NestJS module's `providers` array before injecting it. - Consume the service from controllers or other providers; avoid placing greeting logic directly in route handlers. # INVALID_MIDDLEWARE_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L143) ## Signature ```ts function INVALID_MIDDLEWARE_MESSAGE(text: TemplateStringsArray, name: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `name` | `string` | # KafkaJSRequestTimeoutErrorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1304) `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. # MODULE_PATH **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L38) ## Definition ```ts '__module_path__' ``` ## Value ```ts '__module_path__' ``` # PathsExplorer **Kind:** Class **Source:** [`packages/core/router/paths-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/paths-explorer.ts#L25) `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] # AppModule **Kind:** Module **Source:** [`sample/11-swagger/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # DisconnectEvent **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L407) ## Definition ```ts InstrumentationEvent ``` # getHello **Kind:** API Endpoint **Source:** [`sample/24-serve-static/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/24-serve-static/src/app.controller.ts#L5) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # HelperService **Kind:** Service **Source:** [`integration/inspector/src/request-chain/helper/helper.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/helper/helper.service.ts#L4) `HelperService` is a NestJS service located in the request-chain inspector integration. It currently exposes a `noop()` method that performs no defined business operation and returns an unspecified value. The service provides an injectable extension point for helper behavior within the inspector request flow. ## Methods | Method | Signature | Returns | |---|---|---| | `noop` | `noop()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as NestJS Consumer participant DI as NestJS DI Container participant Helper as HelperService Consumer->>DI: Request HelperService DI-->>Consumer: Inject HelperService instance Consumer->>Helper: noop() Helper-->>Consumer: unknown result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelperService } from './helper/helper.service'; @Injectable() export class InspectorService { constructor(private readonly helperService: HelperService) {} inspectRequest(): void { // Safe placeholder hook for request-chain helper behavior. this.helperService.noop(); } } ``` ## AI Coding Instructions - Inject `HelperService` through NestJS constructor injection; do not instantiate it directly with `new`. - Treat `noop()` as a placeholder operation: do not rely on a specific return type or side effect. - Keep future helper logic isolated in this service rather than adding request-chain utility behavior directly to consumers. - Ensure the module containing `HelperService` registers it in its `providers` array before injecting it elsewhere. # 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) ## Signature ```ts function INVALID_MODULE_CONFIG_MESSAGE(text: TemplateStringsArray, property: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `property` | `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) `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. # 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) 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. # 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) `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] # AppModule **Kind:** Module **Source:** [`sample/14-mongoose-base/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `catsmodule` # DiscoveryOptions **Kind:** Type **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L37) ## Definition ```ts FilterByInclude | FilterByMetadataKey ``` # getHello **Kind:** API Endpoint **Source:** [`sample/25-dynamic-modules/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/app.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # HelperService **Kind:** Service **Source:** [`integration/scopes/src/request-chain/helper/helper.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/helper/helper.service.ts#L4) `HelperService` is a NestJS provider used within the request-chain integration scope as a lightweight injectable dependency. Its `noop()` method provides a no-operation hook that can be used to validate service resolution, request-chain wiring, or extension points without introducing side effects. ## Methods | Method | Signature | Returns | |---|---|---| | `noop` | `noop()` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Request-Chain Consumer participant DI as NestJS DI Container participant Helper as HelperService Consumer->>DI: Resolve HelperService DI-->>Consumer: Inject HelperService instance Consumer->>Helper: noop() Helper-->>Consumer: unknown result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { HelperService } from './helper/helper.service'; @Injectable() export class RequestChainService { constructor(private readonly helperService: HelperService) {} execute() { // Invoke the helper without relying on side effects or a specific return type. return this.helperService.noop(); } } ``` ## AI Coding Instructions - Inject `HelperService` through NestJS constructor dependency injection; do not instantiate it manually with `new`. - Treat `noop()` as a side-effect-free extension or wiring hook unless its implementation is intentionally changed. - Since `noop()` returns `unknown`, narrow or validate its result before using it in typed application logic. - Ensure `HelperService` is registered in the appropriate NestJS module `providers` array before injecting it. - Keep this helper lightweight; place request-specific business logic in the request-chain services that consume it. # isMiddlewareClass **Kind:** Function **Source:** [`packages/core/middleware/utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/utils.ts#L100) ## Signature ```ts function isMiddlewareClass(middleware: any): middleware is Type ``` ## Parameters | Name | Type | |---|---| | `middleware` | `any` | **Returns:** `middleware is Type` # 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) 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. # MQTT_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L8) ## Definition ```ts 'mqtt://localhost:1883' ``` ## Value ```ts 'mqtt://localhost:1883' ``` # 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) `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. # AppModule **Kind:** Module **Source:** [`sample/16-gateways-ws/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/16-gateways-ws/src/app.module.ts#L4) ## Relationships - MODULE_IMPORTS β†’ `eventsmodule` # EachBatchHandler **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1025) ## Definition ```ts (payload: EachBatchPayload) => Promise ``` # getHello **Kind:** API Endpoint **Source:** [`sample/34-using-esm-packages/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/34-using-esm-packages/src/app.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # InputService **Kind:** Service **Source:** [`integration/injector/src/circular/input.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular/input.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ InputService client->>+p1: InputService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `circularservice` # 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) 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. # MQTT_SEPARATOR **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L14) ## Definition ```ts '/' ``` ## Value ```ts '/' ``` # 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) 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. # RoutesMapper **Kind:** Class **Source:** [`packages/core/middleware/routes-mapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/routes-mapper.ts#L24) `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. # AppModule **Kind:** Module **Source:** [`sample/21-serializer/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/app.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `appcontroller` # EachMessageHandler **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1026) ## Definition ```ts (payload: EachMessagePayload) => Promise ``` # getHello **Kind:** API Endpoint **Source:** [`sample/35-use-esm-package-after-node22/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/35-use-esm-package-after-node22/src/app.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # InputService **Kind:** Service **Source:** [`integration/injector/src/circular-modules/input.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-modules/input.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ InputService client->>+p1: InputService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `circularservice` # MODULE_INIT_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L7) ## Signature ```ts function MODULE_INIT_MESSAGE(text: TemplateStringsArray, module: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `module` | `string` | # MQTT_WILDCARD_ALL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L16) ## Definition ```ts '#' ``` ## Value ```ts '#' ``` # RetryOptions **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L253) `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) # 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) `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) # AppModule **Kind:** Module **Source:** [`sample/36-hmr-esm/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/app.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `coremodule` - MODULE_IMPORTS β†’ `catsmodule` # getHome **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L30) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # GroupMember **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L234) ## Definition ```ts { memberId: string; memberMetadata: Buffer } ``` # InputService **Kind:** Service **Source:** [`integration/inspector/src/circular-modules/input.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-modules/input.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ InputService client->>+p1: InputService p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `circularservice` # KafkaJSRequestTimeoutError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1185) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `broker` | `string` | | `correlationId` | `number` | | `createdAt` | `number` | | `sentAt` | `number` | | `pendingDuration` | `number` | # MQTT_WILDCARD_SINGLE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L15) ## Definition ```ts '+' ``` ## Value ```ts '+' ``` # 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) 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` property from the incoming request object. Use it when an endpoint needs access to the unparsed request payload as a `Buffer`, such as for webhook signature verification. ## Signature ```ts function RawBody(pipes: ( | Type> | PipeTransform )[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `( | Type> | PipeTransform )[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.rawBody] B --> C[@RawBody() decorator] C --> D[Route handler parameter: Buffer | undefined] ``` ## Usage ```typescript import { Controller, Post } from '@nestjs/common'; import { RawBody } from '@nestjs/common'; @Controller('webhooks') export class WebhookController { @Post() async handleWebhook(@RawBody() rawBody: Buffer | undefined) { if (!rawBody) { throw new Error('Raw request body is unavailable'); } const payload = rawBody.toString('utf8'); return { received: true, payloadLength: rawBody.length, payload, }; } } ``` ## AI Coding Instructions - Use `@RawBody()` only for handlers that require the original, unparsed request bytes. - Type the decorated parameter as `Buffer | undefined`, since `req.rawBody` may not be configured or available. - Ensure the HTTP adapter or body-parser configuration preserves the raw request body before relying on this decorator. - Prefer raw bytes for cryptographic signature validation; do not serialize or parse the body before verifying the signature. # 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) `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] # AsyncApplicationModule **Kind:** Module **Source:** [`integration/typeorm/src/app-async.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/app-async.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `photomodule` # getNonExistantFile **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L35) ## Endpoint `GET /file/not/exist` ## Referenced By - `AppController` (MODULE_DECLARES) # GroupState **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L241) ## Definition ```ts { name: string; metadata: Buffer } ``` # InputService **Kind:** Service **Source:** [`integration/injector/src/circular-properties/input.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-properties/input.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ InputService client->>+p1: InputService p1-->client: return response ``` # 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) `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`. # 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) ## Definition ```ts 'MULTER_MODULE_ID' ``` ## Value ```ts 'MULTER_MODULE_ID' ``` # 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) 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` property from the incoming request object. Use it when an endpoint needs access to the unparsed request payload as a `Buffer`, such as for webhook signature verification. ## Signature ```ts function RawBody(pipes: ( | Type> | PipeTransform )[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `( | Type> | PipeTransform )[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.rawBody] B --> C[@RawBody() decorator] C --> D[Route handler parameter: Buffer | undefined] ``` ## Usage ```typescript import { Controller, Post } from '@nestjs/common'; import { RawBody } from '@nestjs/common'; @Controller('webhooks') export class WebhookController { @Post() async handleWebhook(@RawBody() rawBody: Buffer | undefined) { if (!rawBody) { throw new Error('Raw request body is unavailable'); } const payload = rawBody.toString('utf8'); return { received: true, payloadLength: rawBody.length, payload, }; } } ``` ## AI Coding Instructions - Use `@RawBody()` only for handlers that require the original, unparsed request bytes. - Type the decorated parameter as `Buffer | undefined`, since `req.rawBody` may not be configured or available. - Ensure the HTTP adapter or body-parser configuration preserves the raw request body before relying on this decorator. - Prefer raw bytes for cryptographic signature validation; do not serialize or parse the body before verifying the signature. # 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) `SerializedGraphMetadata` describes supplemental metadata attached to a serialized graph entry when inspection detects an issue. It records the failure cause and optional details that help identify the affected module, node, dependency context, and underlying error. ## Properties | Property | Type | |---|---| | `cause` | `{ type: 'unknown-dependencies' | 'unknown'; context?: InjectorDependencyContext; moduleId?: string; nodeId?: string; error?: any; }` | ## Diagram ```mermaid graph LR Metadata[SerializedGraphMetadata] --> 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 './interfaces/serialized-graph-metadata.interface'; const metadata: SerializedGraphMetadata = { cause: { type: 'unknown-dependencies', moduleId: 'UsersModule', nodeId: 'UsersService', context: { index: 0, dependencies: ['DatabaseService'], name: 'DatabaseService', }, error: new Error('Unable to resolve dependency DatabaseService'), }, }; // Attach metadata to the relevant serialized graph node or edge. console.error(metadata.cause.type, metadata.cause.error); ``` ## AI Coding Instructions - Set `cause.type` to `'unknown-dependencies'` for dependency-resolution failures; use `'unknown'` only when no more specific cause is available. - Include `moduleId` and `nodeId` whenever the affected graph elements are known to make inspector output actionable. - Populate `context` with the related `InjectorDependencyContext` for unresolved constructor or provider dependencies. - Treat `error` as diagnostic data: preserve the original error when possible, but avoid assuming it is always an `Error` instance. ## How it works - `SerializedGraphMetadata` is an exported TypeScript interface for metadata attached to a serialized graph. Its sole required member is `cause`. [`packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts:3-10`] - `cause.type` must be either `'unknown-dependencies'` or `'unknown'`. It may also contain: - `context`, an `InjectorDependencyContext`; - `moduleId`, a string; - `nodeId`, a string; and - `error`, typed as `any`. All four fields are optional. [`packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts:4-10`] - `InjectorDependencyContext` can describe a property key, dependency name or token, dependency-array index, and dependency array; each of those members is optional. [`packages/core/injector/injector.ts:67-85`] - `GraphInspector.registerPartial(error)` marks its graph as `'partial'`. For an `UnknownDependenciesException`, it stores metadata whose cause type is `'unknown-dependencies'`, copies the exception’s dependency context, and conditionally records its module and node IDs. [`packages/core/inspector/graph-inspector.ts:38-49`] - For any other error passed to `registerPartial`, it stores metadata with cause type `'unknown'` and places the received error in `cause.error`. The method then registers the graph with `PartialGraphHost`. [`packages/core/inspector/graph-inspector.ts:50-58`] - `SerializedGraph` holds metadata in a private optional field; assigning its `metadata` setter replaces that field without visible validation or transformation. [`packages/core/inspector/serialized-graph.ts:35,56-58`] - During `SerializedGraph.toJSON()`, metadata is added as the optional `metadata` member of the graph JSON only when the private metadata field is truthy. [`packages/core/inspector/serialized-graph.ts:125-139`; `packages/core/inspector/interfaces/serialized-graph-json.interface.ts:8-15`] - The interface itself declares no runtime checks, error throwing, or side effects; it is a compile-time shape declaration. [`packages/core/inspector/interfaces/serialized-graph-metadata.interface.ts:1-12`] # Acl **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L443) `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. # BModule **Kind:** Module **Source:** [`integration/testing-module-override/circular-dependency/b.module.ts`](https://github.com/nestjs/nest/blob/master/integration/testing-module-override/circular-dependency/b.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `BProvider` - MODULE_EXPORTS β†’ `BProvider` # getNonFile **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L20) ## Endpoint `GET /non-file/pipe-method` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) ## Definition ```ts HandlerResponseBasicFn | HandleSseResponseFn ``` # Interceptor **Kind:** Service **Source:** [`integration/scopes/src/hello/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/interceptors/logging.interceptor.ts#L11) `Interceptor` is a NestJS interceptor that wraps request handling for the Hello scope and logs activity around controller execution. It implements the `intercept()` lifecycle hook, allowing it to run logic before the route handler and react to the returned `Observable` stream. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, call: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Interceptor as Logging Interceptor participant Controller as Hello Controller Client->>Nest: HTTP request Nest->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Log request / execution start Interceptor->>Controller: next.handle() Controller-->>Interceptor: Observable response Interceptor->>Interceptor: Log response / execution completion Interceptor-->>Nest: Return Observable Nest-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Interceptor } from './interceptors/logging.interceptor'; @Controller('hello') @UseInterceptors(Interceptor) export class HelloController { @Get() getHello(): { message: string } { return { message: 'Hello, world!' }; } } ``` ## AI Coding Instructions - Keep `intercept()` non-blocking: return the `next.handle()` observable and use RxJS operators for post-response behavior. - Use `ExecutionContext` to access request metadata such as HTTP method, URL, headers, or authenticated user when logging. - Avoid logging sensitive values, including authorization headers, cookies, passwords, or tokens. - Register the interceptor with `@UseInterceptors()` for route/controller scope, or configure it as a global provider when logging is required application-wide. - Preserve thrown errors and response values unless the interceptor is explicitly intended to transform them. # 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) ## Definition ```ts 'MULTER_MODULE_OPTIONS' ``` ## Value ```ts 'MULTER_MODULE_OPTIONS' ``` # 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) `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. # 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) 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` property from the incoming request object. Use it when an endpoint needs access to the unparsed request payload as a `Buffer`, such as for webhook signature verification. ## Signature ```ts function RawBody(pipes: ( | Type> | PipeTransform )[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `( | Type> | PipeTransform )[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.rawBody] B --> C[@RawBody() decorator] C --> D[Route handler parameter: Buffer | undefined] ``` ## Usage ```typescript import { Controller, Post } from '@nestjs/common'; import { RawBody } from '@nestjs/common'; @Controller('webhooks') export class WebhookController { @Post() async handleWebhook(@RawBody() rawBody: Buffer | undefined) { if (!rawBody) { throw new Error('Raw request body is unavailable'); } const payload = rawBody.toString('utf8'); return { received: true, payloadLength: rawBody.length, payload, }; } } ``` ## AI Coding Instructions - Use `@RawBody()` only for handlers that require the original, unparsed request bytes. - Type the decorated parameter as `Buffer | undefined`, since `req.rawBody` may not be configured or available. - Ensure the HTTP adapter or body-parser configuration preserves the raw request body before relying on this decorator. - Prefer raw bytes for cryptographic signature validation; do not serialize or parse the body before verifying the signature. # ApiVersions **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L660) # CatsModule **Kind:** Module **Source:** [`integration/mongoose/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/cats.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # getParams **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L10) ## Endpoint `GET /params` ## Referenced By - `AppController` (MODULE_DECLARES) # HeaderStream **Kind:** Type **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L59) ## Definition ```ts WritableHeaderStream & ReadHeaders ``` # Interceptor **Kind:** Service **Source:** [`integration/scopes/src/msvc/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/interceptors/logging.interceptor.ts#L11) `Interceptor` is a NestJS logging interceptor that wraps request handling in the integration scopes service. It observes the `intercept()` execution pipeline to capture request/response lifecycle information without changing the underlying controller or service behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, call: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Interceptor participant Controller participant Service Client->>NestJS: HTTP request NestJS->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Log request metadata Interceptor->>Controller: next.handle() Controller->>Service: Execute business logic Service-->>Controller: Return result Controller-->>Interceptor: Observable response Interceptor->>Interceptor: Log response/error details Interceptor-->>NestJS: Return Observable NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Interceptor } from './msvc/interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(Interceptor) export class HealthController { @Get() check() { return { status: 'ok', timestamp: new Date().toISOString(), }; } } ``` ## AI Coding Instructions - Keep `intercept()` non-blocking: return the `next.handle()` Observable and use RxJS operators for logging or response-side effects. - Avoid modifying request or response payloads unless the interceptor is explicitly intended to transform data. - Read request metadata through `ExecutionContext.switchToHttp()` when handling HTTP requests; account for other NestJS transports if this interceptor is shared. - Ensure logging does not expose sensitive headers, credentials, tokens, or personally identifiable information. - Register the interceptor with `@UseInterceptors()` for scoped usage or provide it through NestJS as a global interceptor when request-wide logging is required. # NAMESPACE_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L7) ## Definition ```ts 'namespace' ``` ## Value ```ts 'namespace' ``` # 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) 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. # 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) `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()`. # 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) 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. # CatsModule **Kind:** Module **Source:** [`sample/06-mongoose/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # getProfile **Kind:** API Endpoint **Source:** [`sample/19-auth-jwt/src/auth/auth.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/auth.controller.ts#L24) ## Endpoint `GET /auth/profile` ## Referenced By - `AuthController` (MODULE_DECLARES) # 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) ## Definition ```ts string | string[] | number ``` # Interceptor **Kind:** Service **Source:** [`integration/inspector/src/circular-hello/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/interceptors/logging.interceptor.ts#L10) `Interceptor` is a NestJS logging interceptor used in the circular hello integration flow. It wraps request handler execution, allowing the application to observe or log requests before and after the controller or service method runs. It integrates with NestJS's interceptor pipeline through the `intercept()` method. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, call: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Interceptor participant Handler as Controller/Route Handler Client->>NestJS: HTTP request NestJS->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Log/inspect incoming request Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable response Interceptor->>Interceptor: Log/inspect response or errors Interceptor-->>NestJS: Return response Observable NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Interceptor } from './interceptors/logging.interceptor'; @Controller('hello') @UseInterceptors(Interceptor) export class HelloController { @Get() getHello(): { message: string } { return { message: 'Hello from the circular integration example.' }; } } ``` To register it globally: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { Interceptor } from './circular-hello/interceptors/logging.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new Interceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Implement `intercept()` using NestJS's `CallHandler` and return the `Observable` from `next.handle()`; do not subscribe inside the interceptor. - Use RxJS operators such as `tap`, `map`, or `catchError` to inspect responses, transform output, or log errors without breaking the request pipeline. - Apply the interceptor with `@UseInterceptors(Interceptor)` for controller or route-level behavior, or register it globally through `app.useGlobalInterceptors(...)`. - Preserve the original handler response unless transformation is intentional, since downstream NestJS serialization depends on the returned observable value. - Avoid logging sensitive request headers, credentials, or personally identifiable information when inspecting execution context. # NATS_DEFAULT_GRACE_PERIOD **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L65) ## Definition ```ts 10000 ``` ## Value ```ts 10000 ``` # RouterProxy **Kind:** Class **Source:** [`packages/core/router/router-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-proxy.ts#L10) `RouterProxy` wraps route handlers and exception-layer callbacks so thrown or rejected errors are forwarded into Nest’s exception handling pipeline. It creates the execution context expected by exception filters, allowing HTTP adapters and middleware layers to handle errors consistently. ## 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[HTTP Request] --> B[RouterProxy.createProxy] B --> C[Route Handler] C -->|Success| D[HTTP Response] C -->|Throw / Reject| E[ExecutionContextHost] E --> F[Exceptions Handler] F --> D G[Error Middleware] --> H[createExceptionLayerProxy] H --> F ``` ## Usage ```ts import { RouterProxy } from '@nestjs/core/router/router-proxy'; const routerProxy = new RouterProxy(); const routeHandler = async (req, res) => { const user = await userService.findById(req.params.id); if (!user) { throw new Error('User not found'); } res.json(user); }; // Usually provided internally by Nest's router/exceptions infrastructure. const proxiedHandler = routerProxy.createProxy( routeHandler, exceptionsHandler, ); httpAdapter.get('/users/:id', proxiedHandler); // Wrap an error-layer callback when integrating custom router middleware. const exceptionLayer = routerProxy.createExceptionLayerProxy( (error, req, res, next) => next(error), exceptionsHandler, ); ``` ## AI Coding Instructions - Wrap asynchronous route callbacks with `createProxy()` so rejected promises reach Nest’s exception filters instead of becoming unhandled errors. - Pass the same exception handler instance used by the router’s exception-filter pipeline; do not replace it with ad hoc `try/catch` response logic. - Preserve the Express-style `(req, res, next)` callback signature when creating route proxies. - Use `createExceptionLayerProxy()` for error middleware layers that receive `(error, req, res, next)`. - Avoid sending a response after delegating an error to the exception handler, since the configured exception filter may already write the response. ## How it works ## `RouterProxy` `RouterProxy` is a class that builds asynchronous wrapper functions around router callbacks and routes failures from those callbacks to an `ExceptionsHandler`. It has two factory methods: one for `(req, res, next)` callbacks and one for error-layer `(err, req, res, next)` callbacks. [packages/core/router/router-proxy.ts:10-14](packages/core/router/router-proxy.ts#L10-L14) [packages/core/router/router-proxy.ts:30-38](packages/core/router/router-proxy.ts#L30-L38) # 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) 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. # 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) 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. # CatsModule **Kind:** Module **Source:** [`sample/14-mongoose-base/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/cats.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `databasemodule` - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # ClientsContainer **Kind:** Class **Source:** [`packages/microservices/container.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/container.ts#L3) `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. # DescribeAclResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L462) `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) # getRawBody **Kind:** API Endpoint **Source:** [`integration/nest-application/raw-body/src/express.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/raw-body/src/express.controller.ts#L6) ## Endpoint `POST /` ## Referenced By - `ExpressController` (MODULE_DECLARES) # ICustomPartitioner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L135) ## Definition ```ts () => (args: PartitionerArgs) => number ``` # Interceptor **Kind:** Service **Source:** [`integration/scopes/src/circular-hello/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/interceptors/logging.interceptor.ts#L10) `Interceptor` is a NestJS interceptor that wraps request handling to provide logging around controller execution. Its `intercept()` method receives the current execution context and `CallHandler`, allowing it to run logic before and after the downstream route handler returns an `Observable`. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, call: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Interceptor participant Controller Client->>NestJS: HTTP request NestJS->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Log request/start event Interceptor->>Controller: next.handle() Controller-->>Interceptor: Observable response Interceptor->>Interceptor: Log response/completion event Interceptor-->>NestJS: Return transformed Observable NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Interceptor } from './interceptors/logging.interceptor'; @Controller('hello') @UseInterceptors(Interceptor) export class HelloController { @Get() getHello(): { message: string } { return { message: 'Hello from the circular scope example' }; } } ``` ## AI Coding Instructions - Keep `intercept()` returning the `Observable` produced by `next.handle()`; do not eagerly subscribe inside the interceptor. - Use RxJS operators such as `tap`, `catchError`, or `finalize` to add logging without changing the request lifecycle. - Register the interceptor with `@UseInterceptors(Interceptor)` for controller or route-level logging, or configure it globally when appropriate. - Preserve errors by rethrowing them after logging; swallowing errors can prevent NestJS exception filters from producing correct responses. - Avoid logging sensitive request headers, credentials, tokens, or response payloads. # NATS_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L7) ## Definition ```ts 'nats://localhost:4222' ``` ## Value ```ts 'nats://localhost:4222' ``` # CatsModule **Kind:** Module **Source:** [`integration/inspector/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/cats.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # 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) 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. # Deserializer **Kind:** Interface **Source:** [`packages/microservices/interfaces/deserializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/deserializer.interface.ts#L10) # 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) `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) # getRawBody **Kind:** API Endpoint **Source:** [`integration/nest-application/raw-body/src/fastify.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/raw-body/src/fastify.controller.ts#L6) ## Endpoint `POST /` ## Referenced By - `FastifyController` (MODULE_DECLARES) # IncomingEvent **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L20) ## Definition ```ts ReadPacket ``` # Interceptor **Kind:** Service **Source:** [`integration/scopes/src/circular-transient/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/interceptors/logging.interceptor.ts#L10) `Interceptor` is a NestJS logging interceptor used in the circular transient integration scope. It wraps request handling through `intercept()` and returns an `Observable`, allowing logging or other cross-cutting behavior to run before and after the target handler executes. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, call: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Interceptor as Logging Interceptor participant Handler as Route/Provider Handler Client->>Nest: Request Nest->>Interceptor: intercept(context, next) Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable response Interceptor-->>Nest: Observable response Nest-->>Client: Response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Interceptor } from './interceptors/logging.interceptor'; @Controller('examples') @UseInterceptors(Interceptor) export class ExampleController { @Get() findAll() { return { message: 'Request processed through the logging interceptor.' }; } } ``` ## AI Coding Instructions - Keep `intercept()` compatible with NestJS's interceptor contract: accept an `ExecutionContext` and `CallHandler`, then return an `Observable`. - Call `next.handle()` to continue request execution; omitting it prevents the target handler from running. - Use RxJS operators such as `tap`, `map`, or `catchError` to add behavior without eagerly subscribing inside the interceptor. - Register the interceptor with `@UseInterceptors()` for local scope or through Nest providers for global application behavior. - Preserve transient-scope assumptions in this integration fixture; avoid converting this interceptor into a singleton dependency pattern unless the scope behavior is intentionally being changed. # NestFactory **Kind:** Constant **Source:** [`packages/core/nest-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts#L402) 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. # CatsModule **Kind:** Module **Source:** [`sample/01-cats-app/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # EachMessagePayload **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L994) `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) # ExceptionsZone **Kind:** Class **Source:** [`packages/core/errors/exceptions-zone.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exceptions-zone.ts#L6) `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. # 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) ## Signature ```ts function flatten(arr: T): T extends Array ? R : never ``` ## Parameters | Name | Type | |---|---| | `arr` | `T` | **Returns:** `T extends Array ? R : never` # getRequestContext **Kind:** API Endpoint **Source:** [`integration/scopes/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.controller.ts#L24) ## Endpoint `GET /durable/request-context` ## Referenced By - `DurableController` (MODULE_DECLARES) # IncomingRequest **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L18) ## Definition ```ts ReadPacket & PacketId ``` # Interceptor **Kind:** Service **Source:** [`integration/scopes/src/transient/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/interceptors/logging.interceptor.ts#L10) `Interceptor` is a NestJS logging interceptor used in the transient scope integration area. It wraps request handler execution, allowing the application to observe or log activity before and after a controller method returns an `Observable`. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, call: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant Interceptor participant Controller Client->>NestJS: HTTP request NestJS->>Interceptor: intercept(context, next) Interceptor->>Controller: next.handle() Controller-->>Interceptor: Observable response Interceptor-->>NestJS: Observable with logging behavior NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Interceptor } from './interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(Interceptor) export class HealthController { @Get() check() { return { status: 'ok' }; } } ``` ## AI Coding Instructions - Keep `intercept()` compatible with NestJS's interceptor contract: accept an `ExecutionContext` and `CallHandler`, then return an `Observable`. - Always invoke `next.handle()` to continue the request pipeline unless intentionally short-circuiting the request. - Use RxJS operators such as `tap`, `map`, or `catchError` to add logging without subscribing inside the interceptor. - Register the interceptor with `@UseInterceptors()` for route-level usage or provide it as `APP_INTERCEPTOR` for global usage. - Avoid logging sensitive request headers, authorization tokens, passwords, or personal data. # NO_MESSAGE_HANDLER **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L57) ## 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.` ``` # CatsModule **Kind:** Module **Source:** [`sample/10-fastify/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/cats.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # 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) `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. # getRxJSFile **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L25) ## Endpoint `GET /file/rxjs/stream` ## Referenced By - `AppController` (MODULE_DECLARES) # IncomingResponse **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L21) ## Definition ```ts WritePacket & PacketId ``` # LoggerMiddleware **Kind:** Service **Source:** [`integration/inspector/src/common/middleware/logger.middleware.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/common/middleware/logger.middleware.ts#L3) `LoggerMiddleware` is a NestJS middleware responsible for observing incoming HTTP requests and recording request/response information for the inspector integration. It runs before route handlers, making it a central place to add consistent request logging, timing, correlation IDs, or diagnostic metadata across the backend. ## Methods | Method | Signature | Returns | |---|---|---| | `use` | `use(req: any, res: any, next: () => void)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant LoggerMiddleware participant NestJS participant Controller participant Service Client->>LoggerMiddleware: HTTP request LoggerMiddleware->>LoggerMiddleware: Capture request context / start timing LoggerMiddleware->>NestJS: next() NestJS->>Controller: Invoke matched route handler Controller->>Service: Execute business logic Service-->>Controller: Return result Controller-->>Client: Send HTTP response LoggerMiddleware->>LoggerMiddleware: Record response status and duration ``` ## Usage ```ts import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './common/middleware/logger.middleware'; import { InspectorController } from './inspector.controller'; @Module({ controllers: [InspectorController], }) export class InspectorModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .forRoutes(InspectorController); } } ``` ## AI Coding Instructions - Keep `use()` non-blocking: always call `next()` unless the middleware intentionally terminates the request. - Capture request metadata defensively; headers, authenticated users, and request IDs may be absent. - Attach response logging to response lifecycle events such as `finish` when recording status codes or durations. - Avoid logging sensitive values such as authorization headers, cookies, tokens, passwords, or full request bodies. - Register the middleware through NestJS `MiddlewareConsumer` and scope it to appropriate routes when possible. # 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) 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. # NonAppliedDecorator **Kind:** Constant **Source:** [`integration/discovery/src/decorators/non-applied.decorator.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/decorators/non-applied.decorator.ts#L9) This decorator must not be used anywhere! This will be used to test the scenario where we are trying to retrieving metadata for a discoverable decorator that was not applied to any class. `NonAppliedDecorator` is a test-only decorator constant that is intentionally never applied to a class, method, or property. It provides a known discoverable decorator key for validating that metadata discovery correctly handles decorators with no registered usages. ## Definition ```ts DiscoveryService.createDecorator() ``` ## Value ```ts DiscoveryService.createDecorator() ``` ## Diagram ```mermaid graph LR A[NonAppliedDecorator constant] --> B[Discovery metadata lookup] B --> C[No decorated targets found] C --> D[Verify empty discovery result] ``` ## Usage ```ts import { NonAppliedDecorator } from './decorators/non-applied.decorator'; // Intentionally do not apply this decorator to any target. // // @NonAppliedDecorator() // class ExampleService {} describe('metadata discovery', () => { it('returns no results for an unused decorator', async () => { const results = await discoveryService.getMetadataByDecorator( NonAppliedDecorator, ); expect(results).toEqual([]); }); }); ``` ## AI Coding Instructions - Keep `NonAppliedDecorator` unassigned to all classes, methods, properties, and parameters; its purpose is to represent an unused decorator. - Use it only in discovery and metadata-retrieval tests that need to verify empty-result behavior. - Do not add production behavior or business logic that depends on this decorator. - When updating discovery APIs, ensure lookups for this decorator return an empty collection rather than throwing or returning unrelated metadata. # 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) 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 NestJS applications. It extracts the `files` object populated by Multer middleware and injects it into the decorated controller parameter, typically when handling multiple uploaded files or named file fields. ## Signature ```ts function UploadedFiles(pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[HTTP multipart/form-data request] --> Multer[Multer middleware] Multer --> Files[req.files] Files --> Decorator["@UploadedFiles()"] Decorator --> Handler[Controller handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFiles, UseInterceptors, } from '@nestjs/common'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors( FileFieldsInterceptor([ { name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: 5 }, ]), ) uploadFiles( @UploadedFiles() files: { avatar?: Express.Multer.File[]; documents?: Express.Multer.File[]; }, ) { return { avatar: files.avatar?.[0]?.filename, documentCount: files.documents?.length ?? 0, }; } } ``` ## AI Coding Instructions - Use `@UploadedFiles()` only with a Multer-compatible interceptor or middleware that populates `req.files`, such as `FileFieldsInterceptor` or `AnyFilesInterceptor`. - Prefer explicit TypeScript types for named file fields so controllers safely handle optional or repeated uploads. - Use `@UploadedFile()` instead when the endpoint accepts a single file rather than a `files` collection. - Validate file size, MIME type, and storage configuration in the associated Multer interceptor or upload middleware. - Handle missing fields defensively because optional multipart file fields may not be present in the injected object. # CatsModule **Kind:** Module **Source:** [`sample/11-swagger/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/cats.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # FilterByInclude **Kind:** Interface **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L16) `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. # getSlowFile **Kind:** API Endpoint **Source:** [`integration/send-files/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/app.controller.ts#L40) ## Endpoint `GET /file/slow` ## Referenced By - `AppController` (MODULE_DECLARES) # Injectable **Kind:** Type **Source:** [`packages/common/interfaces/injectable.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/injectable.interface.ts#L1) ## Definition ```ts unknown ``` # LoggerMiddleware **Kind:** Service **Source:** [`sample/01-cats-app/src/common/middleware/logger.middleware.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/middleware/logger.middleware.ts#L3) `LoggerMiddleware` is a NestJS middleware service that intercepts incoming HTTP requests before they reach route handlers. It is responsible for logging request-related information and then delegating control to the next middleware or controller in the pipeline. ## Methods | Method | Signature | Returns | |---|---|---| | `use` | `use(req: any, res: any, next: () => void)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant LoggerMiddleware participant Next as Next Middleware/Controller participant Handler as Route Handler Client->>LoggerMiddleware: HTTP request LoggerMiddleware->>LoggerMiddleware: Log request details LoggerMiddleware->>Next: next() Next->>Handler: Continue request pipeline Handler-->>Client: HTTP response ``` ## Usage ```ts import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './common/middleware/logger.middleware'; import { CatsModule } from './cats/cats.module'; @Module({ imports: [CatsModule], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('*'); } } ``` ## AI Coding Instructions - Keep `use()` compatible with NestJS middleware conventions: accept `req`, `res`, and `next`, and always call `next()` unless intentionally terminating the request. - Log only useful request metadata, such as method, URL, status code, duration, or request IDs; avoid logging credentials, tokens, or sensitive body fields. - Register the middleware through `MiddlewareConsumer` in a module implementing `NestModule`. - Use route filters such as `forRoutes('*')`, controllers, or route patterns to control where logging is applied. - Avoid blocking I/O or expensive synchronous work inside `use()`, since middleware runs on every matching request. # OPTIONAL_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L13) ## Definition ```ts 'optional:paramtypes' ``` ## Value ```ts 'optional:paramtypes' ``` # 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) `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] # 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) 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 NestJS applications. It extracts the `files` object populated by Multer middleware and injects it into the decorated controller parameter, typically when handling multiple uploaded files or named file fields. ## Signature ```ts function UploadedFiles(pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[HTTP multipart/form-data request] --> Multer[Multer middleware] Multer --> Files[req.files] Files --> Decorator["@UploadedFiles()"] Decorator --> Handler[Controller handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFiles, UseInterceptors, } from '@nestjs/common'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors( FileFieldsInterceptor([ { name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: 5 }, ]), ) uploadFiles( @UploadedFiles() files: { avatar?: Express.Multer.File[]; documents?: Express.Multer.File[]; }, ) { return { avatar: files.avatar?.[0]?.filename, documentCount: files.documents?.length ?? 0, }; } } ``` ## AI Coding Instructions - Use `@UploadedFiles()` only with a Multer-compatible interceptor or middleware that populates `req.files`, such as `FileFieldsInterceptor` or `AnyFilesInterceptor`. - Prefer explicit TypeScript types for named file fields so controllers safely handle optional or repeated uploads. - Use `@UploadedFile()` instead when the endpoint accepts a single file rather than a `files` collection. - Validate file size, MIME type, and storage configuration in the associated Multer interceptor or upload middleware. - Handle missing fields defensively because optional multipart file fields may not be present in the injected object. # CatsModule **Kind:** Module **Source:** [`sample/12-graphql-schema-first/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.module.ts#L7) ## Relationships - MODULE_IMPORTS β†’ `OwnersModule` - MODULE_PROVIDES β†’ `catsservice` - MODULE_PROVIDES β†’ `CatsResolver` - MODULE_PROVIDES β†’ `CatOwnerResolver` # FilterByMetadataKey **Kind:** Interface **Source:** [`packages/core/discovery/discovery-service.ts`](https://github.com/nestjs/nest/blob/master/packages/core/discovery/discovery-service.ts#L26) `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. # getTest **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L20) ## Endpoint `GET /test` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # LoggerMiddleware **Kind:** Service **Source:** [`sample/10-fastify/src/common/middleware/logger.middleware.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/common/middleware/logger.middleware.ts#L3) `LoggerMiddleware` is a NestJS middleware responsible for logging incoming HTTP requests before they reach route handlers. It integrates into the Fastify-based application request pipeline and should forward control to the next middleware or controller after logging request details. ## Methods | Method | Signature | Returns | |---|---|---| | `use` | `use(req: any, res: any, next: () => void)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant LoggerMiddleware participant Controller Client->>LoggerMiddleware: HTTP request LoggerMiddleware->>LoggerMiddleware: Log request metadata LoggerMiddleware->>Controller: next() Controller-->>Client: HTTP response ``` ## Usage ```ts import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './common/middleware/logger.middleware'; import { AppController } from './app.controller'; @Module({ controllers: [AppController], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('*'); } } ``` ## AI Coding Instructions - Keep `use()` non-blocking and always call `next()` so requests continue through the NestJS pipeline. - Log useful request metadata such as HTTP method, URL, request ID, and response timing without exposing sensitive headers or body data. - Register the middleware through `configure()` in a module implementing `NestModule`. - Ensure Fastify-compatible request and response types are used when adding type annotations. - Avoid placing authorization or business logic in this middleware; keep it focused on cross-cutting request logging. # OPTIONAL_PROPERTY_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L15) ## Definition ```ts 'optional:properties_metadata' ``` ## Value ```ts 'optional:properties_metadata' ``` # PostsResolvers **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/posts/posts.resolvers.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/posts.resolvers.ts#L8) `PostsResolvers` exposes the GraphQL API for managing `Post` records in the Prisma-backed posts module. It provides query resolvers for reading posts, mutation resolvers for creating, updating, and deleting posts, and a subscription resolver for receiving post creation events. ## Methods | Method | Signature | Returns | |---|---|---| | `posts` | `posts()` | `Promise` | | `post` | `post(args: string)` | `Promise` | | `create` | `create(args: NewPost)` | `Promise` | | `update` | `update(args: UpdatePost)` | `Promise` | | `delete` | `delete(args: string)` | `Promise` | | `postCreated` | `postCreated()` | `void` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[PostsResolvers] Resolver --> Queries[posts / post] Resolver --> Mutations[create / update / delete] Resolver --> Subscription[postCreated] Queries --> Prisma[Prisma Client] Mutations --> Prisma Mutations --> PubSub[PubSub Event Publisher] PubSub --> Subscription Subscription --> Client ``` ## Usage ```graphql query GetPosts { posts { id title content } } mutation CreatePost { create( data: { title: "Introducing GraphQL" content: "A post created through the API." } ) { id title content } } subscription OnPostCreated { postCreated { id title content } } ``` ## AI Coding Instructions - Keep resolver methods thin: delegate database operations to Prisma or the posts service rather than embedding business logic in GraphQL resolvers. - Ensure GraphQL return types and input types remain aligned with the Prisma `Post` model and schema definitions. - Publish the expected event after successful post creation so `postCreated` subscribers receive new records. - Handle missing post IDs consistently in `post`, `update`, and `delete`; avoid returning invalid or partially populated records. - Update the GraphQL schema and generated types when adding fields or changing resolver method arguments. ## Referenced By - `PostsModule` (MODULE_PROVIDES) # 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) 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 NestJS applications. It extracts the `files` object populated by Multer middleware and injects it into the decorated controller parameter, typically when handling multiple uploaded files or named file fields. ## Signature ```ts function UploadedFiles(pipes: (Type | PipeTransform)[]): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `pipes` | `(Type | PipeTransform)[]` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR Client[HTTP multipart/form-data request] --> Multer[Multer middleware] Multer --> Files[req.files] Files --> Decorator["@UploadedFiles()"] Decorator --> Handler[Controller handler parameter] ``` ## Usage ```typescript import { Controller, Post, UploadedFiles, UseInterceptors, } from '@nestjs/common'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; @Controller('uploads') export class UploadController { @Post() @UseInterceptors( FileFieldsInterceptor([ { name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: 5 }, ]), ) uploadFiles( @UploadedFiles() files: { avatar?: Express.Multer.File[]; documents?: Express.Multer.File[]; }, ) { return { avatar: files.avatar?.[0]?.filename, documentCount: files.documents?.length ?? 0, }; } } ``` ## AI Coding Instructions - Use `@UploadedFiles()` only with a Multer-compatible interceptor or middleware that populates `req.files`, such as `FileFieldsInterceptor` or `AnyFilesInterceptor`. - Prefer explicit TypeScript types for named file fields so controllers safely handle optional or repeated uploads. - Use `@UploadedFile()` instead when the endpoint accepts a single file rather than a `files` collection. - Validate file size, MIME type, and storage configuration in the associated Multer interceptor or upload middleware. - Handle missing fields defensively because optional multipart file fields may not be present in the injected object. # CatsModule **Kind:** Module **Source:** [`sample/36-hmr-esm/src/cats/cats.module.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/cats.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `catscontroller` - MODULE_PROVIDES β†’ `catsservice` # greeting **Kind:** API Endpoint **Source:** [`integration/inspector/src/circular-hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/hello.controller.ts#L24) ## Endpoint `GET /hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) `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. # InjectorDependency **Kind:** Type **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L51) 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. # LoggerMiddleware **Kind:** Service **Source:** [`sample/36-hmr-esm/src/common/middleware/logger.middleware.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/middleware/logger.middleware.ts#L3) `LoggerMiddleware` is a NestJS middleware service that intercepts incoming HTTP requests before they reach route handlers. Its responsibility is to record request informationβ€”such as the HTTP method and URLβ€”while passing control to the next middleware or controller in the pipeline. ## Methods | Method | Signature | Returns | |---|---|---| | `use` | `use(req: any, res: any, next: () => void)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant App as NestJS Application participant Logger as LoggerMiddleware participant Controller Client->>App: HTTP request App->>Logger: use(req, res, next) Logger->>Logger: Log request details Logger->>Controller: next() Controller-->>Client: HTTP response ``` ## Usage ```ts import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './common/middleware/logger.middleware'; import { AppController } from './app.controller'; @Module({ controllers: [AppController], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .forRoutes('*'); } } ``` ## AI Coding Instructions - Keep `use()` compatible with NestJS middleware signatures: `(req, res, next) => void`. - Always call `next()` after logging; omitting it prevents the request from reaching controllers. - Register the middleware through a module's `configure()` method and `MiddlewareConsumer`. - Avoid logging sensitive request data such as authorization headers, cookies, passwords, or full request bodies. - Prefer structured, concise request logs that include useful fields such as method, path, status code, and duration. # 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) 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. # RpcProxy **Kind:** Class **Source:** [`packages/microservices/context/rpc-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-proxy.ts#L6) `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] # 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) ## Signature ```ts function validateModuleKeys(keys: string[]) ``` ## Parameters | Name | Type | |---|---| | `keys` | `string[]` | # addLeadingSlash **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L26) ## Signature ```ts function addLeadingSlash(path: string): string ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string` # CircularModule **Kind:** Module **Source:** [`integration/injector/src/circular-modules/circular.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-modules/circular.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `circularservice` - MODULE_EXPORTS β†’ `circularservice` # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/circular-hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/hello.controller.ts#L24) ## Endpoint `GET /hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) `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. # ISocketFactory **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L83) ## Definition ```ts (args: ISocketFactoryArgs) => net.Socket ``` # LoggingInterceptor **Kind:** Service **Source:** [`integration/inspector/src/request-chain/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS interceptor that observes incoming request handling and logs details around the execution lifecycle. It fits into the request chain by wrapping controller or route handler execution, allowing logging of request metadata, responses, errors, and timing without changing business logic. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Dependencies - `HelperService` ## Where it refuses work - `LoggingInterceptor` stops the work with `Error` when `!this.helperSvc.request` β€” β€œerror”. ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant LoggingInterceptor participant Handler as Controller/Route Handler participant Logger Client->>NestJS: HTTP request NestJS->>LoggingInterceptor: intercept(context, next) LoggingInterceptor->>Logger: Log request metadata LoggingInterceptor->>Handler: next.handle() Handler-->>LoggingInterceptor: Observable response LoggingInterceptor->>Logger: Log response/timing LoggingInterceptor-->>NestJS: Return response Observable NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './request-chain/interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(LoggingInterceptor) export class HealthController { @Get() check() { return { status: 'ok', timestamp: new Date().toISOString(), }; } } ``` Register it globally when request logging should apply to every route: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggingInterceptor } from './request-chain/interceptors/logging.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new LoggingInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Preserve the NestJS interceptor contract: `intercept()` must return the `Observable` from `next.handle()` or a transformed version of it. - Use RxJS operators such as `tap`, `catchError`, and `finalize` for logging; avoid eagerly subscribing inside the interceptor. - Keep logging side-effect-only so response payloads, status codes, and exception behavior remain unchanged. - Avoid logging sensitive request data such as authorization headers, cookies, passwords, tokens, or full personal data payloads. - Ensure the interceptor is registered at the intended scope: global for all requests, controller-level for a feature area, or handler-level for a specific endpoint. ## Relationships - DEPENDS_ON β†’ `helperservice` # 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) ``` # SocketServerProvider **Kind:** Class **Source:** [`packages/websockets/socket-server-provider.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/socket-server-provider.ts#L8) `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] # CircularModule **Kind:** Module **Source:** [`integration/inspector/src/circular-modules/circular.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-modules/circular.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `circularservice` - MODULE_EXPORTS β†’ `circularservice` # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/circular-transient/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/hello.controller.ts#L24) ## Endpoint `GET /hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) 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. # 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) `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. # KafkaMessage **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L738) ## Definition ```ts MessageSetEntry | RecordBatchEntry ``` # LoggingInterceptor **Kind:** Service **Source:** [`integration/scopes/src/request-chain/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS request-chain interceptor responsible for observing incoming request handling and logging relevant execution details. It wraps the downstream handler as an RxJS `Observable`, allowing it to capture information before and after controller execution without changing the response payload. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Dependencies - `HelperService` ## Where it refuses work - `LoggingInterceptor` stops the work with `Error` when `!this.helperSvc.request` β€” β€œerror”. ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Logger as LoggingInterceptor participant Handler as Controller/Route Handler Client->>Nest: HTTP request Nest->>Logger: intercept(context, next) Logger->>Logger: Log request metadata Logger->>Handler: next.handle() Handler-->>Logger: Observable response/error Logger->>Logger: Log completion, timing, or errors Logger-->>Nest: Return Observable Nest-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './request-chain/interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(LoggingInterceptor) export class HealthController { @Get() getHealth() { return { status: 'ok' }; } } ``` Register it globally when request logging should apply to all routes: ```ts import { APP_INTERCEPTOR } from '@nestjs/core'; import { LoggingInterceptor } from './request-chain/interceptors/logging.interceptor'; export const loggingInterceptorProvider = { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor, }; ``` ## AI Coding Instructions - Preserve the NestJS interceptor contract: `intercept()` must return the `Observable` produced by `next.handle()` or a correctly transformed version of it. - Use RxJS operators such as `tap`, `catchError`, and `finalize` for logging side effects; do not eagerly subscribe inside the interceptor. - Read request-specific metadata through `ExecutionContext`, typically via `context.switchToHttp().getRequest()`. - Avoid logging sensitive values such as authorization headers, cookies, tokens, passwords, or unredacted request bodies. - Keep logging non-blocking and resilient so logging failures do not prevent the underlying controller handler from completing. ## Relationships - DEPENDS_ON β†’ `helperservice` # PARAM_ARGS_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L39) ## Definition ```ts ROUTE_ARGS_METADATA ``` ## Value ```ts ROUTE_ARGS_METADATA ``` # WsProxy **Kind:** Class **Source:** [`packages/websockets/context/ws-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/context/ws-proxy.ts#L6) `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. # CatsResolver **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/cats/cats.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cats.resolver.ts#L11) `CatsResolver` is the GraphQL resolver for cat-related queries, mutations, and subscription events in the schema-first sample. It coordinates requests with the cats service, exposing operations to list cats, fetch a cat by ID, create a cat, and publish cat creation notifications. ## Methods | Method | Signature | Returns | |---|---|---| | `getCats` | `getCats()` | `void` | | `findOneById` | `findOneById(id: number)` | `Promise` | | `create` | `create(args: CreateCatDto)` | `Promise` | | `catCreated` | `catCreated()` | `void` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[CatsResolver] Resolver --> Service[CatsService] Service --> Store[Cat Data Store] Resolver --> Query[getCats / findOneById] Resolver --> Mutation[create] Mutation --> Publisher[PubSub Publisher] Publisher --> Subscription[catCreated Subscription] Subscription --> Client ``` ## Usage ```ts import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql'; import { CatsService } from './cats.service'; import { Cat } from './models/cat.model'; import { CreateCatInput } from './dto/create-cat.input'; @Resolver('Cat') export class CatsResolver { constructor(private readonly catsService: CatsService) {} @Query('cats') getCats(): Cat[] { return this.catsService.findAll(); } @Query('cat') findOneById(@Args('id') id: string): Promise { return this.catsService.findOneById(id); } @Mutation('createCat') async create(@Args('createCatInput') input: CreateCatInput): Promise { const cat = await this.catsService.create(input); // Publish the created cat for catCreated subscribers. return cat; } @Subscription('catCreated') catCreated() { // Return the configured async iterator for cat creation events. } } ``` ## AI Coding Instructions - Keep GraphQL operation names, argument names, and return types aligned with the schema-first `.graphql` definitions. - Delegate persistence and business logic to `CatsService`; resolvers should primarily map GraphQL requests to service calls. - Preserve `Promise` return types for asynchronous lookup and creation operations. - When adding mutations that should notify clients, publish the event through the configured PubSub integration and expose a matching subscription resolver. - Validate input DTOs before passing data to the service, and ensure subscription payload field names match the GraphQL subscription schema. ## Referenced By - `CatsModule` (MODULE_PROVIDES) # CircularModule **Kind:** Module **Source:** [`integration/injector/src/circular/circular.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular/circular.module.ts#L5) ## Relationships - MODULE_PROVIDES β†’ `circularservice` - MODULE_PROVIDES β†’ `inputservice` # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/circular-transient/test.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/test.controller.ts#L14) ## Endpoint `GET /test` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `TestController` (MODULE_DECLARES) # InstancePerContext **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L42) `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. # 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) ## Signature ```ts function isValueProvider(provider: Provider): provider is ValueProvider ``` ## Parameters | Name | Type | |---|---| | `provider` | `Provider` | **Returns:** `provider is ValueProvider` # LegacyPartitioner **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L137) ## Definition ```ts ICustomPartitioner ``` # LoggingInterceptor **Kind:** Service **Source:** [`integration/inspector/src/core/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/core/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS interceptor that wraps request handling to capture and log information about incoming requests, responses, and execution timing. It integrates into NestJS’s interceptor pipeline, allowing cross-cutting logging behavior without adding logging code to individual controllers or handlers. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant LoggingInterceptor participant Controller Client->>NestJS: HTTP Request NestJS->>LoggingInterceptor: intercept(context, next) LoggingInterceptor->>LoggingInterceptor: Record request metadata/start time LoggingInterceptor->>Controller: next.handle() Controller-->>LoggingInterceptor: Observable response LoggingInterceptor->>LoggingInterceptor: Log response or error details LoggingInterceptor-->>NestJS: Return Observable NestJS-->>Client: HTTP Response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(LoggingInterceptor) export class HealthController { @Get() check() { return { status: 'ok', timestamp: new Date().toISOString(), }; } } ``` Register it globally when request logging should apply to every route: ```ts import { APP_INTERCEPTOR } from '@nestjs/core'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; providers: [ { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor, }, ]; ``` ## AI Coding Instructions - Keep `intercept()` non-blocking: return the `next.handle()` observable and use RxJS operators such as `tap`, `catchError`, or `finalize` for logging. - Read request-specific metadata through `ExecutionContext`, including HTTP method, URL, controller, and handler name. - Avoid logging sensitive values such as authorization headers, cookies, access tokens, passwords, or unredacted request bodies. - Preserve the original response and error behavior; logging must not alter emitted values or swallow exceptions. - Prefer global interceptor registration with `APP_INTERCEPTOR` for consistent backend request logging across controllers. # PARAM_ARGS_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L10) ## Definition ```ts ROUTE_ARGS_METADATA ``` ## Value ```ts ROUTE_ARGS_METADATA ``` # CatsResolvers **Kind:** Class **Source:** [`integration/graphql-schema-first/src/cats/cats.resolvers.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/cats.resolvers.ts#L10) `CatsResolvers` implements the GraphQL resolver layer for cat-related operations in the schema-first integration example. It provides query and mutation handlers for listing cats, retrieving a cat by ID, creating cats, and publishing or resolving the `catCreated` event flow. ## Methods | Method | Signature | Returns | |---|---|---| | `getCats` | `getCats()` | `void` | | `findOneById` | `findOneById(id: number)` | `Promise` | | `create` | `create(args: Cat)` | `Promise` | | `catCreated` | `catCreated()` | `void` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Schema[GraphQL Schema] Schema --> Resolvers[CatsResolvers] Resolvers --> GetCats[getCats] Resolvers --> FindOne[findOneById] Resolvers --> Create[create] Resolvers --> Created[catCreated] GetCats --> CatsService[Cats Service / Data Source] FindOne --> CatsService Create --> CatsService Create --> PubSub[PubSub Event Publisher] PubSub --> Created ``` ## Usage ```ts import { CatsResolvers } from './cats/cats.resolvers'; import { CatsService } from './cats/cats.service'; import { PubSub } from 'graphql-subscriptions'; const catsService = new CatsService(); const pubSub = new PubSub(); const resolvers = new CatsResolvers(catsService, pubSub); // Example query resolver usage const cats = resolvers.getCats(); // Example mutation resolver usage const createdCat = await resolvers.create({ name: 'Milo', age: 2, breed: 'Tabby', }); // Example lookup resolver usage const cat = await resolvers.findOneById('cat-id'); ``` ## AI Coding Instructions - Keep resolver methods thin: delegate persistence and business logic to the cats service or injected data layer. - Ensure resolver method names and argument shapes match the schema-first GraphQL definitions exactly. - Return `Promise` from asynchronous lookup and creation operations; do not expose database-specific entities directly. - Publish the `catCreated` event only after a cat has been successfully created. - Handle missing cat IDs consistently with the GraphQL schema's expected nullable or error behavior. ## Referenced By - `CatsModule` (MODULE_PROVIDES) # CircularPropertiesModule **Kind:** Module **Source:** [`integration/injector/src/circular-properties/circular-properties.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-properties/circular-properties.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `circularservice` - MODULE_EXPORTS β†’ `circularservice` # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/hello.controller.ts#L24) ## Endpoint `GET /hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `HelloController` (MODULE_DECLARES) # InstrumentationEvent **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L397) `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. # logCreator **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L639) ## Definition ```ts (logLevel: logLevel) => (entry: LogEntry) => void ``` # LoggingInterceptor **Kind:** Service **Source:** [`sample/01-cats-app/src/core/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/core/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS interceptor that observes incoming request handling and logs information before and after a route handler executes. It fits into the application's cross-cutting infrastructure layer, allowing request timing, response details, or errors to be monitored without changing individual controllers. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Interceptor as LoggingInterceptor participant Controller participant Service Client->>Nest: HTTP request Nest->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Log request metadata Interceptor->>Controller: next.handle() Controller->>Service: Execute application logic Service-->>Controller: Return result Controller-->>Interceptor: Observable response Interceptor->>Interceptor: Log completion / duration Interceptor-->>Nest: Return response Observable Nest-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; @Controller('cats') @UseInterceptors(LoggingInterceptor) export class CatsController { @Get() findAll() { return [{ id: 1, name: 'Milo' }]; } } ``` Register it globally when logging should apply to every request: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new LoggingInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Preserve the interceptor contract: `intercept()` must return the `Observable` from `next.handle()`, optionally transformed with RxJS operators. - Use `ExecutionContext` to obtain request-specific metadata such as the HTTP method, URL, controller, or handler name. - Avoid subscribing to `next.handle()` inside the interceptor; use operators such as `tap`, `map`, `catchError`, or `finalize` instead. - Register the interceptor at the appropriate scope: method, controller, module provider, or globally through `useGlobalInterceptors`. - Do not log sensitive request data, including authorization headers, passwords, tokens, or personally identifiable information. # 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) ## Signature ```ts function mixin(mixinClass: Type) ``` ## Parameters | Name | Type | |---|---| | `mixinClass` | `Type` | # PARAMTYPES_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L11) ## Definition ```ts 'design:paramtypes' ``` ## Value ```ts 'design:paramtypes' ``` # ChatGateway **Kind:** Class **Source:** [`integration/inspector/src/chat/chat.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/chat/chat.gateway.ts#L10) `ChatGateway` provides the real-time chat interface for the inspector integration. It exposes create, read, update, and delete operations over the gateway layer, coordinating client requests and broadcasting or returning chat data to connected consumers. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createChatDto: CreateChatDto)` | `void` | | `findAll` | `findAll()` | `void` | | `findOne` | `findOne(id: number)` | `void` | | `update` | `update(updateChatDto: UpdateChatDto)` | `void` | | `remove` | `remove(id: number)` | `void` | ## Diagram ```mermaid graph LR Client[Chat Client] -->|create / find / update / remove events| Gateway[ChatGateway] Gateway -->|CRUD operations| Service[Chat Service / Data Layer] Service -->|Chat data| Gateway Gateway -->|responses / updates| Client ``` ## Usage ```ts import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); // Create a chat message or chat resource. socket.emit('createChat', { content: 'Hello from the inspector', userId: 'user-123', }); // Retrieve all chat records. socket.emit('findAllChat', {}, (chats) => { console.log('Chats:', chats); }); // Retrieve one chat record. socket.emit('findOneChat', { id: 'chat-123' }, (chat) => { console.log('Chat:', chat); }); // Update a chat record. socket.emit('updateChat', { id: 'chat-123', content: 'Updated message', }); // Remove a chat record. socket.emit('removeChat', { id: 'chat-123' }); ``` ## AI Coding Instructions - Keep gateway handlers focused on transport concerns; delegate validation, persistence, and business rules to the chat service or data layer. - Preserve the existing event naming and payload conventions when adding or changing `create`, `findAll`, `findOne`, `update`, or `remove` behavior. - Validate client-provided identifiers and payloads before performing update or delete operations. - Return consistent response shapes and propagate gateway-safe errors so connected clients can handle failures predictably. - Consider authorization and room/client targeting before broadcasting chat updates to other connected users. ## Referenced By - `ChatModule` (MODULE_PROVIDES) # ConfigModule **Kind:** Module **Source:** [`integration/graphql-schema-first/src/config.module.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/config.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `configservice` - MODULE_EXPORTS β†’ `configservice` # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/transient/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/hello.controller.ts#L24) ## Endpoint `GET /hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) `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. # LoggingInterceptor **Kind:** Service **Source:** [`sample/03-microservices/src/common/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/common/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS interceptor that wraps request handling to capture and log execution details around controller or route-handler calls. It integrates with NestJS's interceptor pipeline, allowing cross-cutting logging behavior without adding logging code to every endpoint. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant LoggingInterceptor participant Controller participant Logger Client->>NestJS: HTTP request NestJS->>LoggingInterceptor: intercept(context, next) LoggingInterceptor->>Logger: Log request/start details LoggingInterceptor->>Controller: next.handle() Controller-->>LoggingInterceptor: Observable response LoggingInterceptor->>Logger: Log completion/error details LoggingInterceptor-->>NestJS: Return Observable NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './common/interceptors/logging.interceptor'; @Controller('users') @UseInterceptors(LoggingInterceptor) export class UsersController { @Get() findAll() { return [{ id: 1, name: 'Ada Lovelace' }]; } } ``` To apply it globally: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggingInterceptor } from './common/interceptors/logging.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new LoggingInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Preserve the `intercept(context, next): Observable` contract and always return the observable from `next.handle()`. - Use RxJS operators such as `tap`, `catchError`, or `finalize` for logging completion and error events without consuming the response stream. - Avoid logging sensitive request data, including authorization headers, passwords, tokens, and personally identifiable information. - Register the interceptor with `@UseInterceptors()` for targeted routes/controllers or globally through NestJS application configuration. - Keep logging non-blocking and lightweight so interceptor work does not noticeably increase request latency. # LogLevel **Kind:** Type **Source:** [`packages/common/services/logger.service.ts`](https://github.com/nestjs/nest/blob/master/packages/common/services/logger.service.ts#L18) ## Definition ```ts (typeof LOG_LEVELS)[number] ``` # normalizePath **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L33) ## Signature ```ts function normalizePath(path: string): string ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string` # PartitionAssigners **Kind:** Constant **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L594) ## Definition ```ts { roundRobin: PartitionAssigner } ``` # ConfigModule **Kind:** Module **Source:** [`integration/microservices/src/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.module.ts#L28) ## Relationships - MODULE_PROVIDES β†’ `ConfigService` - MODULE_EXPORTS β†’ `ConfigService` # 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) `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] # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/transient/test.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/test.controller.ts#L14) ## Endpoint `GET /test` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `unknown` | βœ“ | | ## Referenced By - `TestController` (MODULE_DECLARES) # ISocketFactoryArgs **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L76) `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. # LoggingInterceptor **Kind:** Service **Source:** [`sample/10-fastify/src/core/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/core/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS interceptor that wraps request handling to capture and log execution details around controller or route handler calls. It participates in the Fastify/Nest request pipeline, allowing cross-cutting logging behavior to be applied without duplicating logging code in individual handlers. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Fastify participant LoggingInterceptor participant Controller participant Handler Client->>Fastify: HTTP request Fastify->>LoggingInterceptor: intercept(context, next) LoggingInterceptor->>LoggingInterceptor: Log request/start metadata LoggingInterceptor->>Controller: next.handle() Controller->>Handler: Execute route handler Handler-->>LoggingInterceptor: Observable response LoggingInterceptor->>LoggingInterceptor: Log completion/error details LoggingInterceptor-->>Fastify: Response Observable Fastify-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(LoggingInterceptor) export class HealthController { @Get() check() { return { status: 'ok', timestamp: new Date().toISOString(), }; } } ``` Register it globally when request logging should apply to every route: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new LoggingInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Keep `intercept()` non-blocking: return the `next.handle()` observable and use RxJS operators such as `tap`, `catchError`, or `finalize` for logging. - Read request-specific values through `ExecutionContext.switchToHttp().getRequest()` so the interceptor remains compatible with NestJS request handling. - Avoid logging sensitive headers, authorization tokens, passwords, cookies, or full request bodies unless explicitly sanitized. - Register the interceptor globally for application-wide observability, or use `@UseInterceptors(LoggingInterceptor)` for controller- or route-specific logging. - Preserve errors by logging them and rethrowing them through the observable pipeline rather than swallowing or replacing the original exception. # MockFactory **Kind:** Type **Source:** [`packages/testing/interfaces/mock-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/interfaces/mock-factory.ts#L3) ## Definition ```ts (token?: InjectionToken) => any ``` # 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) 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. # UNDEFINED_FORWARDREF_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L148) ## Signature ```ts function UNDEFINED_FORWARDREF_MESSAGE(scope: Type[]) ``` ## Parameters | Name | Type | |---|---| | `scope` | `Type[]` | # ConfigModule **Kind:** Module **Source:** [`integration/microservices/src/tcp-tls/app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.module.ts#L39) ## Relationships - MODULE_PROVIDES β†’ `ConfigService` - MODULE_EXPORTS β†’ `ConfigService` # greeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.controller.ts#L10) ## Endpoint `GET /hello` ## Referenced By - `HelloController` (MODULE_DECLARES) # ITopicConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L266) `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. # Kafka **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L19) `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. # LoggingInterceptor **Kind:** Service **Source:** [`sample/36-hmr-esm/src/core/interceptors/logging.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/core/interceptors/logging.interceptor.ts#L10) `LoggingInterceptor` is a NestJS interceptor that wraps request handler execution to add logging around the request/response lifecycle. It fits into the application's interceptor pipeline, allowing cross-cutting logging behavior to be applied without modifying individual controllers or services. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS as NestJS Pipeline participant Interceptor as LoggingInterceptor participant Handler as Controller Handler Client->>NestJS: HTTP request NestJS->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Log incoming request Interceptor->>Handler: next.handle() Handler-->>Interceptor: Observable response Interceptor->>Interceptor: Log response or completion Interceptor-->>NestJS: Return Observable NestJS-->>Client: HTTP response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; @Controller('health') @UseInterceptors(LoggingInterceptor) export class HealthController { @Get() check() { return { status: 'ok' }; } } ``` To register it globally: ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggingInterceptor } from './core/interceptors/logging.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new LoggingInterceptor()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Preserve the interceptor contract: `intercept()` must return the `Observable` produced by `next.handle()` or a transformed version of it. - Use RxJS operators such as `tap`, `catchError`, or `finalize` for response, error, and completion logging rather than subscribing inside the interceptor. - Avoid logging sensitive request data, including authorization headers, cookies, passwords, and access tokens. - Apply this interceptor globally for consistent application-wide logging, or use `@UseInterceptors(LoggingInterceptor)` for targeted controller or route logging. - Keep logging non-blocking and avoid expensive serialization or synchronous I/O in the request pipeline. # MsFundamentalPattern **Kind:** Type **Source:** [`packages/microservices/interfaces/pattern.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern.interface.ts#L1) ## Definition ```ts string | number ``` # PATH_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L10) ## Definition ```ts 'path' ``` ## Value ```ts 'path' ``` # UNKNOWN_REQUEST_MAPPING **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L253) ## Signature ```ts function UNKNOWN_REQUEST_MAPPING(metatype: Type) ``` ## Parameters | Name | Type | |---|---| | `metatype` | `Type` | # ConfigModule **Kind:** Module **Source:** [`integration/mongoose/src/async-existing-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/async-existing-options.module.ts#L17) ## Relationships - MODULE_PROVIDES β†’ `configservice` - MODULE_EXPORTS β†’ `configservice` # CONTROLLER_MAPPING_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L28) ## Signature ```ts function CONTROLLER_MAPPING_MESSAGE(name: string, path: string) ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `path` | `string` | # greeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host/host.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.controller.ts#L13) ## Endpoint `GET /` ## Referenced By - `HostController` (MODULE_DECLARES) # KafkaJSErrorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1282) `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. # 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) `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. # MsPattern **Kind:** Type **Source:** [`packages/microservices/interfaces/pattern.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern.interface.ts#L7) ## Definition ```ts MsObjectPattern | MsFundamentalPattern ``` # ParseIntPipe **Kind:** Service **Source:** [`integration/inspector/src/common/pipes/parse-int.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/common/pipes/parse-int.pipe.ts#L8) `ParseIntPipe` is a NestJS pipe that transforms incoming request values into integers before they reach a controller handler. It is typically used for route parameters or query values that must be numeric, helping keep validation and conversion logic out of controllers. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ParseIntPipe` stops the work with `BadRequestException` when `isNaN(val)` β€” β€œValidation failed”. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as NestJS Controller participant Pipe as ParseIntPipe participant Handler as Route Handler Client->>Controller: Request with "id" = "42" Controller->>Pipe: transform("42") Pipe-->>Controller: 42 (number) Controller->>Handler: Invoke handler with parsed id Handler-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { ParseIntPipe } from '../common/pipes/parse-int.pipe'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id, message: `Fetching user ${id}`, }; } } ``` ## AI Coding Instructions - Apply `ParseIntPipe` to route parameters or query parameters that must be handled as integer values. - Keep parsing logic inside the pipe rather than using `parseInt()` repeatedly in controller methods. - Ensure invalid or non-numeric input is handled consistently with the application's NestJS error-handling conventions. - Preserve the `transform()` contract: accept the raw request value and return the converted numeric value. - Use this pipe alongside DTO validation when a parameter requires additional constraints beyond integer conversion. # PATTERN_EXTRAS_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L34) ## Definition ```ts 'microservices:pattern_extras' ``` ## Value ```ts 'microservices:pattern_extras' ``` # ConfigModule **Kind:** Module **Source:** [`integration/typeorm/src/async-existing-options.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/async-existing-options.module.ts#L27) ## Relationships - MODULE_PROVIDES β†’ `configservice` - MODULE_EXPORTS β†’ `configservice` # greeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host-array/host-array.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.controller.ts#L13) ## Endpoint `GET /` ## Referenced By - `HostArrayController` (MODULE_DECLARES) # 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) 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` is a route-handler parameter decorator that reads host parameters from the incoming request's `hosts` property. Use it to inject all host parameters or a single named host parameter into a controller method argument, optionally applying NestJS pipes for validation or transformation. ## Signature ```ts function HostParam(property: string | (Type | PipeTransform)): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.hosts] B --> C[HostParam decorator] C --> D{Parameter key provided?} D -->|No| E[Inject all host parameters] D -->|Yes| F[Inject named host parameter] E --> G[Optional pipes] F --> G G --> H[Route handler parameter] ``` ## Usage ```typescript import { Controller, Get, HostParam, ParseIntPipe } from '@nestjs/common'; @Controller() export class AccountsController { // Request host pattern example: :account.example.com @Get() findByHost(@HostParam('account') account: string) { return { account }; } @Get('details') findDetails(@HostParam() hosts: string[]) { return { hosts }; } @Get('numeric') findNumericHost( @HostParam('id', ParseIntPipe) id: number, ) { return { id }; } } ``` ## AI Coding Instructions - Use `@HostParam()` when the handler needs the complete `req.hosts` value, and `@HostParam('name')` when only one named host parameter is needed. - Ensure the controller or route configuration defines matching host parameter names before attempting to extract them. - Apply pipes as additional decorator arguments when host values require validation or type conversion. - Treat extracted host parameters as request-derived input; validate values before using them in authorization, database, or routing logic. # 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) `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. # 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) ## Definition ```ts MulterOptions ``` # ParseIntPipe **Kind:** Service **Source:** [`sample/01-cats-app/src/common/pipes/parse-int.pipe.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/pipes/parse-int.pipe.ts#L8) `ParseIntPipe` is a NestJS pipe that converts incoming route or request values into integers before they reach a controller handler. It validates that the value can be parsed as a number and rejects invalid input with an HTTP bad-request error, helping controllers receive correctly typed numeric parameters. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ParseIntPipe` stops the work with `BadRequestException` when `isNaN(val)` β€” β€œValidation failed”. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant ParseIntPipe participant Handler Client->>Controller: GET /cats/:id Controller->>ParseIntPipe: transform(id) alt Valid integer value ParseIntPipe-->>Controller: parsed number Controller->>Handler: handler(id: number) Handler-->>Client: Response else Invalid value ParseIntPipe-->>Controller: BadRequestException Controller-->>Client: 400 Bad Request end ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { ParseIntPipe } from '../common/pipes/parse-int.pipe'; @Controller('cats') export class CatsController { @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id }; } } ``` ## AI Coding Instructions - Apply `ParseIntPipe` to route parameters that must be numeric, such as IDs, page numbers, or limits. - Keep `transform()` focused on parsing and validation; do not place business logic or database lookups in the pipe. - Ensure invalid or non-numeric values produce a clear `BadRequestException` rather than reaching controller logic. - Prefer applying the pipe directly in decorators, such as `@Param('id', ParseIntPipe)`, to make input validation explicit. # PATTERN_HANDLER_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L37) ## Definition ```ts 'microservices:handler_type' ``` ## Value ```ts 'microservices:handler_type' ``` # PipesConsumer **Kind:** Class **Source:** [`packages/core/pipes/pipes-consumer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/pipes/pipes-consumer.ts#L5) `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] # CoreModule **Kind:** Module **Source:** [`sample/01-cats-app/src/core/core.module.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/core/core.module.ts#L6) # greeting **Kind:** API Endpoint **Source:** [`integration/inspector/src/request-chain/request-chain.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/request-chain.controller.ts#L9) ## Endpoint `GET /hello` ## Referenced By - `RequestChainController` (MODULE_DECLARES) # 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) 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` is a route-handler parameter decorator that reads host parameters from the incoming request's `hosts` property. Use it to inject all host parameters or a single named host parameter into a controller method argument, optionally applying NestJS pipes for validation or transformation. ## Signature ```ts function HostParam(property: string | (Type | PipeTransform)): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.hosts] B --> C[HostParam decorator] C --> D{Parameter key provided?} D -->|No| E[Inject all host parameters] D -->|Yes| F[Inject named host parameter] E --> G[Optional pipes] F --> G G --> H[Route handler parameter] ``` ## Usage ```typescript import { Controller, Get, HostParam, ParseIntPipe } from '@nestjs/common'; @Controller() export class AccountsController { // Request host pattern example: :account.example.com @Get() findByHost(@HostParam('account') account: string) { return { account }; } @Get('details') findDetails(@HostParam() hosts: string[]) { return { hosts }; } @Get('numeric') findNumericHost( @HostParam('id', ParseIntPipe) id: number, ) { return { id }; } } ``` ## AI Coding Instructions - Use `@HostParam()` when the handler needs the complete `req.hosts` value, and `@HostParam('name')` when only one named host parameter is needed. - Ensure the controller or route configuration defines matching host parameter names before attempting to extract them. - Apply pipes as additional decorator arguments when host values require validation or type conversion. - Treat extracted host parameters as request-derived input; validate values before using them in authorization, database, or routing logic. # LogEntry **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L626) `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. # 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) 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. # ParseIntPipe **Kind:** Service **Source:** [`sample/10-fastify/src/common/pipes/parse-int.pipe.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/common/pipes/parse-int.pipe.ts#L4) `ParseIntPipe` is a NestJS pipe that converts incoming request values into JavaScript integers before they reach a controller handler. It is typically used for route parameters or query values that arrive as strings, helping controllers receive validated numeric input consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ParseIntPipe` stops the work with `BadRequestException` when `isNaN(val)` β€” β€œValidation failed”. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as NestJS Controller participant Pipe as ParseIntPipe participant Handler as Route Handler Client->>Controller: GET /resources/42 Controller->>Pipe: transform("42") Pipe->>Pipe: Parse value as integer Pipe-->>Controller: 42 Controller->>Handler: Invoke handler with numeric ID Handler-->>Client: Return response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { ParseIntPipe } from '../common/pipes/parse-int.pipe'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { // `id` is transformed from a route string to a number. return { id }; } } ``` ## AI Coding Instructions - Apply `ParseIntPipe` to route parameters and query parameters that must be handled as integers. - Keep `transform()` focused on conversion and validation; controller methods should receive already-normalized values. - Ensure invalid numeric input produces an appropriate NestJS HTTP exception rather than silently passing `NaN`. - Use the pipe consistently across controllers to avoid duplicating `parseInt()` logic in route handlers. # PATTERN_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L33) ## Definition ```ts 'microservices:pattern' ``` ## Value ```ts 'microservices:pattern' ``` # RouterModule **Kind:** Class **Source:** [`packages/core/router/router-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-module.ts#L19) `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) # CoreModule **Kind:** Module **Source:** [`sample/10-fastify/src/core/core.module.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/core/core.module.ts#L6) # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/request-chain/request-chain.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/request-chain.controller.ts#L9) ## Endpoint `GET /hello` ## Referenced By - `RequestChainController` (MODULE_DECLARES) # 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) 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` is a route-handler parameter decorator that reads host parameters from the incoming request's `hosts` property. Use it to inject all host parameters or a single named host parameter into a controller method argument, optionally applying NestJS pipes for validation or transformation. ## Signature ```ts function HostParam(property: string | (Type | PipeTransform)): ParameterDecorator ``` ## Parameters | Name | Type | |---|---| | `property` | `string | (Type | PipeTransform)` | **Returns:** `ParameterDecorator` ## Diagram ```mermaid graph LR A[Incoming HTTP Request] --> B[req.hosts] B --> C[HostParam decorator] C --> D{Parameter key provided?} D -->|No| E[Inject all host parameters] D -->|Yes| F[Inject named host parameter] E --> G[Optional pipes] F --> G G --> H[Route handler parameter] ``` ## Usage ```typescript import { Controller, Get, HostParam, ParseIntPipe } from '@nestjs/common'; @Controller() export class AccountsController { // Request host pattern example: :account.example.com @Get() findByHost(@HostParam('account') account: string) { return { account }; } @Get('details') findDetails(@HostParam() hosts: string[]) { return { hosts }; } @Get('numeric') findNumericHost( @HostParam('id', ParseIntPipe) id: number, ) { return { id }; } } ``` ## AI Coding Instructions - Use `@HostParam()` when the handler needs the complete `req.hosts` value, and `@HostParam('name')` when only one named host parameter is needed. - Ensure the controller or route configuration defines matching host parameter names before attempting to extract them. - Apply pipes as additional decorator arguments when host values require validation or type conversion. - Treat extracted host parameters as request-derived input; validate values before using them in authorization, database, or routing logic. # Message **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L121) `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. # 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) ## Definition ```ts NestApplicationContextOptions ``` # ParseIntPipe **Kind:** Service **Source:** [`sample/36-hmr-esm/src/common/pipes/parse-int.pipe.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/pipes/parse-int.pipe.ts#L8) `ParseIntPipe` is a NestJS pipe that transforms incoming request values into integers before they reach a controller handler. It is typically used for route parameters, query parameters, or payload fields that must be numeric, and should reject invalid numeric input with an appropriate HTTP error. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Where it refuses work - `ParseIntPipe` stops the work with `BadRequestException` when `isNaN(val)` β€” β€œValidation failed”. ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant ParseIntPipe participant Handler Client->>Controller: GET /resources/:id Controller->>ParseIntPipe: transform("42") ParseIntPipe-->>Controller: 42 (number) Controller->>Handler: handler(id: 42) Handler-->>Client: Response Note over ParseIntPipe: Invalid input should throw
a validation error ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { ParseIntPipe } from './common/pipes/parse-int.pipe'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return { id, message: `Loading user ${id}`, }; } } ``` ## AI Coding Instructions - Apply `ParseIntPipe` at controller boundaries, especially for route and query parameters that must be integers. - Ensure `transform()` returns a numeric value for valid input and throws a NestJS-compatible HTTP exception for invalid values. - Avoid relying on JavaScript's permissive parsing alone; reject values such as non-numeric strings or partially numeric input when strict validation is required. - Keep pipe logic focused on conversion and validation; delegate business rules such as resource existence checks to services or guards. # PIPES_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L22) ## Definition ```ts '__pipes__' ``` ## Value ```ts '__pipes__' ``` # RpcException **Kind:** Class **Source:** [`packages/microservices/exceptions/rpc-exception.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/exceptions/rpc-exception.ts#L6) `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. # CoreModule **Kind:** Module **Source:** [`sample/36-hmr-esm/src/core/core.module.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/core/core.module.ts#L6) # greeting **Kind:** API Endpoint **Source:** [`integration/inspector/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/durable/durable.controller.ts#L8) ## Endpoint `GET /durable` ## Referenced By - `DurableController` (MODULE_DECLARES) # INVALID_CLASS_MESSAGE **Kind:** Function **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L242) ## Signature ```ts function INVALID_CLASS_MESSAGE(text: TemplateStringsArray, value: any) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `value` | `any` | # 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) `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. # OutgoingEvent **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L19) ## Definition ```ts ReadPacket ``` # PassthroughInterceptor **Kind:** Service **Source:** [`integration/nest-application/sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/src/app.controller.ts#L28) `PassthroughInterceptor` is a NestJS interceptor that receives a request handler’s observable response stream and returns it without modifying the emitted values. It is typically used in the SSE integration application to preserve streaming behavior while providing a standard interceptor extension point for future cross-cutting concerns. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(_context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Interceptor as PassthroughInterceptor participant Controller participant Stream as Observable Stream Client->>Nest: HTTP/SSE request Nest->>Interceptor: intercept(context, next) Interceptor->>Controller: next.handle() Controller-->>Stream: Return Observable Stream-->>Interceptor: Emit response events Interceptor-->>Nest: Return unchanged Observable Nest-->>Client: Stream response events ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Observable, interval, map } from 'rxjs'; import { PassthroughInterceptor } from './app.controller'; @Controller('events') @UseInterceptors(PassthroughInterceptor) export class EventsController { @Get() streamEvents(): Observable<{ data: string }> { return interval(1000).pipe( map((count) => ({ data: `Event ${count}`, })), ); } } ``` ## AI Coding Instructions - Return `next.handle()` directly when the interceptor must preserve the original observable and SSE event flow. - Do not eagerly subscribe to the observable inside `intercept()`; NestJS manages subscription and response delivery. - Add RxJS operators such as `tap`, `map`, or `catchError` only when intentionally adding logging, transformation, or error handling. - Ensure interceptor usage is compatible with streaming endpoints; avoid buffering or converting observable streams to promises. - Apply the interceptor with `@UseInterceptors()` at the route, controller, or global application level as appropriate. # port **Kind:** Constant **Source:** [`integration/nest-application/get-url/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/e2e/utils.ts#L3) ## Definition ```ts number ``` # WsException **Kind:** Class **Source:** [`packages/websockets/errors/ws-exception.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/errors/ws-exception.ts#L3) `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] # ApplicationGateway **Kind:** Class **Source:** [`integration/websockets/src/app.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/app.gateway.ts#L12) `ApplicationGateway` provides the WebSocket-facing behavior for the integration application. It handles push-oriented interactions and exposes paths that verify successful and error responses when clients communicate with the gateway. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(data: undefined)` | `void` | | `getPathCalled` | `getPathCalled(client: undefined, data: undefined)` | `void` | | `getPathCalledWithError` | `getPathCalledWithError()` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] --> Gateway[ApplicationGateway] Gateway --> Push[onPush()] Gateway --> Success[getPathCalled()] Gateway --> Error[getPathCalledWithError()] Success --> Response[Successful response] Error --> Failure[Error response] ``` ## Usage ```ts import { ApplicationGateway } from './app.gateway'; // In a NestJS module, register the gateway as a provider. @Module({ providers: [ApplicationGateway], }) export class AppModule {} // The gateway methods are invoked by the configured WebSocket transport // when clients send messages to their associated routes/events. ``` ## AI Coding Instructions - Keep WebSocket message handling inside `ApplicationGateway`; avoid placing transport-specific logic in unrelated services. - Preserve the distinction between `getPathCalled()` success behavior and `getPathCalledWithError()` error behavior for integration coverage. - Update the corresponding client event/path configuration when changing gateway handler names or routes. - Ensure errors thrown or returned by gateway handlers are compatible with the configured WebSocket adapter and test expectations. ## Referenced By - `ApplicationModule` (MODULE_PROVIDES) # DatabaseModule **Kind:** Module **Source:** [`integration/inspector/src/database/database.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `DatabaseController` - MODULE_PROVIDES β†’ `DatabaseService` # greeting **Kind:** API Endpoint **Source:** [`integration/scopes/src/durable/durable.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable.controller.ts#L12) ## Endpoint `GET /durable` ## Referenced By - `DurableController` (MODULE_DECLARES) # 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) ## Signature ```ts function isClassProvider(provider: Provider): provider is ClassProvider ``` ## Parameters | Name | Type | |---|---| | `provider` | `Provider` | **Returns:** `provider is ClassProvider` # MessageMappingProperties **Kind:** Interface **Source:** [`packages/websockets/gateway-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/gateway-metadata-explorer.ts#L15) `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`. # OutgoingRequest **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L17) ## Definition ```ts ReadPacket & PacketId ``` # PhotoService **Kind:** Service **Source:** [`sample/13-mongo-typeorm/src/photo/photo.service.ts`](https://github.com/nestjs/nest/blob/master/sample/13-mongo-typeorm/src/photo/photo.service.ts#L6) `PhotoService` is a NestJS service responsible for retrieving `Photo` entities from the MongoDB-backed TypeORM data layer. It provides application-facing business logic for photo operations and is typically consumed by a controller or another service. ## Methods | Method | Signature | Returns | |---|---|---| | `findAll` | `findAll()` | `Promise` | ## Dependencies - `MongoRepository` ## Diagram ```mermaid sequenceDiagram participant Client participant PhotoController participant PhotoService participant PhotoRepository as TypeORM Repository participant MongoDB Client->>PhotoController: GET /photos PhotoController->>PhotoService: findAll() PhotoService->>PhotoRepository: find() PhotoRepository->>MongoDB: Query photo documents MongoDB-->>PhotoRepository: Photo records PhotoRepository-->>PhotoService: Promise PhotoService-->>PhotoController: Photo[] PhotoController-->>Client: JSON response ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { PhotoService } from './photo.service'; import { Photo } from './photo.entity'; @Controller('photos') export class PhotoController { constructor(private readonly photoService: PhotoService) {} @Get() async findAll(): Promise { return this.photoService.findAll(); } } ``` ## AI Coding Instructions - Keep database access inside `PhotoService`; controllers should delegate photo retrieval rather than querying repositories directly. - Preserve the `Promise` return type when extending `findAll()` or adding related retrieval methods. - Use the injected TypeORM MongoDB repository for persistence operations and avoid creating database connections manually. - Add filtering, pagination, or sorting through explicit service method parameters rather than changing the behavior of `findAll()` unexpectedly. - Ensure new photo entity fields and query behavior remain compatible with the MongoDB TypeORM configuration. ## Relationships - DEPENDS_ON β†’ `mongorepository` # PORT_METADATA **Kind:** Constant **Source:** [`packages/websockets/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/constants.ts#L8) ## Definition ```ts 'port' ``` ## Value ```ts 'port' ``` # 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) `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. # DatabaseModule **Kind:** Module **Source:** [`sample/14-mongoose-base/src/database/database.module.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/database/database.module.ts#L4) # greetingRequest **Kind:** API Endpoint **Source:** [`integration/scopes/src/inject-inquirer/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello.controller.ts#L20) ## Endpoint `GET /request` ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) ## Signature ```ts function isFactoryProvider(provider: Provider): provider is FactoryProvider ``` ## Parameters | Name | Type | |---|---| | `provider` | `Provider` | **Returns:** `provider is FactoryProvider` # 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) `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. # OutgoingResponse **Kind:** Type **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L22) ## Definition ```ts WritePacket & PacketId ``` # 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) 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. # PropertiesService **Kind:** Service **Source:** [`integration/injector/src/properties/properties.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/properties/properties.service.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ PropertiesService client->>+p1: PropertiesService p1-->client: return response ``` # DefaultsModule **Kind:** Module **Source:** [`integration/injector/src/defaults/defaults.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/defaults/defaults.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `defaultsservice` # 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) 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. # greetingTransient **Kind:** API Endpoint **Source:** [`integration/scopes/src/inject-inquirer/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/inject-inquirer/hello.controller.ts#L15) ## Endpoint `GET /transient` ## Referenced By - `HelloController` (MODULE_DECLARES) # NO_EVENT_HANDLER **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L55) ## Signature ```ts function NO_EVENT_HANDLER(text: TemplateStringsArray, pattern: string) ``` ## Parameters | Name | Type | |---|---| | `text` | `TemplateStringsArray` | | `pattern` | `string` | # 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) ## Definition ```ts object | string | number ``` # ParamProperties **Kind:** Interface **Source:** [`packages/core/helpers/context-utils.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/context-utils.ts#L15) `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. # PropertiesService **Kind:** Service **Source:** [`integration/inspector/src/properties/properties.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/properties/properties.service.ts#L6) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ PropertiesService client->>+p1: PropertiesService p1-->client: return response ``` # PROPERTY_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L14) ## Definition ```ts 'self:properties_metadata' ``` ## Value ```ts 'self:properties_metadata' ``` # DefaultsModule **Kind:** Module **Source:** [`integration/inspector/src/defaults/defaults.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/defaults/defaults.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `defaultsservice` # 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) `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. # hello **Kind:** API Endpoint **Source:** [`integration/versioning/src/middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/middleware.controller.ts#L8) ## Endpoint `GET /` ## Referenced By - `MiddlewareController` (MODULE_DECLARES) # 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) ## Definition ```ts ParameterDecorator ``` # ProducerBatch **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L764) `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) # 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) 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. # RequestChainService **Kind:** Service **Source:** [`integration/inspector/src/request-chain/request-chain.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/request-chain.service.ts#L4) `RequestChainService` is a NestJS backend service responsible for executing the request-chain workflow through its `call()` method. It provides a focused integration point for inspector-related request processing, allowing controllers or other services to trigger the chain without owning its internal orchestration. ## Methods | Method | Signature | Returns | |---|---|---| | `call` | `call()` | `unknown` | ## Dependencies - `HelperService` ## Diagram ```mermaid sequenceDiagram participant Caller as Controller / Service participant RequestChainService participant Chain as Request Chain Caller->>RequestChainService: call() RequestChainService->>Chain: Execute request-chain workflow Chain-->>RequestChainService: Processing result RequestChainService-->>Caller: Return result ``` ## Usage ```ts import { Controller, Get } from '@nestjs/common'; import { RequestChainService } from './request-chain/request-chain.service'; @Controller('inspector') export class InspectorController { constructor( private readonly requestChainService: RequestChainService, ) {} @Get('request-chain') getRequestChainResult() { return this.requestChainService.call(); } } ``` ## AI Coding Instructions - Inject `RequestChainService` through NestJS dependency injection rather than creating it manually with `new`. - Keep request-chain orchestration behind `call()` so callers do not depend on internal processing details. - Treat the return value of `call()` carefully until its concrete result type is defined; avoid unsafe assumptions about its shape. - Register the service in the appropriate NestJS module before injecting it into controllers or other providers. ## Relationships - DEPENDS_ON β†’ `helperservice` # ROUTE_MAPPED_MESSAGE **Kind:** Function **Source:** [`packages/core/helpers/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/messages.ts#L12) ## Signature ```ts function ROUTE_MAPPED_MESSAGE(path: string, method: string | number) ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | | `method` | `string | number` | # DurableModule **Kind:** Module **Source:** [`integration/inspector/src/durable/durable.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/durable/durable.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `durablecontroller` - MODULE_PROVIDES β†’ `durableservice` # 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) ## Signature ```ts function getClassScope(provider: Type): Scope ``` ## Parameters | Name | Type | |---|---| | `provider` | `Type` | **Returns:** `Scope` # helloFoo **Kind:** API Endpoint **Source:** [`integration/versioning/src/no-versioning.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/no-versioning.controller.ts#L5) ## Endpoint `GET /foo/bar` ## Referenced By - `NoVersioningController` (MODULE_DECLARES) # 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) `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. # 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) ## Definition ```ts Record ``` # ProducerRecord **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L740) `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) # 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) 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. # RequestChainService **Kind:** Service **Source:** [`integration/scopes/src/request-chain/request-chain.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/request-chain.service.ts#L4) `RequestChainService` is a NestJS service responsible for executing a request-processing chain through its `call()` method. It provides a focused backend integration point for consumers that need to trigger the configured request-chain behavior without depending on its internal implementation. ## Methods | Method | Signature | Returns | |---|---|---| | `call` | `call()` | `unknown` | ## Dependencies - `HelperService` ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller / Service participant RequestChainService participant Chain as Request Chain Dependencies Consumer->>RequestChainService: call() RequestChainService->>Chain: Execute configured chain Chain-->>RequestChainService: Result RequestChainService-->>Consumer: Result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { RequestChainService } from './request-chain/request-chain.service'; @Injectable() export class ExampleService { constructor( private readonly requestChainService: RequestChainService, ) {} async processRequest() { const result = await this.requestChainService.call(); return result; } } ``` ## AI Coding Instructions - Inject `RequestChainService` through NestJS constructor injection rather than creating it manually. - Use `call()` as the public entry point; keep request-chain orchestration details inside the service and its dependencies. - Treat the return value as `unknown` until it is validated, narrowed, or mapped to an application-specific type. - Ensure the module that consumes this service imports the module that provides `RequestChainService`. - Preserve asynchronous handling with `await` when `call()` may resolve work performed by downstream chain components. ## Relationships - DEPENDS_ON β†’ `helperservice` # EventsModule **Kind:** Module **Source:** [`sample/02-gateways/src/events/events.module.ts`](https://github.com/nestjs/nest/blob/master/sample/02-gateways/src/events/events.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `eventsgateway` # hellov2 **Kind:** API Endpoint **Source:** [`integration/versioning/src/middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/middleware.controller.ts#L13) ## Endpoint `GET /override` ## Referenced By - `MiddlewareController` (MODULE_DECLARES) # isDurable **Kind:** Function **Source:** [`packages/core/helpers/is-durable.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/is-durable.ts#L4) ## Signature ```ts function isDurable(provider: Type): boolean | undefined ``` ## Parameters | Name | Type | |---|---| | `provider` | `Type` | **Returns:** `boolean | undefined` # KafkaJSNumberOfRetriesExceeded **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1170) **Extends:** `KafkaJSNonRetriableError` ## Properties | Property | Type | |---|---| | `stack` | `string` | | `retryCount` | `number` | | `retryTime` | `number` | # 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) ## Definition ```ts 'body' | 'query' | 'param' | 'custom' ``` # PropertyDependency **Kind:** Interface **Source:** [`packages/core/injector/injector.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/injector.ts#L56) 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. # 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) 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. # RequestInterceptor **Kind:** Service **Source:** [`integration/websockets/src/request.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/request.interceptor.ts#L3) `RequestInterceptor` is a NestJS interceptor used by the WebSocket integration layer to observe and wrap incoming request handling. Its `intercept()` method runs within Nest's execution pipeline, allowing cross-cutting concerns such as logging, validation, context enrichment, or response transformation to be applied consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client as WebSocket Client participant Gateway as NestJS Gateway participant Interceptor as RequestInterceptor participant Handler as Message Handler Client->>Gateway: Emit WebSocket event Gateway->>Interceptor: intercept(context, next) Interceptor->>Interceptor: Inspect/enrich request context Interceptor->>Handler: next.handle() Handler-->>Interceptor: Handler result or stream Interceptor-->>Gateway: Transformed/pass-through result Gateway-->>Client: Emit response ``` ## Usage ```ts import { UseInterceptors } from '@nestjs/common'; import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; import { RequestInterceptor } from './request.interceptor'; @WebSocketGateway() @UseInterceptors(RequestInterceptor) export class EventsGateway { @SubscribeMessage('ping') handlePing() { return { event: 'pong', data: { timestamp: Date.now() } }; } } ``` ## AI Coding Instructions - Implement `intercept()` using NestJS's `ExecutionContext` and `CallHandler` contracts; always return the observable from `next.handle()` unless intentionally transforming it. - Keep request-wide concerns such as logging, tracing, and context extraction in this interceptor rather than duplicating them in individual gateway handlers. - Account for WebSocket execution contexts when reading request or client data; do not assume HTTP-specific methods such as `context.switchToHttp()`. - Apply the interceptor with `@UseInterceptors(RequestInterceptor)` at the gateway or handler level based on the intended scope. - Preserve errors from downstream handlers unless the interceptor explicitly maps them with RxJS error-handling operators. # 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. # EventsModule **Kind:** Module **Source:** [`sample/16-gateways-ws/src/events/events.module.ts`](https://github.com/nestjs/nest/blob/master/sample/16-gateways-ws/src/events/events.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `eventsgateway` # helloWorldV1 **Kind:** API Endpoint **Source:** [`integration/inspector/src/app-v1.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app-v1.controller.ts#L7) ## Endpoint `GET /` ## Referenced By - `AppV1Controller` (MODULE_DECLARES) # 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) `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`. # 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) ## Definition ```ts ParseArrayPipeOptions ``` # REDIRECT_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L40) ## Definition ```ts '__redirect__' ``` ## Value ```ts '__redirect__' ``` # RouteDefinition **Kind:** Interface **Source:** [`packages/core/router/paths-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/paths-explorer.ts#L17) `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) # TimeoutInterceptor **Kind:** Service **Source:** [`integration/inspector/src/common/interceptors/timeout.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/common/interceptors/timeout.interceptor.ts#L10) `TimeoutInterceptor` is a NestJS interceptor that wraps request handling in an RxJS timeout boundary. It ensures long-running controller operations fail predictably instead of keeping HTTP connections open indefinitely, allowing the application to return or transform timeout errors consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant TimeoutInterceptor participant Controller Client->>NestJS: HTTP request NestJS->>TimeoutInterceptor: intercept(context, next) TimeoutInterceptor->>Controller: next.handle() alt Response completes before timeout Controller-->>TimeoutInterceptor: Observable response TimeoutInterceptor-->>NestJS: Response Observable NestJS-->>Client: HTTP response else Request exceeds timeout TimeoutInterceptor-->>NestJS: Timeout error NestJS-->>Client: Timeout error response end ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor'; @Controller('reports') @UseInterceptors(TimeoutInterceptor) export class ReportsController { @Get() async getReports() { // This operation must complete within the interceptor's configured limit. return { reports: [], }; } } ``` ## AI Coding Instructions - Keep `intercept()` compatible with NestJS's `NestInterceptor` contract and return an `Observable`. - Apply timeout behavior to `next.handle()` using RxJS operators; do not eagerly subscribe inside the interceptor. - Ensure timeout errors are mapped consistently with the application's exception handling strategy. - Configure the interceptor globally or per-controller/route based on the intended timeout scope. - Avoid using a timeout value shorter than expected database, network, or downstream service response times. # ExpressModule **Kind:** Module **Source:** [`integration/nest-application/raw-body/src/express.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/raw-body/src/express.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `ExpressController` # 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` | # helloWorldV1 **Kind:** API Endpoint **Source:** [`integration/versioning/src/app-v1.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app-v1.controller.ts#L7) ## Endpoint `GET /` ## Referenced By - `AppV1Controller` (MODULE_DECLARES) # 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) `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. # 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) ## Definition ```ts Record | string ``` # REDIS_DEFAULT_HOST **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L6) ## Definition ```ts 'localhost' ``` ## Value ```ts 'localhost' ``` # RouteDefinition **Kind:** Interface **Source:** [`packages/core/router/router-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-explorer.ts#L49) `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. # TimeoutInterceptor **Kind:** Service **Source:** [`sample/01-cats-app/src/common/interceptors/timeout.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/interceptors/timeout.interceptor.ts#L10) `TimeoutInterceptor` is a NestJS interceptor that enforces a maximum execution time for incoming request handlers. It wraps the downstream observable and throws a timeout error when a controller or service response exceeds the configured limit, helping prevent long-running requests from consuming resources indefinitely. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant TimeoutInterceptor participant Handler as Controller/Route Handler Client->>NestJS: HTTP request NestJS->>TimeoutInterceptor: intercept(context, next) TimeoutInterceptor->>Handler: next.handle() Handler-->>TimeoutInterceptor: Observable response alt Response completes before timeout TimeoutInterceptor-->>NestJS: Return response NestJS-->>Client: HTTP response else Request exceeds timeout TimeoutInterceptor-->>NestJS: Throw timeout error NestJS-->>Client: Timeout error response end ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor'; @Controller('cats') @UseInterceptors(TimeoutInterceptor) export class CatsController { @Get() findAll() { return [{ id: 1, name: 'Milo' }]; } } ``` Register it globally when all HTTP routes should use the same timeout behavior: ```ts import { APP_INTERCEPTOR } from '@nestjs/core'; import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor'; @Module({ providers: [ { provide: APP_INTERCEPTOR, useClass: TimeoutInterceptor, }, ], }) export class AppModule {} ``` ## AI Coding Instructions - Keep `intercept()` compliant with NestJS's `NestInterceptor` contract: accept `ExecutionContext` and `CallHandler`, then return an `Observable`. - Apply RxJS timeout operators to `next.handle()` rather than manually managing timers or Promises. - Ensure timeout failures are converted into appropriate NestJS HTTP exceptions if clients need a consistent error response. - Use route-level `@UseInterceptors()` for endpoint-specific limits, or register the interceptor through `APP_INTERCEPTOR` for global enforcement. - Avoid setting overly aggressive timeout values for endpoints that legitimately perform slow database queries, file processing, or external API calls. # FastifyModule **Kind:** Module **Source:** [`integration/nest-application/raw-body/src/fastify.module.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/raw-body/src/fastify.module.ts#L4) ## Relationships - MODULE_DECLARES β†’ `FastifyController` # 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` | # helloWorldV2 **Kind:** API Endpoint **Source:** [`integration/inspector/src/app-v2.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app-v2.controller.ts#L7) ## Endpoint `GET /` ## Referenced By - `AppV2Controller` (MODULE_DECLARES) # ProducerDeserializer **Kind:** Type **Source:** [`packages/microservices/interfaces/deserializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/deserializer.interface.ts#L17) ## Definition ```ts Deserializer ``` # REDIS_DEFAULT_PORT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L5) ## Definition ```ts 6379 ``` ## Value ```ts 6379 ``` # 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) `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] | # 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) `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) # TimeoutInterceptor **Kind:** Service **Source:** [`sample/36-hmr-esm/src/common/interceptors/timeout.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/interceptors/timeout.interceptor.ts#L10) `TimeoutInterceptor` enforces a maximum execution time for NestJS request handlers. It wraps the downstream handler observable, converts RxJS timeout failures into an HTTP `408 Request Timeout` response, and rethrows all other errors unchanged. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable` | ## Diagram ```mermaid sequenceDiagram participant Client participant Nest as NestJS Pipeline participant Timeout as TimeoutInterceptor participant Handler as Controller/Handler Client->>Nest: HTTP request Nest->>Timeout: intercept(context, next) Timeout->>Handler: next.handle() Handler-->>Timeout: Observable response alt Completes before timeout Timeout-->>Nest: Response observable Nest-->>Client: HTTP response else Exceeds timeout limit Timeout-->>Nest: RequestTimeoutException Nest-->>Client: 408 Request Timeout else Other handler error Timeout-->>Nest: Rethrow original error Nest-->>Client: Error response end ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor'; @Module({ providers: [ { provide: APP_INTERCEPTOR, useClass: TimeoutInterceptor, }, ], }) export class AppModule {} ``` You can also apply it to a single controller or route: ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor'; @Controller('reports') @UseInterceptors(TimeoutInterceptor) export class ReportsController { @Get() findAll() { return { status: 'completed' }; } } ``` ## AI Coding Instructions - Keep timeout handling inside the RxJS pipeline returned by `next.handle()`; interceptors must return an `Observable`. - Preserve non-timeout failures by rethrowing the original error so NestJS exception filters can handle them correctly. - Register the interceptor with `APP_INTERCEPTOR` for application-wide enforcement, or use `@UseInterceptors()` for targeted routes. - Ensure long-running operations are designed to complete within the configured timeout or move them to asynchronous/background processing. - When changing the timeout duration, consider downstream database, HTTP client, and reverse-proxy timeout settings to avoid inconsistent behavior. # HelloModule **Kind:** Module **Source:** [`integration/hello-world/src/hello/hello.module.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.module.ts#L6) ## Relationships - MODULE_DECLARES β†’ `hellocontroller` - MODULE_PROVIDES β†’ `helloservice` - MODULE_PROVIDES β†’ `usersservice` # helloWorldV2 **Kind:** API Endpoint **Source:** [`integration/versioning/src/app-v2.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app-v2.controller.ts#L7) ## Endpoint `GET /` ## Referenced By - `AppV2Controller` (MODULE_DECLARES) # 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) ## Signature ```ts function isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel ``` ## Parameters | Name | Type | |---|---| | `maybeLogLevel` | `any` | **Returns:** `maybeLogLevel is LogLevel` # 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) ## Definition ```ts 0 | 1 | 2 ``` # RENDER_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L36) ## Definition ```ts '__renderTemplate__' ``` ## Value ```ts '__renderTemplate__' ``` # 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) `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) # TransformInterceptor **Kind:** Service **Source:** [`integration/inspector/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/core/interceptors/transform.interceptor.ts#L14) `TransformInterceptor` is a NestJS interceptor that wraps controller responses in a consistent `Response` structure before they are returned to clients. It runs after a route handler completes, allowing the inspector service to normalize successful API output without changing individual controller implementations. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable>` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant TransformInterceptor participant Handler as Route Handler Client->>TransformInterceptor: HTTP request TransformInterceptor->>Handler: next.handle() Handler->>Controller: Execute controller logic Controller-->>Handler: Return payload Handler-->>TransformInterceptor: Observable TransformInterceptor->>TransformInterceptor: Transform payload to Response TransformInterceptor-->>Client: Normalized API response ``` ## Usage ```ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors, } from '@nestjs/common'; import { map, Observable } from 'rxjs'; interface Response { data: T; } @Injectable() export class TransformInterceptor implements NestInterceptor> { intercept( _context: ExecutionContext, next: CallHandler, ): Observable> { return next.handle().pipe( map((data) => ({ data, })), ); } } @UseInterceptors(TransformInterceptor) @Controller('projects') export class ProjectsController { @Get() findAll() { return [{ id: 'project-1', name: 'Inspector' }]; } } // Response: // { // "data": [ // { "id": "project-1", "name": "Inspector" } // ] // } ``` ## AI Coding Instructions - Keep transformations inside the RxJS `pipe()` returned by `next.handle()`; do not eagerly resolve or subscribe to the observable. - Preserve generic typing with `T` and `Response` so controller return types remain accurately inferred. - Apply this interceptor with `@UseInterceptors()` at the controller, route, or global application level depending on the required response scope. - Avoid using this interceptor for error formatting; handle exceptions through NestJS exception filters or dedicated error interceptors. # 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) # HelperModule **Kind:** Module **Source:** [`integration/inspector/src/request-chain/helper/helper.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/helper/helper.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `helperservice` - MODULE_EXPORTS β†’ `helperservice` # index **Kind:** API Endpoint **Source:** [`integration/nest-application/use-body-parser/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/use-body-parser/src/app.controller.ts#L6) ## Endpoint `POST /` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) ## Signature ```ts function isRequestMethodAll(method: RequestMethod) ``` ## Parameters | Name | Type | |---|---| | `method` | `RequestMethod` | # 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) ## Definition ```ts T & { rawBody?: Buffer } ``` # REPL_INITIALIZED_MESSAGE **Kind:** Constant **Source:** [`packages/core/repl/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/constants.ts#L1) ## Definition ```ts 'REPL initialized' ``` ## Value ```ts 'REPL initialized' ``` # 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) `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] # TransformInterceptor **Kind:** Service **Source:** [`sample/36-hmr-esm/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/core/interceptors/transform.interceptor.ts#L14) `TransformInterceptor` is a NestJS interceptor that wraps controller responses in a consistent `Response` envelope. It runs after a route handler produces its value, transforming the emitted data before it is returned to the client. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable>` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant TransformInterceptor participant Controller Client->>NestJS: HTTP request NestJS->>TransformInterceptor: intercept(context, next) TransformInterceptor->>Controller: next.handle() Controller-->>TransformInterceptor: Observable TransformInterceptor->>TransformInterceptor: map result to Response TransformInterceptor-->>NestJS: Observable> NestJS-->>Client: Transformed JSON response ``` ## Usage ```ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors, } from '@nestjs/common'; import { map, Observable } from 'rxjs'; interface Response { data: T; } @Injectable() export class TransformInterceptor implements NestInterceptor> { intercept( _context: ExecutionContext, next: CallHandler, ): Observable> { return next.handle().pipe( map((data) => ({ data })), ); } } @UseInterceptors(TransformInterceptor) export class UsersController { // Responses from this controller are returned as: // { data: ... } } ``` ## AI Coding Instructions - Keep transformation logic inside the RxJS pipeline returned by `next.handle()`; use operators such as `map` rather than manually subscribing. - Preserve generic typing with `T` and return `Observable>` so controller response types remain accurate. - Register the interceptor with `@UseInterceptors()` for controller/route scope, or configure it as an `APP_INTERCEPTOR` for global response formatting. - Avoid wrapping responses that already follow the `Response` contract, unless double-wrapping is explicitly intended. - Ensure error formatting is handled separately with an exception filter or `catchError`; this interceptor should primarily transform successful responses. # WritePacket **Kind:** Interface **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L10) `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) `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. # HelperModule **Kind:** Module **Source:** [`integration/scopes/src/request-chain/helper/helper.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/helper/helper.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `helperservice` - MODULE_EXPORTS β†’ `helperservice` # index **Kind:** API Endpoint **Source:** [`sample/28-sse/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/28-sse/src/app.controller.ts#L10) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # RemoveInstrumentationEventListener **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L404) ## 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) ## Definition ```ts 'microservices:reply_pattern' ``` ## Value ```ts 'microservices:reply_pattern' ``` # 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) `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) # TransformInterceptor **Kind:** Service **Source:** [`sample/01-cats-app/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/core/interceptors/transform.interceptor.ts#L14) `TransformInterceptor` is a NestJS interceptor that normalizes successful controller responses into a consistent `Response` shape. It runs after a route handler returns data, wrapping the payload so API consumers receive a predictable response contract across the application. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable>` | ## Diagram ```mermaid sequenceDiagram participant Client participant NestJS participant TransformInterceptor participant Controller Client->>NestJS: HTTP request NestJS->>TransformInterceptor: intercept(context, next) TransformInterceptor->>Controller: next.handle() Controller-->>TransformInterceptor: Observable TransformInterceptor->>TransformInterceptor: map(data => ({ data })) TransformInterceptor-->>NestJS: Observable> NestJS-->>Client: Normalized JSON response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { TransformInterceptor } from './core/interceptors/transform.interceptor'; interface Cat { id: number; name: string; } @Controller('cats') @UseInterceptors(TransformInterceptor) export class CatsController { @Get() findAll(): Cat[] { return [ { id: 1, name: 'Milo' }, { id: 2, name: 'Luna' }, ]; } } // Response: // { // "data": [ // { "id": 1, "name": "Milo" }, // { "id": 2, "name": "Luna" } // ] // } ``` ## AI Coding Instructions - Return plain DTOs or values from controllers; let `TransformInterceptor` apply the shared `Response` envelope. - Register the interceptor with `@UseInterceptors(TransformInterceptor)` at the controller level, or configure it globally for application-wide response formatting. - Preserve the generic `T` type when changing `intercept()` so wrapped response types remain accurate. - Do not use this interceptor to format thrown errors; handle error payloads through NestJS exception filters instead. # ConfigSynonyms **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L359) `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. # InjectModule **Kind:** Module **Source:** [`integration/injector/src/inject/inject.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/inject/inject.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `InjectService` # localPipe **Kind:** API Endpoint **Source:** [`integration/hello-world/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.controller.ts#L26) ## Endpoint `GET /hello/local-pipe/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `any` | βœ“ | | ## Referenced By - `HelloController` (MODULE_DECLARES) # ReplFunctionClass **Kind:** Type **Source:** [`packages/core/repl/repl.interfaces.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl.interfaces.ts#L21) ## Definition ```ts new (replContext: ReplContext) => ReplFunction ``` # 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) 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. # rethrow **Kind:** Function **Source:** [`packages/core/helpers/rethrow.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/rethrow.ts#L1) ## Signature ```ts function rethrow(err: unknown) ``` ## Parameters | Name | Type | |---|---| | `err` | `unknown` | # TransformInterceptor **Kind:** Service **Source:** [`sample/10-fastify/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/core/interceptors/transform.interceptor.ts#L14) `TransformInterceptor` is a NestJS interceptor that wraps successful controller responses in a consistent `Response` structure. It runs after a route handler returns data, transforming the emitted value before Fastify sends the HTTP response. ## Methods | Method | Signature | Returns | |---|---|---| | `intercept` | `intercept(context: ExecutionContext, next: CallHandler)` | `Observable>` | ## Diagram ```mermaid sequenceDiagram participant Client participant Fastify participant TransformInterceptor participant Controller Client->>Fastify: HTTP request Fastify->>TransformInterceptor: intercept(context, next) TransformInterceptor->>Controller: next.handle() Controller-->>TransformInterceptor: Observable TransformInterceptor->>TransformInterceptor: map(data => ({ data })) TransformInterceptor-->>Fastify: Observable> Fastify-->>Client: JSON response ``` ## Usage ```ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { TransformInterceptor } from './core/interceptors/transform.interceptor'; type User = { id: string; name: string; }; @Controller('users') @UseInterceptors(TransformInterceptor) export class UsersController { @Get('me') getCurrentUser(): User { return { id: 'user_123', name: 'Ada Lovelace', }; } } // Response: // { // "data": { // "id": "user_123", // "name": "Ada Lovelace" // } // } ``` ## AI Coding Instructions - Return plain DTOs or values from controllers; let `TransformInterceptor` apply the `{ data: ... }` response envelope. - Register the interceptor with `@UseInterceptors(TransformInterceptor)` for specific controllers/routes, or globally through Nest application configuration when consistent formatting is required everywhere. - Preserve the generic `Response` contract when modifying the interceptor so controller return types remain accurately represented. - Do not use this interceptor to format exception responses; handle errors through NestJS exception filters or exception handling middleware. # WebhooksExplorer **Kind:** Class **Source:** [`integration/discovery/src/webhooks.explorer.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/webhooks.explorer.ts#L5) `WebhooksExplorer` discovers and retrieves webhook definitions for an integration. It encapsulates webhook exploration logic behind `getWebhooks()`, allowing the broader discovery pipeline to consume webhook metadata consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `getWebhooks` | `getWebhooks()` | `void` | ## Diagram ```mermaid graph LR A[Integration Discovery Pipeline] --> B[WebhooksExplorer] B --> C[getWebhooks()] C --> D[Webhook Definitions] D --> E[Generated Integration Metadata] ``` ## Usage ```ts import { WebhooksExplorer } from './integration/discovery/src/webhooks.explorer'; // Provide the dependencies required by the explorer in your application setup. const webhooksExplorer = new WebhooksExplorer(/* discovery dependencies */); const webhooks = await webhooksExplorer.getWebhooks(); for (const webhook of webhooks) { console.log(`Discovered webhook: ${webhook.name}`); } ``` ## AI Coding Instructions - Keep webhook discovery responsibilities inside `WebhooksExplorer`; callers should use `getWebhooks()` rather than duplicating discovery logic. - Preserve the shape of returned webhook definitions so downstream metadata generation remains compatible. - Handle missing, disabled, or unsupported webhook configurations gracefully rather than failing the entire discovery process. - When adding webhook capabilities, ensure they are included in `getWebhooks()` and follow existing integration discovery conventions. ## Referenced By - `AppModule` (MODULE_PROVIDES) # ContextId **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L36) `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. # 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) `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. # InputModule **Kind:** Module **Source:** [`integration/injector/src/circular-modules/input.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-modules/input.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `inputservice` - MODULE_EXPORTS β†’ `inputservice` # multicats **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt-broadcast.controller.ts#L16) ## Endpoint `GET /broadcast` ## Referenced By - `MqttBroadcastController` (MODULE_DECLARES) # 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) ## Definition ```ts 'REQUEST' ``` ## Value ```ts 'REQUEST' ``` # 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) ## Signature ```ts function RouteConstraints(config: RouteShorthandOptions['constraints']) ``` ## Parameters | Name | Type | |---|---| | `config` | `RouteShorthandOptions['constraints']` | # 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) ## Definition ```ts RouteTree[] ``` # TransientService **Kind:** Service **Source:** [`integration/lazy-modules/src/transient.service.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/transient.service.ts#L4) `TransientService` is a NestJS service located in the lazy-modules integration area. It exposes an `eager()` method that can be invoked by consuming modules or providers to access eagerly resolved behavior while participating in Nest's dependency injection system. ## Methods | Method | Signature | Returns | |---|---|---| | `eager` | `eager()` | `unknown` | ## Dependencies - `EagerService` ## Diagram ```mermaid sequenceDiagram participant Consumer as Consumer Provider participant DI as NestJS DI Container participant Service as TransientService Consumer->>DI: Request TransientService DI-->>Consumer: Provide service instance Consumer->>Service: eager() Service-->>Consumer: Return result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { TransientService } from './transient.service'; @Injectable() export class ExampleConsumer { constructor(private readonly transientService: TransientService) {} run() { const result = this.transientService.eager(); return result; } } ``` ## AI Coding Instructions - Inject `TransientService` through NestJS constructor injection rather than creating it with `new`. - Call `eager()` through the injected service instance and preserve its `unknown` return type until it is safely narrowed. - Ensure the module consuming this service imports or provides the module that registers `TransientService`. - Keep lazy-module integration behavior isolated; avoid introducing direct coupling to unrelated application modules. ## Relationships - DEPENDS_ON β†’ `EagerService` # BLOCKED_RMQ_MESSAGE **Kind:** Function **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L61) ## Signature ```ts function BLOCKED_RMQ_MESSAGE(reason: string) ``` ## Parameters | Name | Type | |---|---| | `reason` | `string` | # DeleteAclFilterResponses **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L491) `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. # 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) `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. # InputModule **Kind:** Module **Source:** [`integration/inspector/src/circular-modules/input.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-modules/input.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `inputservice` - MODULE_EXPORTS β†’ `inputservice` # multicats **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats-broadcast.controller.ts#L21) ## Endpoint `GET /broadcast` ## Referenced By - `NatsBroadcastController` (MODULE_DECLARES) # 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) ## Definition ```ts Symbol('REQUEST_CONTEXT_ID') ``` ## Value ```ts Symbol('REQUEST_CONTEXT_ID') ``` # SASLMechanism **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L104) ## Definition ```ts keyof SASLMechanismOptionsMap ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/inspector/src/circular-hello/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/users/user-by-id.pipe.ts#L4) `UserByIdPipe` is a NestJS pipe that transforms an incoming user identifier into a user value before it reaches a route handler. It is intended for use at controller boundaries, centralizing user lookup, validation, or normalization logic for endpoints that operate on a specific user. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Dependencies - `UsersService` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant Pipe as UserByIdPipe participant Handler as Route Handler Client->>Controller: Request with user ID parameter Controller->>Pipe: transform(userId) Pipe->>Pipe: Validate/resolve user ID Pipe-->>Controller: Transformed user value Controller->>Handler: Invoke handler with transformed value Handler-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':id') getUser(@Param('id', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Keep `transform()` focused on converting a route parameter into the value expected by the controller handler. - Throw appropriate NestJS HTTP exceptions when the supplied user ID is invalid or cannot be resolved. - Apply this pipe at parameter level with `@Param('id', UserByIdPipe)` when only a single user identifier needs transformation. - Preserve the pipe contract: `transform()` should return the transformed value or throw, rather than returning partially valid data. - Update controller parameter types when the pipe’s output changes from an ID string to a resolved user entity. ## Relationships - DEPENDS_ON β†’ `usersservice` # 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) ## Signature ```ts function createContextId(): ContextId ``` **Returns:** `ContextId` # 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) `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) # InputPropertiesModule **Kind:** Module **Source:** [`integration/injector/src/circular-properties/input-properties.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-properties/input-properties.module.ts#L5) ## Relationships - MODULE_IMPORTS β†’ `forwardRef` - MODULE_PROVIDES β†’ `inputservice` - MODULE_EXPORTS β†’ `inputservice` # multicats **Kind:** API Endpoint **Source:** [`integration/microservices/src/redis/redis-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis-broadcast.controller.ts#L16) ## Endpoint `GET /broadcast` ## Referenced By - `RedisBroadcastController` (MODULE_DECLARES) # REQUEST_PATTERN_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L40) ## Definition ```ts 'microservices:request_pattern' ``` ## Value ```ts 'microservices:request_pattern' ``` # SASLOptions **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L108) ## Definition ```ts SASLMechanismOptions ``` # 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) `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] # UserByIdPipe **Kind:** Service **Source:** [`integration/scopes/src/circular-hello/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/users/user-by-id.pipe.ts#L4) `UserByIdPipe` is a NestJS pipe that transforms an incoming user identifier into a user value used by the circular hello integration scope. It centralizes user-ID parsing or lookup behavior before the value reaches a controller or downstream handler. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Dependencies - `UsersService` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant Pipe as UserByIdPipe participant Handler Client->>Controller: Request with user ID parameter Controller->>Pipe: transform(userId) Pipe-->>Controller: Transformed user value Controller->>Handler: Invoke handler with transformed value Handler-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':id') getUser(@Param('id', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Keep `transform()` focused on converting or resolving the incoming user ID; avoid controller-specific response logic. - Throw appropriate NestJS exceptions, such as `NotFoundException` or `BadRequestException`, when the ID is invalid or no user exists. - Register or inject any required user repository/service through NestJS dependency injection rather than creating dependencies directly. - Apply the pipe at the parameter level (`@Param('id', UserByIdPipe)`) when only a user ID needs transformation. - Preserve the expected transformed return type so controllers can safely consume the resolved user value. ## Relationships - DEPENDS_ON β†’ `usersservice` # CatOwnerResolver **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/cats/cat-owner.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/cat-owner.resolver.ts#L5) `CatOwnerResolver` provides the GraphQL resolver for the `owner` field on a `Cat` object. It connects the schema-defined relationship between cats and owners to application data by resolving and returning an `Owner` asynchronously. ## Methods | Method | Signature | Returns | |---|---|---| | `owner` | `owner(cat: Cat & { ownerId: number })` | `Promise` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Query[Cat query] Query --> Cat[Cat object] Cat -->|owner field| Resolver[CatOwnerResolver.owner()] Resolver --> Owner[Owner] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { CatOwnerResolver } from './cats/cat-owner.resolver'; @Module({ imports: [ GraphQLModule.forRoot({ typePaths: ['./**/*.graphql'], }), ], providers: [CatOwnerResolver], }) export class AppModule {} ``` ```graphql query GetCatOwner { cat { id name owner { id name } } } ``` When a client requests `cat.owner`, GraphQL invokes `CatOwnerResolver.owner()` to provide the matching `Owner`. ## AI Coding Instructions - Register `CatOwnerResolver` in the NestJS module `providers` array so GraphQL can discover the field resolver. - Keep the `owner()` return type aligned with the schema’s `Owner` type and preserve its `Promise` contract. - Use this resolver for `Cat`-specific relationship fields; avoid placing unrelated cat query or mutation logic here. - When adding database access, use the parent cat identifier to resolve the correct owner rather than returning a shared or hard-coded owner. - Ensure the GraphQL schema defines the `owner` field on `Cat` with a compatible `Owner` return type. ## Referenced By - `CatsModule` (MODULE_PROVIDES) # 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) `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. # isFunction **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L43) ## Signature ```ts function isFunction(val: any): val is Function ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is Function` # LazyModule **Kind:** Module **Source:** [`integration/lazy-modules/src/lazy.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/lazy.module.ts#L9) ## Relationships - MODULE_PROVIDES β†’ `LazyService` # multicats **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq-broadcast.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq-broadcast.controller.ts#L27) ## Endpoint `GET /broadcast` ## Referenced By - `RMQBroadcastController` (MODULE_DECLARES) # REQUEST_SCOPED_FACTORY **Kind:** Constant **Source:** [`integration/injector/src/scoped/scoped.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/scoped.module.ts#L9) ## Definition ```ts 'REQUEST_SCOPED_FACTORY' ``` ## Value ```ts 'REQUEST_SCOPED_FACTORY' ``` # SeekEntry **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L438) ## Definition ```ts PartitionOffset ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/scopes/src/circular-transient/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/users/user-by-id.pipe.ts#L8) `UserByIdPipe` is a NestJS pipe used to transform an incoming user identifier into a user-related value before it reaches a controller handler. It centralizes user lookup or identifier normalization logic for routes that receive a user ID, keeping controllers focused on request handling. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant Pipe as UserByIdPipe participant UserService Client->>Controller: Request with userId parameter Controller->>Pipe: transform(userId) Pipe->>UserService: Resolve user by ID UserService-->>Pipe: User result Pipe-->>Controller: Transformed value Controller-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':userId') getUser(@Param('userId', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Keep `transform()` compatible with NestJS pipe conventions: accept the incoming value and return the transformed result or throw an appropriate exception. - Use this pipe at controller parameter boundaries, such as `@Param('userId', UserByIdPipe)`, rather than duplicating lookup logic in controllers. - Preserve dependency injection patterns when adding user repository or service dependencies to the pipe. - Handle missing, malformed, or unknown user IDs consistently, typically by throwing a NestJS HTTP exception such as `NotFoundException`. # CleanupWebhook **Kind:** Class **Source:** [`integration/discovery/src/my-webhook/cleanup.webhook.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/my-webhook/cleanup.webhook.ts#L3) `CleanupWebhook` is a webhook lifecycle class responsible for running cleanup logic when the application or webhook process starts. It fits into the discovery integration by providing a dedicated `onStart()` entry point for removing stale state, resetting resources, or preparing the webhook environment before normal processing begins. ## Methods | Method | Signature | Returns | |---|---|---| | `onStart` | `onStart()` | `void` | ## Diagram ```mermaid graph LR A[Application/Webhook Startup] --> B[CleanupWebhook] B --> C[onStart()] C --> D[Perform cleanup tasks] D --> E[Webhook ready for processing] ``` ## Usage ```ts import { CleanupWebhook } from './my-webhook/cleanup.webhook'; const cleanupWebhook = new CleanupWebhook(); // Invoke during application or webhook initialization. await cleanupWebhook.onStart(); ``` ## AI Coding Instructions - Keep startup cleanup logic inside `onStart()` so it runs consistently through the webhook lifecycle. - Make cleanup operations safe to run multiple times; startup hooks may be retried or invoked after restarts. - Avoid placing request-specific processing in this class; use it only for initialization and stale-resource cleanup. - Handle external cleanup failures carefully so non-critical cleanup does not prevent the webhook from starting. - Register or invoke `CleanupWebhook` through the discovery integration's startup lifecycle rather than calling it from individual request handlers. ## Referenced By - `MyWebhookModule` (MODULE_PROVIDES) # HttpExceptionOptions **Kind:** Interface **Source:** [`packages/common/exceptions/http.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts#L8) `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. # isNil **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L48) ## Signature ```ts function isNil(val: any): val is null | undefined ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is null | undefined` # LongLivingAppModule **Kind:** Module **Source:** [`integration/repl/src/long-living-app.module.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/long-living-app.module.ts#L4) # multiple **Kind:** API Endpoint **Source:** [`integration/versioning/src/multiple-middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/multiple-middleware.controller.ts#L8) ## Endpoint `GET /multiple` ## Referenced By - `MultipleMiddlewareVersionController` (MODULE_DECLARES) # 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) 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. # 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) ## Definition ```ts Pick ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/scopes/src/transient/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/users/user-by-id.pipe.ts#L3) `UserByIdPipe` is a NestJS pipe used to transform and validate incoming user ID route parameters before they reach a controller handler. It centralizes user lookup or ID normalization logic for endpoints that operate on a specific user within the transient users scope. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant UserByIdPipe participant UserService Client->>Controller: GET /users/:userId Controller->>UserByIdPipe: transform(userId) UserByIdPipe->>UserService: Resolve user by ID UserService-->>UserByIdPipe: User entity or not found UserByIdPipe-->>Controller: Transformed user value Controller-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':userId') findOne( @Param('userId', UserByIdPipe) user: unknown, ) { return user; } } ``` ## AI Coding Instructions - Use `UserByIdPipe` on route parameters that require a resolved or validated user identifier. - Keep `transform()` focused on parameter transformation and validation; avoid controller-specific response logic. - Throw appropriate NestJS HTTP exceptions when the supplied user ID is invalid or the user cannot be found. - Ensure any services used for user lookup are injected through NestJS dependency injection. - Preserve the transient scope behavior when adding dependencies or reusing this pipe across request flows. # FlushWebhook **Kind:** Class **Source:** [`integration/discovery/src/my-webhook/flush.webhook.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/my-webhook/flush.webhook.ts#L3) `FlushWebhook` is a webhook handler responsible for running flush-related initialization when the webhook lifecycle starts. Its `onStart()` method integrates the webhook into the discovery service startup flow, ensuring any required flush behavior is triggered before processing requests. ## Methods | Method | Signature | Returns | |---|---|---| | `onStart` | `onStart()` | `void` | ## Diagram ```mermaid graph LR A[Discovery Service Startup] --> B[FlushWebhook] B --> C[onStart()] C --> D[Initialize / trigger flush workflow] D --> E[Webhook ready for requests] ``` ## Usage ```ts import { FlushWebhook } from "./my-webhook/flush.webhook"; const flushWebhook = new FlushWebhook(); // Invoke this as part of the application or webhook lifecycle startup. await flushWebhook.onStart(); ``` ## AI Coding Instructions - Keep startup-specific behavior inside `onStart()` so it runs consistently with the webhook lifecycle. - Ensure `onStart()` remains safe to call during service initialization and does not depend on request-specific state. - Register or instantiate `FlushWebhook` through the discovery service's existing webhook integration mechanism. - Avoid moving flush logic into request handlers when it must occur before the webhook begins serving requests. ## Referenced By - `MyWebhookModule` (MODULE_PROVIDES) # 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) `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. # isObject **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L4) ## Signature ```ts function isObject(fn: any): fn is object ``` ## Parameters | Name | Type | |---|---| | `fn` | `any` | **Returns:** `fn is object` # multiple **Kind:** API Endpoint **Source:** [`integration/versioning/src/multiple.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/multiple.controller.ts#L7) ## Endpoint `GET /multiple` ## Referenced By - `MultipleVersionController` (MODULE_DECLARES) # MultipleProvidersModule **Kind:** Module **Source:** [`integration/injector/src/multiple-providers/multiple-providers.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/multiple-providers/multiple-providers.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `amodule` - MODULE_IMPORTS β†’ `bmodule` - MODULE_IMPORTS β†’ `CModule` # RESPONSE_PASSTHROUGH_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L41) ## Definition ```ts '__responsePassthrough__' ``` ## Value ```ts '__responsePassthrough__' ``` # SerializedGraphStatus **Kind:** Type **Source:** [`packages/core/inspector/serialized-graph.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/serialized-graph.ts#L22) ## Definition ```ts 'partial' | 'complete' ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/hello-world/src/hello/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/users/user-by-id.pipe.ts#L4) `UserByIdPipe` is a NestJS pipe that transforms and validates a user identifier received by a route handler. It centralizes user lookup or ID parsing logic so controllers can receive a resolved, validated value instead of handling request input directly. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Dependencies - `UsersService` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant UserByIdPipe participant UserService Client->>Controller: GET /users/:id Controller->>UserByIdPipe: transform(id) UserByIdPipe->>UserService: Find/validate user by ID UserService-->>UserByIdPipe: User or lookup result UserByIdPipe-->>Controller: Transformed value Controller-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Keep `transform()` focused on converting or validating the incoming route parameter value. - Throw appropriate NestJS HTTP exceptions when the supplied user ID is invalid or cannot be resolved. - Use the pipe at controller parameter boundaries, such as `@Param('id', UserByIdPipe)`. - Avoid duplicating user ID parsing and lookup logic in controllers; place it in this pipe or a dedicated user service. ## Relationships - DEPENDS_ON β†’ `usersservice` # 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) `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. # IResourceConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L381) `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. # isUndefined **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L1) ## Signature ```ts function isUndefined(obj: any): obj is undefined ``` ## Parameters | Name | Type | |---|---| | `obj` | `any` | **Returns:** `obj is undefined` # neutral **Kind:** API Endpoint **Source:** [`integration/versioning/src/neutral-middleware.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/neutral-middleware.controller.ts#L8) ## Endpoint `GET /neutral` ## Referenced By - `VersionNeutralMiddlewareController` (MODULE_DECLARES) # PhotoModule **Kind:** Module **Source:** [`integration/typeorm/src/photo/photo.module.ts`](https://github.com/nestjs/nest/blob/master/integration/typeorm/src/photo/photo.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `photocontroller` - MODULE_PROVIDES β†’ `photoservice` # RMQ_SEPARATOR **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L24) ## Definition ```ts '.' ``` ## Value ```ts '.' ``` # TopicPartitions **Kind:** Type **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L874) ## Definition ```ts { topic: string; partitions: number[] } ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/hello-world/src/host/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/users/user-by-id.pipe.ts#L4) `UserByIdPipe` is a NestJS pipe that transforms an incoming user identifier into a user-related value before the request reaches a controller handler. It centralizes ID parsing, validation, or user lookup logic so controllers can receive a normalized user object or validated identifier. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Dependencies - `UsersService` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as NestJS Controller participant Pipe as UserByIdPipe participant Service as Users Service Client->>Controller: Request with user ID parameter Controller->>Pipe: transform(userId) Pipe->>Pipe: Parse and validate ID Pipe->>Service: Find user by ID Service-->>Pipe: User or not found result Pipe-->>Controller: Transformed user value Controller-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Keep `transform()` focused on converting and validating the incoming route parameter value. - Throw appropriate NestJS HTTP exceptions, such as `BadRequestException` for invalid IDs or `NotFoundException` when a user does not exist. - Inject and reuse the existing users/data-access service rather than performing database queries directly in controllers. - Ensure the transformed return type matches what controller handlers expect: either a validated ID or a resolved user entity. - Register the pipe as a provider when it depends on injected services. ## Relationships - DEPENDS_ON β†’ `usersservice` # ITopicPartitionConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L274) `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. # KafkaJSServerDoesNotSupportApiKey **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1215) **Extends:** `KafkaJSNonRetriableError` ## Properties | Property | Type | |---|---| | `apiKey` | `number` | | `apiName` | `string` | # neutral **Kind:** API Endpoint **Source:** [`integration/versioning/src/neutral.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/neutral.controller.ts#L7) ## Endpoint `GET /neutral` ## Referenced By - `VersionNeutralController` (MODULE_DECLARES) # PhotoModule **Kind:** Module **Source:** [`sample/13-mongo-typeorm/src/photo/photo.module.ts`](https://github.com/nestjs/nest/blob/master/sample/13-mongo-typeorm/src/photo/photo.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `photocontroller` - MODULE_PROVIDES β†’ `photoservice` # RMQ_WILDCARD_ALL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L26) ## Definition ```ts '#' ``` ## Value ```ts '#' ``` # 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) ## Signature ```ts function RouteConfig(config: any) ``` ## Parameters | Name | Type | |---|---| | `config` | `any` | # 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) ## Definition ```ts (value: T, metadata: ArgumentMetadata) => any ``` # UserByIdPipe **Kind:** Service **Source:** [`integration/hello-world/src/host-array/users/user-by-id.pipe.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/users/user-by-id.pipe.ts#L4) `UserByIdPipe` is a NestJS pipe that transforms an incoming user identifier into a user-related value before the request reaches a controller handler. It centralizes user ID parsing, validation, and lookup behavior for routes that operate on users in the host-array hello-world integration. ## Methods | Method | Signature | Returns | |---|---|---| | `transform` | `transform(value: string, metadata: ArgumentMetadata)` | `unknown` | ## Dependencies - `UsersService` ## Diagram ```mermaid sequenceDiagram participant Client participant Controller participant UserByIdPipe participant UsersSource as Users Data Source Client->>Controller: Request with user ID parameter Controller->>UserByIdPipe: transform(userId) UserByIdPipe->>UsersSource: Resolve or validate user UsersSource-->>UserByIdPipe: User data / lookup result UserByIdPipe-->>Controller: Transformed value Controller-->>Client: Response ``` ## Usage ```ts import { Controller, Get, Param } from '@nestjs/common'; import { UserByIdPipe } from './user-by-id.pipe'; @Controller('users') export class UsersController { @Get(':id') getUser(@Param('id', UserByIdPipe) user: unknown) { return user; } } ``` ## AI Coding Instructions - Use `UserByIdPipe` at controller parameter boundaries with decorators such as `@Param('id', UserByIdPipe)`. - Keep transformation logic in `transform()` so controllers receive already validated or resolved user values. - Preserve NestJS pipe error behavior: reject invalid or missing IDs with an appropriate HTTP exception rather than returning ambiguous values. - Ensure the pipe remains aligned with the users data structure used by the host-array integration. ## Relationships - DEPENDS_ON β†’ `usersservice` # KafkaJSDeleteGroupsErrorGroups **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1265) `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. # KafkaJSStaleTopicMetadataAssignment **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1206) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `topic` | `string` | | `unknownPartitions` | `number` | # overridePartialV1 **Kind:** API Endpoint **Source:** [`integration/versioning/src/override-partial.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/override-partial.controller.ts#L7) ## Endpoint `GET /override-partial` ## Referenced By - `OverridePartialController` (MODULE_DECLARES) # PostsModule **Kind:** Module **Source:** [`sample/22-graphql-prisma/src/posts/posts.module.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/posts/posts.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `PrismaModule` - MODULE_PROVIDES β†’ `PostsResolvers` - MODULE_PROVIDES β†’ `postsservice` # RMQ_WILDCARD_SINGLE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L25) ## Definition ```ts '*' ``` ## Value ```ts '*' ``` # 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) ## Signature ```ts function RouteSchema(schema: FastifySchema) ``` ## Parameters | Name | Type | |---|---| | `schema` | `FastifySchema` | # 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) ## Definition ```ts Transport | symbol ``` # UsersService **Kind:** Service **Source:** [`integration/inspector/src/circular-hello/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/users/users.service.ts#L3) `UsersService` is a NestJS backend service responsible for retrieving user data by identifier through its `findById()` method. It belongs to the circular hello integration example and is intended to be injected into controllers or other services that need user lookup functionality. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Service participant UsersService participant UserStore as User Data Source Consumer->>UsersService: findById(userId) UsersService->>UserStore: Look up user by ID UserStore-->>UsersService: User result UsersService-->>Consumer: Return user ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class ProfileService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor injection rather than constructing it manually. - Use `findById()` as the single user lookup entry point so callers remain independent of the underlying data source. - Confirm the expected identifier type and return value before adding consumers, since `findById()` is currently typed as `unknown`. - Handle missing-user behavior consistently at the controller or calling-service boundary. - Keep imports aligned with the `users` module so NestJS can resolve the provider correctly. # KafkaJSDeleteTopicRecordsErrorPartition **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1276) `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. # 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) `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. # overridePartialV2 **Kind:** API Endpoint **Source:** [`integration/versioning/src/override-partial.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/override-partial.controller.ts#L12) ## Endpoint `GET /override-partial` ## Referenced By - `OverridePartialController` (MODULE_DECLARES) # RecipesModule **Kind:** Module **Source:** [`sample/23-graphql-code-first/src/recipes/recipes.module.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/recipes/recipes.module.ts#L6) ## Relationships - MODULE_PROVIDES β†’ `recipesresolver` - MODULE_PROVIDES β†’ `recipesservice` - MODULE_PROVIDES β†’ `datescalar` # Roles **Kind:** Constant **Source:** [`sample/01-cats-app/src/common/decorators/roles.decorator.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/decorators/roles.decorator.ts#L3) ## Definition ```ts Reflector.createDecorator() ``` ## Value ```ts Reflector.createDecorator() ``` # 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) ## Signature ```ts function SerializeOptions(options: ClassSerializerContextOptions) ``` ## Parameters | Name | Type | |---|---| | `options` | `ClassSerializerContextOptions` | # User **Kind:** Type **Source:** [`sample/19-auth-jwt/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/users/users.service.ts#L4) ## Definition ```ts any ``` # UsersService **Kind:** Service **Source:** [`integration/scopes/src/circular-hello/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/users/users.service.ts#L3) `UsersService` is a NestJS provider responsible for user-related operations within the circular hello integration scope. It exposes `findById()` as the service entry point for resolving a user by identifier and can be injected into controllers or other services through NestJS dependency injection. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller/Service participant UsersService as UsersService participant UserStore as User Data Source Consumer->>UsersService: findById(id) UsersService->>UserStore: Look up user by id UserStore-->>UsersService: User or undefined UsersService-->>Consumer: User result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class ProfileService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); if (!user) { throw new Error(`User not found: ${userId}`); } return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor injection rather than creating it with `new`. - Use `findById()` as the boundary for user lookup logic; keep persistence details inside the users domain. - Handle missing or undefined results at the caller boundary, such as in a controller or application service. - Ensure the module that consumes this service imports the module that provides and exports `UsersService`. - Preserve circular-scope integration boundaries; avoid importing unrelated feature modules directly into this service. # 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) `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. # 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) `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. # overrideV1 **Kind:** API Endpoint **Source:** [`integration/versioning/src/override.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/override.controller.ts#L5) ## Endpoint `GET /override` ## Referenced By - `OverrideController` (MODULE_DECLARES) # RecipesModule **Kind:** Module **Source:** [`sample/33-graphql-mercurius/src/recipes/recipes.module.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/recipes/recipes.module.ts#L6) ## Relationships - MODULE_PROVIDES β†’ `recipesresolver` - MODULE_PROVIDES β†’ `recipesservice` - MODULE_PROVIDES β†’ `datescalar` # Roles **Kind:** Constant **Source:** [`sample/36-hmr-esm/src/common/decorators/roles.decorator.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/decorators/roles.decorator.ts#L3) ## Definition ```ts Reflector.createDecorator() ``` ## Value ```ts Reflector.createDecorator() ``` # stripEndSlash **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L40) ## Signature ```ts function stripEndSlash(path: string) ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | # UsersService **Kind:** Service **Source:** [`integration/scopes/src/circular-transient/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/users/users.service.ts#L3) `UsersService` is a NestJS service responsible for retrieving user data within the circular transient integration scope. Its `findById()` method provides the lookup entry point used by collaborating providers while preserving Nest's dependency-injection lifecycle. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Injecting Provider participant UsersService participant UserStore as User Data Source Consumer->>UsersService: findById(userId) UsersService->>UserStore: retrieve user by ID UserStore-->>UsersService: user result UsersService-->>Consumer: user result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class ProfileService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor injection; do not instantiate it directly with `new`. - Use `findById()` as the central user lookup API rather than duplicating lookup logic in consuming services. - Preserve the service's configured provider scope when adding dependencies, especially in circular/transient dependency scenarios. - Ensure any module consuming `UsersService` imports the module that provides and exports it. - Handle the result of `findById()` according to the application's user-not-found conventions. # WritableHeaderStream **Kind:** Type **Source:** [`packages/core/router/sse-stream.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/sse-stream.ts#L58) ## Definition ```ts NodeJS.WritableStream & WriteHeaders ``` # 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) `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. # OrderCreatedListener **Kind:** Class **Source:** [`sample/30-event-emitter/src/orders/listeners/order-created.listener.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/listeners/order-created.listener.ts#L5) `OrderCreatedListener` handles order-created events emitted by the orders domain. Its `handleOrderCreatedEvent()` method receives the event payload and performs the listener-specific follow-up work, keeping event consumers decoupled from the code that creates orders. ## Methods | Method | Signature | Returns | |---|---|---| | `handleOrderCreatedEvent` | `handleOrderCreatedEvent(event: OrderCreatedEvent)` | `void` | ## Diagram ```mermaid graph LR A[Order service] -->|emit order.created| B[Event emitter] B --> C[OrderCreatedListener] C -->|handleOrderCreatedEvent| D[Follow-up processing] ``` ## Usage ```ts import { EventEmitter2 } from '@nestjs/event-emitter'; import { OrderCreatedListener } from './listeners/order-created.listener'; const eventEmitter = new EventEmitter2(); const listener = new OrderCreatedListener(); // Register the listener when wiring the application manually. eventEmitter.on('order.created', listener.handleOrderCreatedEvent.bind(listener)); // Emit an event after an order is created. eventEmitter.emit('order.created', { orderId: 'order-123', customerId: 'customer-456', }); ``` ## AI Coding Instructions - Keep order-creation side effects in event listeners rather than adding them directly to the order creation flow. - Ensure the event name and payload shape match the event emitted by the orders service. - Preserve the listener method signature when changing event payloads, and update all emitters and consumers together. - Bind `handleOrderCreatedEvent` when registering it manually so the listener retains its class context. - Make event handling resilient to duplicate deliveries and failures where downstream work may be retried. ## Referenced By - `OrdersModule` (MODULE_PROVIDES) # overrideV2 **Kind:** API Endpoint **Source:** [`integration/versioning/src/override.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/override.controller.ts#L11) ## Endpoint `GET /override` ## Referenced By - `OverrideController` (MODULE_DECLARES) # RequestChainModule **Kind:** Module **Source:** [`integration/inspector/src/request-chain/request-chain.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/request-chain/request-chain.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `helpermodule` - MODULE_DECLARES β†’ `requestchaincontroller` - MODULE_PROVIDES β†’ `requestchainservice` # ROUTE_ARGS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L18) ## Definition ```ts '__routeArguments__' ``` ## Value ```ts '__routeArguments__' ``` # 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) 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. # UsersService **Kind:** Service **Source:** [`integration/scopes/src/hello/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/users/users.service.ts#L3) `UsersService` is a NestJS service responsible for user-related lookup operations within the `hello` integration scope. Its `findById()` method provides the service boundary for retrieving a user by identifier, allowing controllers or other providers to depend on a dedicated user-access abstraction. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller / Service participant UsersService participant UserStore as User Data Source Consumer->>UsersService: findById(id) UsersService->>UserStore: Lookup user by ID UserStore-->>UsersService: User result UsersService-->>Consumer: User result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class GreetingService { constructor(private readonly usersService: UsersService) {} async getGreeting(userId: string) { const user = await this.usersService.findById(userId); return { message: `Hello, ${user.name}!`, user, }; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor dependency injection; do not instantiate it with `new`. - Keep user lookup logic inside `findById()` rather than duplicating data-access code in controllers. - Define and return a concrete user type instead of leaving `findById()` as `unknown` when implementing the service. - Handle missing users consistently, such as returning `null` or throwing NestJS's `NotFoundException`. - Register `UsersService` in its NestJS module's `providers` array and export it when other modules need access. # isConstructor **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L47) ## Signature ```ts function isConstructor(val: any): boolean ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `boolean` # LoggerEntryContent **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L633) `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. # paramV1 **Kind:** API Endpoint **Source:** [`integration/inspector/src/app-v2.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app-v2.controller.ts#L12) ## Endpoint `GET /:param/hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `param` | path | `string` | βœ“ | | ## Referenced By - `AppV2Controller` (MODULE_DECLARES) # RequestChainModule **Kind:** Module **Source:** [`integration/scopes/src/request-chain/request-chain.module.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/request-chain/request-chain.module.ts#L6) ## Relationships - MODULE_IMPORTS β†’ `helpermodule` - MODULE_DECLARES β†’ `requestchaincontroller` - MODULE_PROVIDES β†’ `requestchainservice` # ROUTES **Kind:** Constant **Source:** [`packages/core/router/router-module.ts`](https://github.com/nestjs/nest/blob/master/packages/core/router/router-module.ts#L9) ## Definition ```ts Symbol('ROUTES') ``` ## Value ```ts Symbol('ROUTES') ``` # ServerFactory **Kind:** Class **Source:** [`packages/microservices/server/server-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-factory.ts#L20) `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) # UsersService **Kind:** Service **Source:** [`integration/scopes/src/msvc/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/users/users.service.ts#L3) `UsersService` is a NestJS backend service responsible for user-related lookup operations within the users microservice scope. Its `findById()` method provides a central integration point for retrieving a user by identifier, allowing controllers or other services to avoid direct data-access coupling. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as UsersController participant Service as UsersService participant Store as User Repository/Data Source Client->>Controller: GET /users/:id Controller->>Service: findById(id) Service->>Store: Query user by ID Store-->>Service: User record or no result Service-->>Controller: User result Controller-->>Client: User response ``` ## Usage ```ts import { Injectable, NotFoundException } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class ProfilesService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); if (!user) { throw new NotFoundException(`User ${userId} was not found`); } return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor injection rather than creating it manually. - Use `findById()` as the shared user lookup abstraction; do not bypass it with direct repository or database calls from consumers. - Handle missing or invalid user IDs at the calling boundary, typically by returning or throwing an appropriate NestJS HTTP exception. - Keep `findById()` focused on retrieval responsibilities; place authorization, response shaping, and transport-specific logic in controllers or dedicated services. # isEmpty **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L50) ## Signature ```ts function isEmpty(array: any): boolean ``` ## Parameters | Name | Type | |---|---| | `array` | `any` | **Returns:** `boolean` # ModuleFactory **Kind:** Interface **Source:** [`packages/core/injector/compiler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/compiler.ts#L8) `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. # paramV1 **Kind:** API Endpoint **Source:** [`integration/inspector/src/app-v1.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/app-v1.controller.ts#L12) ## Endpoint `GET /:param/hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `param` | path | `string` | βœ“ | | ## Referenced By - `AppV1Controller` (MODULE_DECLARES) # RequestLazyModule **Kind:** Module **Source:** [`integration/lazy-modules/src/request.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/request.module.ts#L6) ## Relationships - MODULE_PROVIDES β†’ `RequestService` - MODULE_PROVIDES β†’ `GlobalService` - MODULE_PROVIDES β†’ `EagerService` - MODULE_EXPORTS β†’ `RequestService` # 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) ## Definition ```ts false ``` ## Value ```ts false ``` # UsersRepository **Kind:** Class **Source:** [`integration/repl/src/users/users.repository.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.repository.ts#L3) `UsersRepository` provides user-focused data access for the REPL integration. Its `find()` method retrieves user records, allowing callers to access user data without coupling directly to the underlying persistence implementation. ## Methods | Method | Signature | Returns | |---|---|---| | `find` | `find()` | `void` | ## Diagram ```mermaid graph LR REPL[REPL command or service] --> Repository[UsersRepository] Repository --> Find[find()] Find --> Storage[User data source] Storage --> Users[User records] ``` ## Usage ```ts import { UsersRepository } from "./users.repository"; async function listUsers(usersRepository: UsersRepository) { const users = await usersRepository.find(); console.log(users); return users; } ``` ## AI Coding Instructions - Use `UsersRepository` as the boundary for user-data retrieval instead of accessing persistence code directly. - Call `find()` asynchronously and handle any errors at the calling service or command layer. - Keep REPL-specific formatting and output logic outside the repository. - Add new user query methods to this repository when they represent reusable data-access behavior. ## Referenced By - `UsersService` (DEPENDS_ON) # UsersService **Kind:** Service **Source:** [`integration/scopes/src/transient/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/users/users.service.ts#L3) `UsersService` is a NestJS service responsible for retrieving user data within the transient scope integration. Its `findById()` method provides a focused lookup boundary that controllers or other services can use without coupling directly to user storage details. The service participates in the backend dependency-injection layer and should be consumed through NestJS constructor injection. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Consumer as Controller / Service participant UsersService participant UserStore as User Data Source Consumer->>UsersService: findById(userId) UsersService->>UserStore: Lookup user by ID UserStore-->>UsersService: User result UsersService-->>Consumer: User result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class ProfileService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor injection; do not instantiate it with `new`. - Use `findById()` as the user lookup boundary instead of accessing user persistence or transient scope state directly. - Preserve the method's existing return and error-handling behavior when extending callers, since its current return type is unspecified. - Keep user-specific business rules in appropriate domain services or guards rather than duplicating lookup logic in controllers. - Ensure the module that consumes `UsersService` imports the module that provides and exports it. # ExternalErrorProxy **Kind:** Class **Source:** [`packages/core/helpers/external-proxy.ts`](https://github.com/nestjs/nest/blob/master/packages/core/helpers/external-proxy.ts#L5) `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] # isNumber **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L46) ## Signature ```ts function isNumber(val: any): val is number ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is number` # 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) `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. # paramV1 **Kind:** API Endpoint **Source:** [`integration/versioning/src/app-v1.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app-v1.controller.ts#L12) ## Endpoint `GET /:param/hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `param` | path | `string` | βœ“ | | ## Referenced By - `AppV1Controller` (MODULE_DECLARES) # RQM_DEFAULT_NO_ASSERT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L23) ## Definition ```ts false ``` ## Value ```ts false ``` # SelfInjectionForwardProviderModule **Kind:** Module **Source:** [`integration/injector/src/self-injection/self-injection-provider.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/self-injection/self-injection-provider.module.ts#L26) ## Relationships - MODULE_PROVIDES β†’ `ServiceInjectingItselfForward` # UsersService **Kind:** Service **Source:** [`sample/31-graphql-federation-code-first/users-application/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/users-application/src/users/users.service.ts#L4) `UsersService` is a NestJS application service responsible for retrieving user records in the users subgraph of the code-first GraphQL Federation example. Its `findById()` method provides the lookup behavior used by GraphQL resolvers and federation entity resolution to locate a `User` by identifier. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: number)` | `User` | ## Diagram ```mermaid sequenceDiagram participant Client as Federated Gateway / Client participant Resolver as UsersResolver participant Service as UsersService participant Store as User Data Store Client->>Resolver: Request User by id Resolver->>Service: findById(id) Service->>Store: Find matching user Store-->>Service: User record Service-->>Resolver: User Resolver-->>Client: User response ``` ## Usage ```ts import { Injectable, NotFoundException } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class UsersResolver { constructor(private readonly usersService: UsersService) {} async user(id: string) { const user = this.usersService.findById(id); if (!user) { throw new NotFoundException(`User ${id} was not found`); } return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor dependency injection; do not instantiate it directly. - Use `findById(id)` as the canonical user lookup path for resolvers and GraphQL Federation entity reference resolution. - Preserve the service return contract: callers should handle the possibility that no matching user is found. - Keep GraphQL-specific decorators and response shaping in resolvers; keep lookup and user-data access logic in this service. - When replacing in-memory data with a database or external API, retain the `findById()` interface to avoid breaking resolver integrations. # isString **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L45) ## Signature ```ts function isString(val: any): val is string ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is string` # 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) `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. # 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) `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()`. # paramV1 **Kind:** API Endpoint **Source:** [`integration/versioning/src/app-v2.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/versioning/src/app-v2.controller.ts#L12) ## Endpoint `GET /:param/hello` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `param` | path | `string` | βœ“ | | ## Referenced By - `AppV2Controller` (MODULE_DECLARES) # RQM_DEFAULT_NOACK **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L21) ## Definition ```ts true ``` ## Value ```ts true ``` # SelfInjectionProviderModule **Kind:** Module **Source:** [`integration/injector/src/self-injection/self-injection-provider.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/self-injection/self-injection-provider.module.ts#L21) ## Relationships - MODULE_PROVIDES β†’ `ServiceInjectingItself` # UsersService **Kind:** Service **Source:** [`sample/32-graphql-federation-schema-first/users-application/src/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/users-application/src/users/users.service.ts#L3) `UsersService` is a NestJS application service responsible for retrieving user records within the users application. It exposes `findById()` for resolving a user by identifier, typically supporting GraphQL federation entity resolution and user-related API operations. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: number)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Resolver as GraphQL Resolver participant Service as UsersService participant Store as User Data Store Resolver->>Service: findById(id) Service->>Store: Look up user by ID Store-->>Service: User record or undefined Service-->>Resolver: User result ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class UsersResolver { constructor(private readonly usersService: UsersService) {} async user(id: string) { return this.usersService.findById(id); } } ``` ## AI Coding Instructions - Keep user lookup logic centralized in `UsersService`; resolvers should delegate retrieval rather than access data directly. - Preserve the `findById()` contract when adding persistence or caching layers, including behavior for missing users. - Use this service when implementing GraphQL federation reference resolution for `User` entities. - Add explicit return types and DTO/entity types when replacing the current `unknown` return type. # isSymbol **Kind:** Function **Source:** [`packages/common/utils/shared.utils.ts`](https://github.com/nestjs/nest/blob/master/packages/common/utils/shared.utils.ts#L51) ## Signature ```ts function isSymbol(val: any): val is symbol ``` ## Parameters | Name | Type | |---|---| | `val` | `any` | **Returns:** `val is symbol` # MiddlewareResolver **Kind:** Class **Source:** [`packages/core/middleware/resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/resolver.ts#L7) `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. # PartitionerArgs **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L129) `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) # postTest **Kind:** API Endpoint **Source:** [`integration/nest-application/global-prefix/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/global-prefix/src/app.controller.ts#L25) ## Endpoint `POST /test` ## Referenced By - `AppController` (MODULE_DECLARES) # RQM_DEFAULT_PERSISTENT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L22) ## Definition ```ts false ``` ## Value ```ts false ``` # TransientLazyModule **Kind:** Module **Source:** [`integration/lazy-modules/src/transient.module.ts`](https://github.com/nestjs/nest/blob/master/integration/lazy-modules/src/transient.module.ts#L6) ## Relationships - MODULE_PROVIDES β†’ `transientservice` - MODULE_PROVIDES β†’ `GlobalService` - MODULE_PROVIDES β†’ `EagerService` - MODULE_EXPORTS β†’ `transientservice` # UsersService **Kind:** Service **Source:** [`integration/hello-world/src/hello/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/users/users.service.ts#L3) `UsersService` provides user-related application logic for the Hello World NestJS integration. Its `findById()` method is the service entry point for retrieving a user by identifier, typically called by controllers or other services rather than accessed directly from HTTP handlers. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant Controller as UsersController participant Service as UsersService Client->>Controller: GET /users/:id Controller->>Service: findById(id) Service-->>Controller: User result Controller-->>Client: HTTP response ``` ## Usage ```ts import { Injectable, NotFoundException } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class UsersController { constructor(private readonly usersService: UsersService) {} async getUser(id: string) { const user = await this.usersService.findById(id); if (!user) { throw new NotFoundException(`User ${id} was not found`); } return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor dependency injection; avoid manually instantiating it with `new`. - Keep HTTP-specific concerns, such as request parsing and response status codes, in controllers rather than in the service. - Define and maintain a concrete return type for `findById()` as user model details become available. - Handle missing-user behavior consistently, either by returning `null`/`undefined` or throwing a NestJS exception according to the surrounding application pattern. - Register the service in its NestJS module providers and export it if other modules need to consume it. # 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` # 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) `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. # remove **Kind:** API Endpoint **Source:** [`integration/inspector/src/database/database.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.controller.ts#L41) ## Endpoint `DELETE /database/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `DatabaseController` (MODULE_DECLARES) # 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) # RQM_DEFAULT_PREFETCH_COUNT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L18) ## Definition ```ts 0 ``` ## Value ```ts 0 ``` # UsersModule **Kind:** Module **Source:** [`sample/05-sql-typeorm/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `userscontroller` - MODULE_PROVIDES β†’ `usersservice` # UsersService **Kind:** Service **Source:** [`integration/hello-world/src/host/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/users/users.service.ts#L3) `UsersService` is a NestJS backend service responsible for user-related business logic. Its `findById()` method provides a central integration point for retrieving a user by identifier, typically for use by controllers, guards, or other application services. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant UsersController participant UsersService participant UserRepository Client->>UsersController: GET /users/:id UsersController->>UsersService: findById(id) UsersService->>UserRepository: Look up user by ID UserRepository-->>UsersService: User record or no result UsersService-->>UsersController: User result UsersController-->>Client: User response ``` ## Usage ```ts import { Injectable, NotFoundException } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class ProfileService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); if (!user) { throw new NotFoundException(`User ${userId} was not found`); } return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor dependency injection; do not instantiate it directly. - Keep user lookup and user-domain business logic inside this service rather than duplicating it in controllers. - Treat the current `findById()` return type as unknown until its concrete repository, DTO, or entity contract is established. - Handle missing-user results consistently at the appropriate boundary, such as with a `NotFoundException` in a controller-facing service. - Update related modules and provider exports when introducing dependencies used by `UsersService`. # 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) `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. # remove **Kind:** API Endpoint **Source:** [`integration/inspector/src/dogs/dogs.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.controller.ts#L38) ## Endpoint `DELETE /dogs/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `DogsController` (MODULE_DECLARES) # ResourceConfigQuery **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L343) `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) # RQM_DEFAULT_QUEUE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L17) ## Definition ```ts '' ``` ## Value ```ts '' ``` # UsersModule **Kind:** Module **Source:** [`sample/07-sequelize/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.module.ts#L7) ## Relationships - MODULE_DECLARES β†’ `userscontroller` - MODULE_PROVIDES β†’ `usersservice` # UsersService **Kind:** Service **Source:** [`integration/hello-world/src/host-array/users/users.service.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/users/users.service.ts#L3) `UsersService` is a NestJS backend service responsible for retrieving user-related data. It exposes `findById()` as the primary lookup method and is intended to be injected into controllers or other services that need to resolve a user by identifier. ## Methods | Method | Signature | Returns | |---|---|---| | `findById` | `findById(id: string)` | `unknown` | ## Diagram ```mermaid sequenceDiagram participant Client participant UsersController participant UsersService Client->>UsersController: GET /users/:id UsersController->>UsersService: findById(id) UsersService-->>UsersController: User data or undefined UsersController-->>Client: User response ``` ## Usage ```ts import { Injectable } from '@nestjs/common'; import { UsersService } from './users/users.service'; @Injectable() export class ProfileService { constructor(private readonly usersService: UsersService) {} async getProfile(userId: string) { const user = await this.usersService.findById(userId); if (!user) { throw new Error(`User not found: ${userId}`); } return user; } } ``` ## AI Coding Instructions - Inject `UsersService` through NestJS constructor injection instead of creating it with `new`. - Use `findById()` as the central user lookup integration point; keep controller logic focused on request handling. - Handle missing or unknown results explicitly before accessing user properties. - Preserve the existing return contract of `findById()` when adding repositories, DTOs, or persistence logic. - Register `UsersService` in its NestJS module providers before injecting it into other application components. # 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) 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`. # CoreService **Kind:** Service **Source:** [`integration/injector/src/inject/inject-same-name.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/inject/inject-same-name.module.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CoreService client->>+p1: CoreService p1-->client: return response ``` # createClient **Kind:** Function **Source:** [`packages/microservices/test/json-socket/helpers.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/test/json-socket/helpers.ts#L25) ## Signature ```ts function createClient(server: Server, callback: ( err?: any, clientSocket?: JsonSocket, serverSocket?: JsonSocket, ) => void) ``` ## Parameters | Name | Type | |---|---| | `server` | `Server` | | `callback` | `( err?: any, clientSocket?: JsonSocket, serverSocket?: JsonSocket, ) => void` | # remove **Kind:** API Endpoint **Source:** [`integration/inspector/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.controller.ts#L38) ## Endpoint `DELETE /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) `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) # 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) `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. # RQM_DEFAULT_QUEUE_OPTIONS **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L20) ## Definition ```ts {} ``` ## Value ```ts {} ``` # UsersModule **Kind:** Module **Source:** [`integration/inspector/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.module.ts#L5) ## Relationships - MODULE_DECLARES β†’ `userscontroller` - MODULE_PROVIDES β†’ `usersservice` # CoreService **Kind:** Service **Source:** [`integration/injector/src/defaults/core.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/defaults/core.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CoreService client->>+p1: CoreService p1-->client: return response ``` # 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) 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. # remove **Kind:** API Endpoint **Source:** [`integration/repl/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.controller.ts#L38) ## Endpoint `DELETE /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) `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] # 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) `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] # RQM_DEFAULT_URL **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L10) ## Definition ```ts 'amqp://localhost' ``` ## Value ```ts 'amqp://localhost' ``` # UsersModule **Kind:** Module **Source:** [`sample/19-auth-jwt/src/users/users.module.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/users/users.module.ts#L4) ## Relationships - MODULE_PROVIDES β†’ `usersservice` - MODULE_EXPORTS β†’ `usersservice` # CoreInjectablesModule **Kind:** Module **Source:** [`integration/injector/src/core-injectables/core-injectables.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/core-injectables/core-injectables.module.ts#L3) # CoreService **Kind:** Service **Source:** [`integration/injector/src/inject/core.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/inject/core.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CoreService client->>+p1: CoreService p1-->client: return response ``` # remove **Kind:** API Endpoint **Source:** [`sample/05-sql-typeorm/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/users.controller.ts#L33) ## Endpoint `DELETE /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) `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. # 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' ``` # upperDirectiveTransformer **Kind:** Function **Source:** [`sample/12-graphql-schema-first/src/common/directives/upper-case.directive.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/common/directives/upper-case.directive.ts#L4) ## Signature ```ts function upperDirectiveTransformer(schema: GraphQLSchema, directiveName: string) ``` ## Parameters | Name | Type | |---|---| | `schema` | `GraphQLSchema` | | `directiveName` | `string` | # 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) `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. # CoreService **Kind:** Service **Source:** [`integration/inspector/src/defaults/core.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/defaults/core.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ CoreService client->>+p1: CoreService p1-->client: return response ``` # 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) `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) # remove **Kind:** API Endpoint **Source:** [`sample/07-sequelize/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/users.controller.ts#L25) ## Endpoint `DELETE /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # 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) `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] # SCOPE_OPTIONS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L16) ## Definition ```ts 'scope:options' ``` ## Value ```ts 'scope:options' ``` # upperDirectiveTransformer **Kind:** Function **Source:** [`sample/23-graphql-code-first/src/common/directives/upper-case.directive.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/common/directives/upper-case.directive.ts#L4) ## Signature ```ts function upperDirectiveTransformer(schema: GraphQLSchema, directiveName: string) ``` ## Parameters | Name | Type | |---|---| | `schema` | `GraphQLSchema` | | `directiveName` | `string` | # createServerAndClient **Kind:** Function **Source:** [`packages/microservices/test/json-socket/helpers.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/test/json-socket/helpers.ts#L53) ## Signature ```ts function createServerAndClient(callback: ( err?: any, server?: Server, clientSocket?: JsonSocket, serverSocket?: JsonSocket, ) => void) ``` ## Parameters | Name | Type | |---|---| | `callback` | `( err?: any, server?: Server, clientSocket?: JsonSocket, serverSocket?: JsonSocket, ) => void` | # DependencyService **Kind:** Service **Source:** [`integration/injector/src/properties/dependency.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/properties/dependency.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ DependencyService client->>+p1: DependencyService p1-->client: return response ``` # 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) `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. # root **Kind:** API Endpoint **Source:** [`sample/15-mvc/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/15-mvc/src/app.controller.ts#L5) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # 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) 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. # 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) `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. # DependencyService **Kind:** Service **Source:** [`integration/inspector/src/properties/dependency.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/properties/dependency.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ DependencyService client->>+p1: DependencyService p1-->client: return response ``` # 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) # KafkaJSOffsetOutOfRange **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1164) **Extends:** `KafkaJSProtocolError` ## Properties | Property | Type | |---|---| | `topic` | `string` | | `partition` | `number` | # root **Kind:** API Endpoint **Source:** [`sample/17-mvc-fastify/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/17-mvc-fastify/src/app.controller.ts#L5) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # SELF_DECLARED_DEPS_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L12) ## Definition ```ts 'self:paramtypes' ``` ## Value ```ts 'self:paramtypes' ``` # 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) `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] # BaseWsInstance **Kind:** Interface **Source:** [`packages/websockets/adapters/ws-adapter.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/adapters/ws-adapter.ts#L8) `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. # InputService **Kind:** Service **Source:** [`integration/injector/src/circular-structure-dynamic-module/input.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-structure-dynamic-module/input.service.ts#L3) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ InputService client->>+p1: InputService p1-->client: return response ``` # KafkaJSProtocolError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1158) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `code` | `number` | | `type` | `string` | # range **Kind:** Function **Source:** [`packages/microservices/test/json-socket/helpers.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/test/json-socket/helpers.ts#L76) ## Signature ```ts function range(start: number, end: number) ``` ## Parameters | Name | Type | |---|---| | `start` | `number` | | `end` | `number` | # root **Kind:** API Endpoint **Source:** [`tools/benchmarks/src/frameworks/nest/app.controller.ts`](https://github.com/nestjs/nest/blob/master/tools/benchmarks/src/frameworks/nest/app.controller.ts#L5) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # 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' ``` # ClientProperties **Kind:** Interface **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L16) `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. # 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) `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. # RequestLoggerService **Kind:** Service **Source:** [`integration/scopes/src/resolve-scoped/request-logger.service.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/resolve-scoped/request-logger.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ RequestLoggerService participant p2 as βš™οΈ LoggerService client->>+p1: RequestLoggerService p1->>+p2: LoggerService p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `LoggerService` # sayHello **Kind:** API Endpoint **Source:** [`sample/29-file-upload/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/app.controller.ts#L19) ## Endpoint `GET /` ## Referenced By - `AppController` (MODULE_DECLARES) # sendHttpRequest **Kind:** Function **Source:** [`integration/send-files/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/e2e/utils.ts#L27) ## Signature ```ts async function sendHttpRequest(url: URL) ``` ## Parameters | Name | Type | |---|---| | `url` | `URL` | # SSE_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L42) ## Definition ```ts '__sse__' ``` ## Value ```ts '__sse__' ``` # Ack **Kind:** Function **Source:** [`packages/websockets/decorators/ack.decorator.ts`](https://github.com/nestjs/nest/blob/master/packages/websockets/decorators/ack.decorator.ts#L26) 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. # 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) `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. # ReplLogger **Kind:** Class **Source:** [`packages/core/repl/repl-logger.ts`](https://github.com/nestjs/nest/blob/master/packages/core/repl/repl-logger.ts#L6) `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) # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L119) ## Endpoint `POST /notify` ## Referenced By - `AppController` (MODULE_DECLARES) # STATIC_FACTORY **Kind:** Constant **Source:** [`integration/injector/src/scoped/scoped.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/scoped.module.ts#L8) ## Definition ```ts 'STATIC_FACTORY' ``` ## Value ```ts 'STATIC_FACTORY' ``` # TransientService **Kind:** Service **Source:** [`integration/injector/src/scoped/transient.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/transient.service.ts#L4) ## Diagram ```mermaid sequenceDiagram participant client as 🌐 Client participant p1 as βš™οΈ TransientService participant p2 as βš™οΈ Transient2Service client->>+p1: TransientService p1->>+p2: Transient2Service p2-->-p1: return p1-->client: return response ``` ## Relationships - DEPENDS_ON β†’ `Transient2Service` # createServer **Kind:** Function **Source:** [`packages/microservices/test/json-socket/helpers.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/test/json-socket/helpers.ts#L12) ## Signature ```ts function createServer(callback: (err?: any, server?: Server) => void) ``` ## Parameters | Name | Type | |---|---| | `callback` | `(err?: any, server?: Server) => void` | # 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) `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. # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/kafka/kafka.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/kafka.controller.ts#L131) ## Endpoint `POST /notify` ## Referenced By - `KafkaController` (MODULE_DECLARES) # 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) `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) # SYMBOL_TOKEN **Kind:** Constant **Source:** [`integration/injector/src/properties/properties.service.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/properties/properties.service.ts#L4) ## Definition ```ts Symbol('token') ``` ## Value ```ts Symbol('token') ``` # 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) `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. # fetchInterceptorDelayedSseStats **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L80) ## Signature ```ts async function fetchInterceptorDelayedSseStats(appUrl: string): Promise ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | **Returns:** `Promise` # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L64) ## Endpoint `POST /notify` ## Referenced By - `MqttController` (MODULE_DECLARES) # SYMBOL_TOKEN **Kind:** Constant **Source:** [`integration/inspector/src/properties/properties.service.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/properties/properties.service.ts#L4) ## Definition ```ts Symbol('token') ``` ## Value ```ts Symbol('token') ``` # 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) **Extends:** `RuntimeException` ## Properties | Property | Type | |---|---| | `moduleRef` | `{ id: string } | undefined` | # DeleteAclResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L497) `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) # getAvailableIpv4Host **Kind:** Function **Source:** [`integration/nest-application/get-url/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/e2e/utils.ts#L19) ## Signature ```ts async function getAvailableIpv4Host(preferredHost): Promise ``` ## Parameters | Name | Type | |---|---| | `preferredHost` | `any` | **Returns:** `Promise` # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L121) ## Endpoint `POST /notify` ## Referenced By - `NatsController` (MODULE_DECLARES) # TCP_DEFAULT_HOST **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L4) ## Definition ```ts 'localhost' ``` ## Value ```ts 'localhost' ``` # UuidFactory **Kind:** Class **Source:** [`packages/core/inspector/uuid-factory.ts`](https://github.com/nestjs/nest/blob/master/packages/core/inspector/uuid-factory.ts#L9) `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] # DescriptionAndOptions **Kind:** Interface **Source:** [`packages/common/exceptions/http.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts#L14) `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. # 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) 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. # releaseInterceptorDelayedSse **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L89) ## Signature ```ts async function releaseInterceptorDelayedSse(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/redis/redis.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis.controller.ts#L69) ## Endpoint `POST /notify` ## Referenced By - `RedisController` (MODULE_DECLARES) # TCP_DEFAULT_PORT **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L3) ## Definition ```ts 3000 ``` ## Value ```ts 3000 ``` # 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) `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) # 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) `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. # releasePromiseDelayedSse **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L19) ## Signature ```ts async function releasePromiseDelayedSse(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L132) ## Endpoint `POST /notify` ## Referenced By - `RMQController` (MODULE_DECLARES) # TRANSIENT_SCOPED_FACTORY **Kind:** Constant **Source:** [`integration/injector/src/scoped/scoped.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/scoped/scoped.module.ts#L10) ## Definition ```ts 'TRANSIENT_SCOPED_FACTORY' ``` ## Value ```ts 'TRANSIENT_SCOPED_FACTORY' ``` # 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) `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] # 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) `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) # run **Kind:** Function **Source:** [`tools/benchmarks/src/autocannon/run.ts`](https://github.com/nestjs/nest/blob/master/tools/benchmarks/src/autocannon/run.ts#L17) Runs an autocannon benchmark. By default this is quiet (no live table/progress). Pass `{ verbose: true }` to enable `autocannon.track(...)` output. `run` executes an `autocannon` HTTP benchmark using the provided benchmark options and returns the resulting benchmark data. It runs quietly by default to keep automated benchmark output clean, but can enable `autocannon.track(...)` live progress output when `{ verbose: true }` is supplied. ## Signature ```ts function run(options: RunOptions) ``` ## Parameters | Name | Type | |---|---| | `options` | `RunOptions` | ## Diagram ```mermaid graph LR A[Benchmark configuration] --> B[run options] B --> C[run()] C --> D[autocannon benchmark] D --> E[Benchmark results] B -->|verbose: true| F[autocannon.track progress output] C -. quiet by default .-> D ``` ## Usage ```ts import { run } from './run'; const result = await run({ url: 'http://localhost:3000/api/health', connections: 10, duration: 15, verbose: true, }); console.log({ requestsPerSecond: result.requests.average, latencyMs: result.latency.average, }); ``` ## AI Coding Instructions - Keep `run` quiet by default so benchmark scripts remain suitable for CI and machine-readable output. - Pass `verbose: true` only when interactive progress reporting through `autocannon.track(...)` is useful. - Preserve the underlying `autocannon` options when extending this wrapper; avoid changing benchmark defaults unintentionally. - Await the returned result before reading latency, request-rate, error, or throughput metrics. - Use this function as the shared benchmark entry point rather than invoking `autocannon` directly in individual benchmark scripts. # sendNotification **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L132) ## Endpoint `POST /notify` ## Referenced By - `AppController` (MODULE_DECLARES) # TRANSPORT_METADATA **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L35) ## Definition ```ts 'microservices:transport' ``` ## Value ```ts 'microservices:transport' ``` # 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) `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. # 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) `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. # sendCanceledHttpRequest **Kind:** Function **Source:** [`integration/send-files/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/e2e/utils.ts#L12) ## Signature ```ts async function sendCanceledHttpRequest(url: URL) ``` ## Parameters | Name | Type | |---|---| | `url` | `URL` | # sendSharedWildcardEvent **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L114) ## Endpoint `POST /shared-wildcard-event` ## Referenced By - `MqttController` (MODULE_DECLARES) # UNBLOCKED_RMQ_MESSAGE **Kind:** Constant **Source:** [`packages/microservices/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/constants.ts#L63) ## Definition ```ts 'RMQ broker has unblocked the connection.' ``` ## Value ```ts 'RMQ broker has unblocked the connection.' ``` # IResourceConfigEntry **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L376) `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. # sendSharedWildcardEvent2 **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L127) ## Endpoint `POST /shared-wildcard-event2` ## Referenced By - `MqttController` (MODULE_DECLARES) # Test **Kind:** Class **Source:** [`packages/testing/test.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/test.ts#L8) `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] # UNHANDLED_RUNTIME_EXCEPTION **Kind:** Constant **Source:** [`packages/core/errors/messages.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/messages.ts#L261) ## Definition ```ts `Unhandled Runtime Exception.` ``` ## Value ```ts `Unhandled Runtime Exception.` ``` # waitForInterceptorDelayedSseClose **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L129) ## Signature ```ts async function waitForInterceptorDelayedSseClose(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # ISerializer **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L596) # sendSharedWildcardMessage **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L119) ## Endpoint `POST /shared-wildcard-message` ## Referenced By - `MqttController` (MODULE_DECLARES) # TestingInstanceLoader **Kind:** Class **Source:** [`packages/testing/testing-instance-loader.ts`](https://github.com/nestjs/nest/blob/master/packages/testing/testing-instance-loader.ts#L6) `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] # 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) 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. # waitForInterceptorDelayedSseRequestStart **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L119) ## Signature ```ts async function waitForInterceptorDelayedSseRequestStart(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # ITopicMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L280) `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. # 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) `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) # sendSharedWildcardMessage2 **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L132) ## Endpoint `POST /shared-wildcard-message2` ## Referenced By - `MqttController` (MODULE_DECLARES) # VERSION_METADATA **Kind:** Constant **Source:** [`packages/common/constants.ts`](https://github.com/nestjs/nest/blob/master/packages/common/constants.ts#L43) ## Definition ```ts '__version__' ``` ## Value ```ts '__version__' ``` # waitForInterceptorDelayedSseTeardown **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L137) ## Signature ```ts async function waitForInterceptorDelayedSseTeardown(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `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) 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. # KafkaJSConnectionErrorMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1299) `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. # sendWildcardEvent **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L69) ## Endpoint `POST /wildcard-event` ## Referenced By - `MqttController` (MODULE_DECLARES) # 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) 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. # waitForPromiseDelayedSseClose **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L56) ## Signature ```ts async function waitForPromiseDelayedSseClose(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # 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) 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. # KafkaJSDeleteTopicRecordsErrorTopic **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1271) `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. # sendWildcardEvent2 **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L82) ## Endpoint `POST /wildcard-event2` ## Referenced By - `MqttController` (MODULE_DECLARES) # waitForPromiseDelayedSseRequestStart **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L48) ## Signature ```ts async function waitForPromiseDelayedSseRequestStart(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # Webhook **Kind:** Constant **Source:** [`integration/discovery/src/decorators/webhook.decorators.ts`](https://github.com/nestjs/nest/blob/master/integration/discovery/src/decorators/webhook.decorators.ts#L3) ## Definition ```ts DiscoveryService.createDecorator<{ name: string }>() ``` ## Value ```ts DiscoveryService.createDecorator<{ name: string }>() ``` # ConflictException **Kind:** Class **Source:** [`packages/common/exceptions/conflict.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/conflict.exception.ts#L11) 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. # KafkaJSNumberOfRetriesExceededMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1294) `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. # sendWildcardMessage **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L74) ## Endpoint `POST /wildcard-message` ## Referenced By - `MqttController` (MODULE_DECLARES) # waitForPromiseDelayedSseTeardown **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L64) ## Signature ```ts async function waitForPromiseDelayedSseTeardown(appUrl: string) ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | # ExceptionHandler **Kind:** Class **Source:** [`packages/core/errors/exception-handler.ts`](https://github.com/nestjs/nest/blob/master/packages/core/errors/exception-handler.ts#L3) `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. # fetchPromiseDelayedSseStats **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L12) ## Signature ```ts async function fetchPromiseDelayedSseStats(appUrl: string): Promise ``` ## Parameters | Name | Type | |---|---| | `appUrl` | `string` | **Returns:** `Promise` # KafkaJSOffsetOutOfRangeMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1289) `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. # sendWildcardMessage2 **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L87) ## Endpoint `POST /wildcard-message2` ## Referenced By - `MqttController` (MODULE_DECLARES) # ForbiddenException **Kind:** Class **Source:** [`packages/common/exceptions/forbidden.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/forbidden.exception.ts#L11) 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. # getHttpBaseOptions **Kind:** Function **Source:** [`integration/send-files/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/e2e/utils.ts#L5) ## Signature ```ts async function getHttpBaseOptions(app: INestApplication): Promise ``` ## Parameters | Name | Type | |---|---| | `app` | `INestApplication` | **Returns:** `Promise` # KafkaJSServerDoesNotSupportApiKeyMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1322) `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. # signIn **Kind:** API Endpoint **Source:** [`sample/19-auth-jwt/src/auth/auth.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/auth.controller.ts#L17) ## Endpoint `POST /auth/login` ## Referenced By - `AuthController` (MODULE_DECLARES) # 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) 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. # importEsmPackage **Kind:** Function **Source:** [`sample/34-using-esm-packages/src/import-esm-package.ts`](https://github.com/nestjs/nest/blob/master/sample/34-using-esm-packages/src/import-esm-package.ts#L5) This is the same as `import()` expression that is supposed to load ESM packages while preventing TypeScript from transpiling the import statement into `require()`. `importEsmPackage` dynamically loads an ES module package using behavior equivalent to the native `import()` expression. It prevents TypeScript from transpiling the dynamic import into `require()`, making it suitable for dependencies that are ESM-only. Use it at integration boundaries where CommonJS-compiled code must load an ESM package. ## Signature ```ts async function importEsmPackage(packageName: string): Promise ``` ## Parameters | Name | Type | |---|---| | `packageName` | `string` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Application code] --> B[importEsmPackage(packageName)] B --> C[Native dynamic import()] C --> D[ESM package] D --> E[Module namespace object] ``` ## Usage ```ts import { importEsmPackage } from './import-esm-package'; async function loadFormatter() { const prettier = await importEsmPackage('prettier'); const formatted = await prettier.format('const value=1', { parser: 'babel', }); return formatted; } loadFormatter().then(console.log); ``` ## AI Coding Instructions - Use `importEsmPackage` when loading ESM-only dependencies from code that may otherwise be compiled to CommonJS. - Treat the returned value as a module namespace object; access named exports such as `module.format` or the default export through `module.default`. - Keep the package specifier explicit and ensure the target package is installed as a runtime dependency. - Await the function call and handle import failures when loading optional packages or user-configured integrations. - Do not replace this helper with a regular TypeScript dynamic import unless the build configuration is confirmed to preserve native `import()` behavior. # KafkaJSStaleTopicMetadataAssignmentMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1317) `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. # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/app.controller.ts#L56) ## Endpoint `POST /stream` ## Referenced By - `AppController` (MODULE_DECLARES) # GoneException **Kind:** Class **Source:** [`packages/common/exceptions/gone.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/gone.exception.ts#L11) 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. # 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) `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. # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/nats/nats.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/nats/nats.controller.ts#L43) ## Endpoint `POST /stream` ## Referenced By - `NatsController` (MODULE_DECLARES) # stringCleaner **Kind:** Function **Source:** [`packages/core/test/utils/string.cleaner.ts`](https://github.com/nestjs/nest/blob/master/packages/core/test/utils/string.cleaner.ts#L1) ## Signature ```ts function stringCleaner(str: string) ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | # 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) 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. # MessageRequestProperties **Kind:** Interface **Source:** [`packages/microservices/listener-metadata-explorer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/listener-metadata-explorer.ts#L30) `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. # objectToMap **Kind:** Function **Source:** [`packages/microservices/test/server/utils/object-to-map.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/test/server/utils/object-to-map.ts#L1) ## Signature ```ts function objectToMap(obj: Record) ``` ## Parameters | Name | Type | |---|---| | `obj` | `Record` | # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/redis/redis.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/redis/redis.controller.ts#L25) ## Endpoint `POST /stream` ## Referenced By - `RedisController` (MODULE_DECLARES) # 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) 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. # 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) `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. # randomPort **Kind:** Function **Source:** [`integration/nest-application/get-url/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/get-url/e2e/utils.ts#L5) ## Signature ```ts async function randomPort(): Promise ``` **Returns:** `Promise` # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/rmq.controller.ts#L40) ## Endpoint `POST /stream` ## Referenced By - `RMQController` (MODULE_DECLARES) # 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) 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. # 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) `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. # Roles **Kind:** Function **Source:** [`sample/10-fastify/src/common/decorators/roles.decorator.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/common/decorators/roles.decorator.ts#L3) ## Signature ```ts function Roles(roles: string[]) ``` ## Parameters | Name | Type | |---|---| | `roles` | `string[]` | # stream **Kind:** API Endpoint **Source:** [`integration/microservices/src/tcp-tls/app.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/tcp-tls/app.controller.ts#L69) ## Endpoint `POST /stream` ## Referenced By - `AppController` (MODULE_DECLARES) # KafkaJSTopicMetadataNotLoaded **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1198) **Extends:** `KafkaJSMetadataNotLoaded` ## Properties | Property | Type | |---|---| | `topic` | `string` | # 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) # sleep **Kind:** Function **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L9) ## Signature ```ts function sleep(ms: number) ``` ## Parameters | Name | Type | |---|---| | `ms` | `number` | # streamGreeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/hello/hello.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/hello.controller.ts#L21) ## Endpoint `GET /hello/stream` ## Referenced By - `HelloController` (MODULE_DECLARES) # 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) # 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) 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. # 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) `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()`. # streamGreeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host/host.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/host.controller.ts#L24) ## Endpoint `GET /stream` ## Referenced By - `HostController` (MODULE_DECLARES) # MisdirectedException **Kind:** Class **Source:** [`packages/common/exceptions/misdirected.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/misdirected.exception.ts#L11) 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. # 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) 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. # Public **Kind:** Function **Source:** [`sample/19-auth-jwt/src/auth/decorators/public.decorator.ts`](https://github.com/nestjs/nest/blob/master/sample/19-auth-jwt/src/auth/decorators/public.decorator.ts#L4) # streamGreeting **Kind:** API Endpoint **Source:** [`integration/hello-world/src/host-array/host-array.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/host-array.controller.ts#L24) ## Endpoint `GET /stream` ## Referenced By - `HostArrayController` (MODULE_DECLARES) # 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) 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. # 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) `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. # 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) # synchronous **Kind:** API Endpoint **Source:** [`integration/hello-world/src/errors/errors.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/errors/errors.controller.ts#L5) ## Endpoint `GET /sync` ## Referenced By - `ErrorsController` (MODULE_DECLARES) # 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) 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. # 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) `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. # testMsvc **Kind:** API Endpoint **Source:** [`integration/scopes/src/msvc/http.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/http.controller.ts#L6) ## Endpoint `GET /hello` ## Referenced By - `HttpController` (MODULE_DECLARES) # 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) 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. # PartitionOffset **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L771) `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] # topicExchange **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/fanout-exchange-producer-rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/fanout-exchange-producer-rmq.controller.ts#L24) ## Endpoint `GET /fanout-exchange` ## Referenced By - `RMQFanoutExchangeProducerController` (MODULE_DECLARES) # 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) 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. # PropertyMetadata **Kind:** Interface **Source:** [`packages/core/injector/instance-wrapper.ts`](https://github.com/nestjs/nest/blob/master/packages/core/injector/instance-wrapper.ts#L50) `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] # topicExchange **Kind:** API Endpoint **Source:** [`integration/microservices/src/rmq/topic-exchange-rmq.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/rmq/topic-exchange-rmq.controller.ts#L27) ## Endpoint `GET /topic-exchange` ## Referenced By - `RMQTopicExchangeController` (MODULE_DECLARES) # 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) 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. # ReadPacket **Kind:** Interface **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L5) `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] # transcode **Kind:** API Endpoint **Source:** [`sample/26-queues/src/audio/audio.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/26-queues/src/audio/audio.controller.ts#L9) ## Endpoint `POST /audio/transcode` ## Referenced By - `AudioController` (MODULE_DECLARES) # 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) `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. # 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) 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. # unexpectedError **Kind:** API Endpoint **Source:** [`integration/hello-world/src/errors/errors.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/errors/errors.controller.ts#L15) ## Endpoint `GET /unexpected-error` ## Referenced By - `ErrorsController` (MODULE_DECLARES) # 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) `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) # 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) 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. # update **Kind:** API Endpoint **Source:** [`integration/inspector/src/database/database.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/database.controller.ts#L33) ## Endpoint `PATCH /database/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `DatabaseController` (MODULE_DECLARES) # 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) `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] # UnauthorizedException **Kind:** Class **Source:** [`packages/common/exceptions/unauthorized.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/unauthorized.exception.ts#L11) 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. # update **Kind:** API Endpoint **Source:** [`integration/inspector/src/dogs/dogs.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dogs.controller.ts#L33) ## Endpoint `PATCH /dogs/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `DogsController` (MODULE_DECLARES) # 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) `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) # 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) 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. # update **Kind:** API Endpoint **Source:** [`integration/inspector/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/users.controller.ts#L33) ## Endpoint `PATCH /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # TopicMessages **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L759) `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) # 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) 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. # update **Kind:** API Endpoint **Source:** [`integration/repl/src/users/users.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/users.controller.ts#L33) ## Endpoint `PATCH /users/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `UsersController` (MODULE_DECLARES) # IdentityDeserializer **Kind:** Class **Source:** [`packages/microservices/deserializers/identity.deserializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/deserializers/identity.deserializer.ts#L6) `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. # TopicOffsets **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L776) `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] # update **Kind:** API Endpoint **Source:** [`sample/06-mongoose/src/cats/cats.controller.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/cats.controller.ts#L26) ## Endpoint `POST /cats/:id` | Parameter | In | Type | Required | Description | |---|---|---|---|---| | `id` | path | `string` | βœ“ | | ## Referenced By - `CatsController` (MODULE_DECLARES) # IdentitySerializer **Kind:** Class **Source:** [`packages/microservices/serializers/identity.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/identity.serializer.ts#L3) `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. # useRecordBuilderDuplex **Kind:** API Endpoint **Source:** [`integration/microservices/src/mqtt/mqtt.controller.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/mqtt/mqtt.controller.ts#L95) ## Endpoint `POST /record-builder-duplex` ## Referenced By - `MqttController` (MODULE_DECLARES) # 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) `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] # 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) ## Endpoint `GET /` # 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) 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. # 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) `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] # Abstract **Kind:** Interface **Source:** [`packages/common/interfaces/abstract.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/abstract.interface.ts#L1) `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. # 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) ## Endpoint `GET /` # KafkaJSConnectionError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1180) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `broker` | `string` | # AdminConfig **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L262) `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. # handler **Kind:** API Endpoint **Source:** [`packages/core/middleware/resolver.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/resolver.ts#L18) ## Endpoint `ALL /` # KafkaJSDeleteGroupsError **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1256) **Extends:** `KafkaJSError` ## Properties | Property | Type | |---|---| | `groups` | `DeleteGroupsResult[]` | # 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) 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. # 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) **Extends:** `RuntimeException` # 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) ## Endpoint `GET /` # 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) # 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) # moduleKey **Kind:** API Endpoint **Source:** [`packages/core/middleware/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/container.ts#L27) ## Endpoint `GET /` # 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) `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. # 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) **Extends:** `RuntimeException` # moduleName **Kind:** API Endpoint **Source:** [`packages/core/middleware/container.ts`](https://github.com/nestjs/nest/blob/master/packages/core/middleware/container.ts#L68) ## Endpoint `GET /` # 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) # 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) **Extends:** `RuntimeException` # 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) ## Endpoint `GET /` # 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) `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. # 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) **Extends:** `RuntimeException` # normalizedPattern **Kind:** API Endpoint **Source:** [`packages/microservices/server/server.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server.ts#L150) ## Endpoint `GET /` # 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) # route **Kind:** API Endpoint **Source:** [`packages/microservices/server/server.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server.ts#L168) ## Endpoint `GET /` # 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) **Extends:** `RuntimeException` # 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) # 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) **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) **Extends:** `RuntimeException` # 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) `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. # 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) `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. # RecipesResolver **Kind:** Class **Source:** [`integration/graphql-code-first/src/recipes/recipes.resolver.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/recipes/recipes.resolver.ts#L13) `RecipesResolver` is a code-first GraphQL resolver that exposes recipe queries, mutations, and subscriptions. It coordinates GraphQL operations for retrieving recipes, adding or removing recipes, and notifying subscribed clients when a recipe is added. ## Methods | Method | Signature | Returns | |---|---|---| | `recipe` | `recipe(id: string)` | `Promise` | | `recipes` | `recipes(recipesArgs: RecipesArgs)` | `Promise` | | `addRecipe` | `addRecipe(newRecipeData: NewRecipeInput)` | `Promise` | | `removeRecipe` | `removeRecipe(id: string)` | `void` | | `recipeAdded` | `recipeAdded()` | `void` | ## Where it refuses work - `RecipesResolver` stops the work with `NotFoundException` when `!recipe`. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[RecipesResolver] Resolver --> Query[Queries: recipe / recipes] Resolver --> Mutation[Mutations: addRecipe / removeRecipe] Resolver --> Subscription[Subscription: recipeAdded] Mutation --> Events[Recipe Added Event] Events --> Subscription ``` ## Usage ```ts // Example GraphQL operations handled by RecipesResolver const GET_RECIPES = ` query GetRecipes { recipes { id title description ingredients } } `; const ADD_RECIPE = ` mutation AddRecipe { addRecipe { id title } } `; const RECIPE_ADDED = ` subscription OnRecipeAdded { recipeAdded { id title } } `; // Send GET_RECIPES or ADD_RECIPE through a GraphQL client. // Subscribe to RECIPE_ADDED to receive newly added recipes. ``` ## AI Coding Instructions - Keep resolver methods aligned with the GraphQL schema generated by code-first decorators and their declared return types. - Use `recipe` and `recipes` for read operations; keep state-changing behavior in `addRecipe` and `removeRecipe`. - Ensure `addRecipe` publishes the expected event so `recipeAdded` subscribers receive updates. - Preserve `Promise` and `Promise` return contracts when changing resolver implementations. - Update GraphQL queries, mutation names, and subscription payloads together when renaming resolver methods. # 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) # RecipesResolver **Kind:** Class **Source:** [`sample/33-graphql-mercurius/src/recipes/recipes.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/recipes/recipes.resolver.ts#L16) `RecipesResolver` exposes the GraphQL operations for reading, creating, and removing recipes. It delegates recipe persistence to the recipes service and publishes recipe creation events for GraphQL subscription consumers. ## Methods | Method | Signature | Returns | |---|---|---| | `recipe` | `recipe(id: string)` | `Promise` | | `recipes` | `recipes(recipesArgs: RecipesArgs)` | `Promise` | | `addRecipe` | `addRecipe(newRecipeData: NewRecipeInput, pubSub: PubSub)` | `Promise` | | `removeRecipe` | `removeRecipe(id: string)` | `void` | | `recipeAdded` | `recipeAdded(pubSub: PubSub)` | `void` | ## Where it refuses work - `RecipesResolver` stops the work with `NotFoundException` when `!recipe`. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[RecipesResolver] Resolver --> Service[RecipesService] Service --> Store[Recipe Storage] Resolver --> PubSub[PubSub] PubSub --> Subscription[recipeAdded Subscription] Client -->|recipe / recipes queries| Resolver Client -->|addRecipe / removeRecipe mutations| Resolver Client -->|recipeAdded subscription| Subscription ``` ## Usage ```ts // The resolver is invoked by the GraphQL runtime through operations such as: const query = ` query GetRecipes { recipes { id title description ingredients } } `; const mutation = ` mutation AddRecipe($data: NewRecipeInput!) { addRecipe(newRecipeData: $data) { id title } } `; const subscription = ` subscription OnRecipeAdded { recipeAdded { id title } } `; // Register RecipesResolver in a Nest module so Mercurius can discover // its @Query(), @Mutation(), and @Subscription() handlers. @Module({ providers: [RecipesResolver, RecipesService], }) export class RecipesModule {} ``` ## AI Coding Instructions - Keep resolver methods thin: delegate data access and business logic to `RecipesService`. - Preserve GraphQL decorator names and return types because they define the generated schema contract. - Publish the `recipeAdded` event after a recipe is successfully created so subscription clients receive the new recipe. - Ensure the subscription topic name used by `recipeAdded()` matches the topic passed to `pubSub.publish()`. - Validate recipe input through the GraphQL input type before passing it to the service. # IHeaders **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L160) # RecipesResolver **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/recipes/recipes.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/recipes/recipes.resolver.ts#L11) `RecipesResolver` exposes the GraphQL API for creating, retrieving, removing, and subscribing to recipe data. It acts as the transport layer between GraphQL operations and the underlying recipe service, mapping queries, mutations, and subscriptions to recipe-related behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `recipe` | `recipe(id: string)` | `Promise` | | `recipes` | `recipes(recipesArgs: RecipesArgs)` | `Promise` | | `addRecipe` | `addRecipe(newRecipeData: NewRecipeInput)` | `Promise` | | `removeRecipe` | `removeRecipe(id: string)` | `void` | | `recipeAdded` | `recipeAdded()` | `void` | ## Where it refuses work - `RecipesResolver` stops the work with `NotFoundException` when `!recipe`. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Queries[Queries] Client --> Mutations[Mutations] Client --> Subscriptions[Subscriptions] Queries --> Recipe[recipe()] Queries --> Recipes[recipes()] Mutations --> AddRecipe[addRecipe()] Mutations --> RemoveRecipe[removeRecipe()] Subscriptions --> RecipeAdded[recipeAdded()] Recipe --> Service[RecipesService] Recipes --> Service AddRecipe --> Service RemoveRecipe --> Service AddRecipe --> PubSub[PubSub Event] PubSub --> RecipeAdded ``` ## Usage ```ts import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:3000/graphql', cache: new InMemoryCache(), }); // Retrieve all recipes. const recipesResult = await client.query({ query: gql` query GetRecipes { recipes { id title description ingredients } } `, }); console.log(recipesResult.data.recipes); // Add a recipe through the resolver mutation. const addResult = await client.mutate({ mutation: gql` mutation AddRecipe($newRecipeData: NewRecipeInput!) { addRecipe(newRecipeData: $newRecipeData) { id title } } `, variables: { newRecipeData: { title: 'Chocolate Cake', description: 'A rich chocolate cake', ingredients: ['flour', 'cocoa powder', 'eggs'], }, }, }); console.log(addResult.data.addRecipe); ``` ## AI Coding Instructions - Keep resolver methods thin: delegate recipe persistence and lookup logic to `RecipesService` rather than adding business logic to GraphQL handlers. - Preserve GraphQL decorator metadata such as `@Query`, `@Mutation`, `@Subscription`, `@Args`, and return type functions so the code-first schema remains accurate. - When adding mutations that change recipe data, publish the appropriate event so `recipeAdded()` subscribers receive updates. - Validate and type mutation input through GraphQL input DTOs such as `NewRecipeInput`; avoid accepting untyped request objects. - Ensure removal and lookup operations handle missing recipe IDs consistently, using the service's expected error behavior. # IMemberAssignment **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L939) # 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) **Extends:** `RuntimeException` # BusinessEntity **Kind:** Class **Source:** [`integration/microservices/src/kafka/entities/business.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/entities/business.entity.ts#L4) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | | `phone` | `string` | | `createdBy` | `Partial` | | `created` | `Date` | # JsonSocketOptions **Kind:** Interface **Source:** [`packages/microservices/helpers/json-socket.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/helpers/json-socket.ts#L9) `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. # DatabaseConnection **Kind:** Class **Source:** [`integration/repl/src/database/database.connection.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/database/database.connection.ts#L3) `DatabaseConnection` manages the lifecycle of the REPL integration's database connection. It establishes the connection, monitors it for interruptions, and performs cleanup when the hosting module is destroyed. **Implements:** `OnModuleDestroy` ## Methods | Method | Signature | Returns | |---|---|---| | `connect` | `connect()` | `DatabaseConnection` | | `onModuleDestroy` | `onModuleDestroy()` | `void` | | `maintainConnection` | `maintainConnection()` | `void` | ## Properties | Property | Type | |---|---| | `keepAlive` | `any` | ## Diagram ```mermaid graph LR A[Application / REPL Module] --> B[DatabaseConnection] B -->|connect()| C[Database Client] B -->|maintainConnection()| D[Connection Monitoring] D -->|Reconnect or recover| C A -->|onModuleDestroy()| E[Close Database Connection] E --> C ``` ## Usage ```ts import { DatabaseConnection } from './database/database.connection'; // Typically resolved through the application's dependency-injection container. const databaseConnection = app.get(DatabaseConnection); // Establish and begin maintaining the database connection. databaseConnection.connect(); // When using a framework lifecycle, onModuleDestroy() is called automatically. // Otherwise, call it during application shutdown. await databaseConnection.onModuleDestroy(); ``` ## AI Coding Instructions - Call `connect()` during application startup so connection maintenance is registered before database operations begin. - Treat `DatabaseConnection` as a lifecycle-managed service; prefer dependency injection over creating ad hoc connection instances. - Do not bypass this class with separate database client connections, as that can duplicate connection and reconnection handling. - Ensure application shutdown triggers `onModuleDestroy()` so open database resources are released cleanly. - Keep reconnection and connection-health behavior inside `maintainConnection()` rather than scattering retry logic across consumers. # KafkaJSTopicMetadataNotLoadedMetadata **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1313) `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. # DateScalar **Kind:** Class **Source:** [`integration/graphql-code-first/src/common/scalars/date.scalar.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/common/scalars/date.scalar.ts#L4) `DateScalar` defines a custom GraphQL `Date` scalar for the code-first GraphQL integration. It converts incoming numeric timestamps into JavaScript `Date` instances and serializes `Date` values back to millisecond timestamps for GraphQL responses. ## Methods | Method | Signature | Returns | |---|---|---| | `parseValue` | `parseValue(value: any)` | `void` | | `serialize` | `serialize(value: any)` | `void` | | `parseLiteral` | `parseLiteral(ast: ValueNode)` | `void` | ## Properties | Property | Type | |---|---| | `description` | `any` | ## Where it refuses work - `DateScalar` stops the work with an early return when `ast.kind === Kind.INT`. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|Variable timestamp| ParseValue[parseValue()] Client -->|Inline integer literal| ParseLiteral[parseLiteral()] ParseValue --> DateObject[JavaScript Date] ParseLiteral --> DateObject DateObject --> Resolver[Resolver / Application Code] Resolver --> Serialize[serialize()] Serialize -->|Milliseconds timestamp| Client ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { Query, Resolver } from '@nestjs/graphql'; import { DateScalar } from './common/scalars/date.scalar'; @Resolver() class EventsResolver { @Query(() => Date) nextEventDate(): Date { return new Date('2024-12-31T00:00:00.000Z'); } } @Module({ providers: [DateScalar, EventsResolver], }) export class AppModule {} ``` ```graphql query { nextEventDate } ``` ```json { "data": { "nextEventDate": 1735603200000 } } ``` ## AI Coding Instructions - Register `DateScalar` as a NestJS provider so the code-first GraphQL schema can resolve the custom `Date` scalar. - Treat GraphQL date values as millisecond timestamps; `parseValue()` and `parseLiteral()` create `Date` objects from numeric input. - Return valid JavaScript `Date` instances from resolvers so `serialize()` can safely call `getTime()`. - Use GraphQL variables or integer literals for date input; avoid passing formatted date strings unless the scalar implementation is updated to support them. # 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) `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. # DateScalar **Kind:** Class **Source:** [`integration/graphql-schema-first/src/common/scalars/date.scalar.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/common/scalars/date.scalar.ts#L4) `DateScalar` is a GraphQL custom scalar that converts date values between GraphQL inputs/outputs and JavaScript `Date` instances. It validates variable values and inline literals during query execution, while serializing supported date values into the API’s expected date representation. ## Methods | Method | Signature | Returns | |---|---|---| | `parseValue` | `parseValue(value: undefined)` | `void` | | `serialize` | `serialize(value: undefined)` | `void` | | `parseLiteral` | `parseLiteral(ast: undefined)` | `void` | ## Properties | Property | Type | |---|---| | `description` | `any` | ## Where it refuses work - `DateScalar` stops the work with an early return when `ast.kind === Kind.INT`. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Input[Date Input] Input --> ParseValue[parseValue()] Input --> ParseLiteral[parseLiteral()] ParseValue --> Date[JavaScript Date] ParseLiteral --> Date Date --> Resolver[GraphQL Resolver] Resolver --> Serialize[serialize()] Serialize --> Response[GraphQL Date Response] ``` ## Usage ```ts import { DateScalar } from './common/scalars/date.scalar'; const dateScalar = new DateScalar(); // Parse a GraphQL variable value. const inputDate = dateScalar.parseValue('2024-01-15T10:30:00.000Z'); // Serialize a resolver result for the GraphQL response. const outputDate = dateScalar.serialize(inputDate); // Register in a schema-first scalar resolver map. export const resolvers = { Date: dateScalar, }; ``` ## AI Coding Instructions - Register `DateScalar` under the same scalar name declared in the GraphQL schema, such as `scalar Date`. - Use `parseValue()` for GraphQL variables and `parseLiteral()` for inline query literals; keep their validation behavior consistent. - Ensure resolvers return valid `Date` instances or supported date strings that `serialize()` can safely convert. - Reject invalid, malformed, or unsupported date inputs with GraphQL-compatible errors rather than silently coercing them. - Preserve the scalar’s existing date format when changing serialization logic to avoid breaking API clients. # MsObjectPattern **Kind:** Interface **Source:** [`packages/microservices/interfaces/pattern.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/pattern.interface.ts#L3) # DateScalar **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/common/scalars/date.scalar.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/common/scalars/date.scalar.ts#L4) `DateScalar` is a custom GraphQL scalar that converts date values between GraphQL inputs and JavaScript `Date` instances. It parses incoming values and literals into `Date` objects, then serializes dates as numeric timestamps for GraphQL responses. **Implements:** `CustomScalar` ## Methods | Method | Signature | Returns | |---|---|---| | `parseValue` | `parseValue(value: number)` | `Date` | | `serialize` | `serialize(value: Date)` | `number` | | `parseLiteral` | `parseLiteral(ast: any)` | `Date` | ## Properties | Property | Type | |---|---| | `description` | `any` | ## Where it refuses work - `DateScalar` stops the work with an early return when `ast.kind === Kind.INT`. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|timestamp input| ParseValue[parseValue] Literal[GraphQL AST literal] --> ParseLiteral[parseLiteral] ParseValue --> DateObject[JavaScript Date] ParseLiteral --> DateObject DateObject --> Serialize[serialize] Serialize -->|numeric timestamp| Client ``` ## Usage ```ts import { DateScalar } from './common/scalars/date.scalar'; const dateScalar = new DateScalar(); // Convert a GraphQL input value to a Date. const date = dateScalar.parseValue(1704067200000); // Return a Date from a resolver; GraphQL receives a timestamp. const timestamp = dateScalar.serialize(date); console.log(timestamp); // 1704067200000 ``` ## AI Coding Instructions - Keep the scalar registered as a GraphQL provider so fields using the date scalar resolve through `DateScalar`. - Pass timestamps or otherwise supported date values to `parseValue`; validate invalid input before using the resulting `Date`. - Return JavaScript `Date` instances from resolvers when GraphQL should serialize a date value. - Preserve the existing timestamp-based serialization format to avoid breaking API clients. - Handle GraphQL AST literal kinds consistently in `parseLiteral`, returning an appropriate value for unsupported literal types. # 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) # DateScalar **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/common/scalars/date.scalar.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/common/scalars/date.scalar.ts#L4) `DateScalar` is a custom GraphQL scalar that converts date values between GraphQL inputs/AST literals and JavaScript `Date` instances. It serializes dates as Unix timestamps in milliseconds, allowing the code-first GraphQL schema to expose a consistent date representation. **Implements:** `CustomScalar` ## Methods | Method | Signature | Returns | |---|---|---| | `parseValue` | `parseValue(value: number)` | `Date` | | `serialize` | `serialize(value: Date)` | `number` | | `parseLiteral` | `parseLiteral(ast: ValueNode)` | `Date` | ## Properties | Property | Type | |---|---| | `description` | `any` | ## Where it refuses work - `DateScalar` stops the work with an early return when `ast.kind === Kind.INT`. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|variables / literals| DateScalar[DateScalar] DateScalar -->|parseValue / parseLiteral| Resolver[Resolver] Resolver -->|Date object| DateScalar DateScalar -->|serialize: timestamp| Client ``` ## Usage ```ts import { DateScalar } from './common/scalars/date.scalar'; const dateScalar = new DateScalar(); // Convert a GraphQL variable value into a Date for resolver usage. const inputDate = dateScalar.parseValue('2024-01-15T10:30:00.000Z'); // Convert a Date returned by a resolver into a GraphQL-safe timestamp. const timestamp = dateScalar.serialize(inputDate); console.log(inputDate instanceof Date); // true console.log(timestamp); // 1705314600000 ``` ## AI Coding Instructions - Register `DateScalar` as a GraphQL provider so the code-first schema can resolve the custom scalar type. - Return valid JavaScript `Date` objects from resolvers that expose date fields using this scalar. - Keep serialization consistent: this scalar emits Unix timestamps in milliseconds, not ISO date strings or seconds. - Validate or handle invalid date input in `parseValue()` and `parseLiteral()` when extending the scalar. - Ensure `parseLiteral()` handles the expected GraphQL AST value kinds before converting literal input to a `Date`. # 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) # DateScalar **Kind:** Class **Source:** [`sample/33-graphql-mercurius/src/common/scalars/date.scalar.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/common/scalars/date.scalar.ts#L4) `DateScalar` is a custom GraphQL scalar that converts timestamp values into JavaScript `Date` objects for resolver inputs. It serializes `Date` instances back to numeric timestamps for GraphQL responses and supports date values provided as GraphQL literals. **Implements:** `CustomScalar` ## Methods | Method | Signature | Returns | |---|---|---| | `parseValue` | `parseValue(value: number)` | `Date` | | `serialize` | `serialize(value: Date)` | `number` | | `parseLiteral` | `parseLiteral(ast: ValueNode)` | `Date` | ## Properties | Property | Type | |---|---| | `description` | `any` | ## Where it refuses work - `DateScalar` stops the work with an early return when `ast.kind === Kind.INT`. ## Diagram ```mermaid graph LR Client[GraphQL Client] -->|timestamp value| DateScalar[DateScalar] DateScalar -->|parseValue / parseLiteral| Resolver[Resolver receives Date] Resolver -->|returns Date| DateScalar DateScalar -->|serialize timestamp| Client ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { DateScalar } from './common/scalars/date.scalar'; @Module({ imports: [ GraphQLModule.forRoot({ autoSchemaFile: true, }), ], providers: [DateScalar], }) export class AppModule {} // GraphQL usage: // query { // event { // createdAt // } // } // // Response: // { // "data": { // "event": { // "createdAt": 1711929600000 // } // } // } ``` ## AI Coding Instructions - Register `DateScalar` as a NestJS provider so it is included in the generated GraphQL schema. - Pass date inputs as numeric timestamps; `parseValue()` and `parseLiteral()` convert them into `Date` instances. - Return valid `Date` objects from resolvers so `serialize()` can convert them to timestamps safely. - Validate incoming timestamp values when adding stricter date requirements, such as rejecting invalid or out-of-range dates. - Keep the GraphQL scalar name consistent with schema fields that declare the `Date` type. # 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) # 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) **Extends:** `Error` # OauthbearerProviderResponse **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L85) `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. # 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) **Extends:** `RuntimeException` # Offsets **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L781) `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. # 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) **Extends:** `RuntimeException` # OffsetsByTopicPartition **Kind:** Interface **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L990) `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. # 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) **Extends:** `RuntimeException` # 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) 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. # 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) **Extends:** `RuntimeException` # 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) 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. # 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) # 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) # 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) # 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) # 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) # Post **Kind:** Class **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/posts/models/post.model.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/posts/models/post.model.ts#L4) ## Properties | Property | Type | |---|---| | `id` | `number` | | `title` | `string` | | `authorId` | `number` | | `user` | `User` | # 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) 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. # Post **Kind:** Class **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/models/post.model.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/models/post.model.ts#L4) ## Properties | Property | Type | |---|---| | `id` | `number` | | `title` | `string` | | `authorId` | `number` | | `user` | `User` | # 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) 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. # Recipe **Kind:** Class **Source:** [`integration/graphql-code-first/src/recipes/models/recipe.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/recipes/models/recipe.ts#L3) ## Properties | Property | Type | |---|---| | `id` | `string` | | `title` | `string` | | `description` | `string` | | `creationDate` | `Date` | | `ingredients` | `string[]` | # 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) `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. # Recipe **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/recipes/models/recipe.model.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/recipes/models/recipe.model.ts#L3) ## Properties | Property | Type | |---|---| | `id` | `string` | | `title` | `string` | | `description` | `string` | | `creationDate` | `Date` | | `ingredients` | `string[]` | # PacketId **Kind:** Interface **Source:** [`packages/microservices/interfaces/packet.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/packet.interface.ts#L1) `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. # Recipe **Kind:** Class **Source:** [`sample/33-graphql-mercurius/src/recipes/models/recipe.model.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/recipes/models/recipe.model.ts#L3) ## Properties | Property | Type | |---|---| | `id` | `string` | | `title` | `string` | | `description` | `string` | | `creationDate` | `Date` | | `ingredients` | `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) # 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) # 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) # UserEntity **Kind:** Class **Source:** [`integration/microservices/src/kafka/entities/user.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/entities/user.entity.ts#L3) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | | `email` | `string` | | `phone` | `string` | | `years` | `number` | | `created` | `Date` | # Serializer **Kind:** Interface **Source:** [`packages/microservices/interfaces/serializer.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/serializer.interface.ts#L10) # UserEntity **Kind:** Class **Source:** [`sample/21-serializer/src/entities/user.entity.ts`](https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/entities/user.entity.ts#L4) ## Properties | Property | Type | |---|---| | `id` | `number` | | `firstName` | `string` | | `lastName` | `string` | | `password` | `string` | | `role` | `RoleEntity` | # AckGateway **Kind:** Class **Source:** [`integration/websockets/src/ack.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/ack.gateway.ts#L8) `AckGateway` coordinates acknowledgment messages in the WebSocket integration layer. It reacts to incoming push events through `onPush()` and processes explicit client acknowledgments through `handleManualAck()`, ensuring acknowledgement state is propagated through the realtime connection. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush()` | `void` | | `handleManualAck` | `handleManualAck(data: any, ack: (response: any) => void)` | `void` | ## Diagram ```mermaid graph LR PushSource[Push event source] -->|push payload| AckGateway[AckGateway.onPush()] AckGateway -->|deliver event| WebSocketClient[WebSocket client] WebSocketClient -->|manual acknowledgement| ManualAck[AckGateway.handleManualAck()] ManualAck --> AckService[Acknowledgement handling/service] ``` ## Usage ```ts // The gateway is typically registered by the WebSocket framework. // A connected client receives a pushed event and sends a manual ACK. socket.on("push", async (payload) => { console.log("Received push:", payload); // After the application has processed the payload, acknowledge it. socket.emit("manual-ack", { messageId: payload.messageId, status: "received", }); }); ``` ## AI Coding Instructions - Keep `onPush()` focused on translating incoming push data into the WebSocket event contract expected by connected clients. - Validate manual acknowledgment payloads in `handleManualAck()` before updating acknowledgement state or forwarding data to downstream services. - Preserve event names and payload shapes used by existing WebSocket clients; changing them is a breaking realtime API change. - Ensure acknowledgement handling is idempotent, since clients may retry manual ACK messages after reconnecting. - Handle disconnected or stale clients gracefully when delivering push events or processing acknowledgements. # Type **Kind:** Interface **Source:** [`packages/common/interfaces/type.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/type.interface.ts#L1) # Cat **Kind:** Interface **Source:** [`integration/graphql-schema-first/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-schema-first/src/cats/interfaces/cat.interface.ts#L1) `Cat` defines the core shape of a cat record in the GraphQL schema-first integration. It provides a consistent contract for cat data, including a numeric identifier, display name, and age, across resolvers, services, and API responses. ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | | `age` | `number` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[Cat Resolver] Resolver --> Service[Cat Service] Service --> Cat[Cat Interface] Cat --> Id[id: number] Cat --> Name[name: string] Cat --> Age[age: number] ``` ## Usage ```ts import { Cat } from './interfaces/cat.interface'; const cat: Cat = { id: 1, name: 'Milo', age: 3, }; function getCatLabel(cat: Cat): string { return `${cat.name} is ${cat.age} years old`; } console.log(getCatLabel(cat)); // "Milo is 3 years old" ``` ## AI Coding Instructions - Use the `Cat` interface whenever passing or returning complete cat records between application layers. - Ensure `id` and `age` are numbers; do not serialize them as strings in TypeScript service code. - Keep property names aligned with the GraphQL schema: `id`, `name`, and `age`. - Add optional or derived fields through separate DTOs or interfaces rather than changing this core contract without updating schema integrations. # Cat **Kind:** Class **Source:** [`sample/11-swagger/src/cats/entities/cat.entity.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/entities/cat.entity.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # Cat **Kind:** Interface **Source:** [`integration/inspector/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/interfaces/cat.interface.ts#L1) `Cat` defines the core data shape for cat records in the inspector integration. It ensures that every cat includes a name, age, and breed when passed between cat-related services, controllers, and UI components. ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | ## Diagram ```mermaid graph LR A[Cat Record] --> B[name: string] A --> C[age: number] A --> D[breed: string] ``` ## Usage ```ts import type { Cat } from './interfaces/cat.interface'; const cat: Cat = { name: 'Milo', age: 3, breed: 'Maine Coon', }; function describeCat(cat: Cat): string { return `${cat.name} is a ${cat.age}-year-old ${cat.breed}.`; } console.log(describeCat(cat)); ``` ## AI Coding Instructions - Provide all required fields (`name`, `age`, and `breed`) whenever creating a `Cat` object. - Keep `name` and `breed` as strings, and use a numeric value for `age`. - Import `Cat` using `import type` when it is only used for TypeScript type checking. - Use this interface consistently at cat-related integration boundaries, such as service responses and controller payloads. # Cat **Kind:** Class **Source:** [`sample/06-mongoose/src/cats/schemas/cat.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/schemas/cat.schema.ts#L6) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # Cat **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/graphql.schema.ts#L39) ## Properties | Property | Type | |---|---| | `id` | `Nullable` | | `name` | `Nullable` | | `age` | `Nullable` | | `owner` | `Nullable` | # Cat **Kind:** Interface **Source:** [`integration/mongoose/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/interfaces/cat.interface.ts#L3) `Cat` defines the data contract for cat records used by the Mongoose integration's cats feature. It ensures each cat object includes a name, age, and breed when passed between controllers, services, and persistence-related code. ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | ## Diagram ```mermaid graph LR Client[Client Request] --> Controller[Cats Controller] Controller --> Service[Cats Service] Service --> Cat[Cat Interface] Service --> Database[(MongoDB)] Cat --> Database ``` ## Usage ```ts import { Cat } from './interfaces/cat.interface'; const newCat: Cat = { name: 'Milo', age: 3, breed: 'Siamese', }; function describeCat(cat: Cat): string { return `${cat.name} is a ${cat.age}-year-old ${cat.breed}.`; } console.log(describeCat(newCat)); ``` ## AI Coding Instructions - Use the `Cat` interface for objects representing cat domain data in controllers and services. - Provide all required fields: `name` as a string, `age` as a number, and `breed` as a string. - Keep this interface aligned with the corresponding Mongoose schema and document model fields. - Avoid adding persistence-specific properties, such as MongoDB `_id`, unless the interface is intentionally expanded to represent stored documents. # Cat **Kind:** Interface **Source:** [`sample/01-cats-app/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/interfaces/cat.interface.ts#L1) `Cat` defines the core data shape for a cat within the cats application. It ensures that every cat record includes a name, age, and breed, providing a consistent contract between controllers, services, and other application layers. ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | ## Diagram ```mermaid graph LR Cat[Cat Interface] Name[name: string] Age[age: number] Breed[breed: string] Cat --> Name Cat --> Age Cat --> Breed ``` ## Usage ```ts import { Cat } from './cats/interfaces/cat.interface'; const newCat: Cat = { name: 'Whiskers', age: 3, breed: 'Siamese', }; function describeCat(cat: Cat): string { return `${cat.name} is a ${cat.age}-year-old ${cat.breed}.`; } console.log(describeCat(newCat)); ``` ## AI Coding Instructions - Use the `Cat` interface whenever passing cat data between application layers. - Provide all required fields: `name`, `age`, and `breed`. - Keep `age` as a numeric value rather than a string received directly from request input. - Add optional or new cat properties only after updating all related DTOs, services, and consumers. - Import the interface from `cats/interfaces/cat.interface` instead of duplicating the object shape. # CatsController **Kind:** Class **Source:** [`sample/09-babel-example/src/cats/cats.controller.js`](https://github.com/nestjs/nest/blob/master/sample/09-babel-example/src/cats/cats.controller.js#L12) `CatsController` handles HTTP requests for the cats resource in the Babel example application. It exposes endpoints to create cats, retrieve all cats, and retrieve an individual cat by identifier, delegating business logic and data access to the associated service layer. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(createCatDto: undefined)` | `void` | | `findAll` | `findAll()` | `void` | | `findOne` | `findOne(id: undefined)` | `void` | ## Diagram ```mermaid graph LR Client[HTTP Client] --> Controller[CatsController] Controller -->|create()| Service[CatsService] Controller -->|findAll()| Service Controller -->|findOne(id)| Service Service --> Repository[Cat Data Store] ``` ## Usage ```ts import { CatsController } from './cats.controller'; import { CatsService } from './cats.service'; const catsService = new CatsService(); const catsController = new CatsController(catsService); // Create a cat const createdCat = await catsController.create({ name: 'Milo', age: 3, breed: 'Tabby', }); // List all cats const cats = await catsController.findAll(); // Retrieve one cat const cat = await catsController.findOne('1'); ``` ## AI Coding Instructions - Keep controllers focused on HTTP request/response handling; place business rules and persistence logic in `CatsService`. - Preserve the existing method responsibilities: use `create()` for new resources, `findAll()` for collection queries, and `findOne()` for identifier-based lookups. - Validate incoming create payloads with DTOs or validation middleware before passing data to the service layer. - Handle missing cat identifiers consistently, typically by allowing the service layer to raise a not-found error. - When adding routes, use framework decorators and route conventions consistent with the existing cats module. # Cat **Kind:** Interface **Source:** [`sample/10-fastify/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/interfaces/cat.interface.ts#L1) `Cat` defines the data shape for cat records in the Fastify application's cats module. It ensures that every cat object includes a `name`, `age`, and `breed`, providing a consistent contract between routes, services, and stored data. ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | ## Diagram ```mermaid graph LR Client[API Client] --> Route[Fastify Cat Route] Route --> Service[Cat Service] Service --> Cat[Cat Interface] Cat --> Name[name: string] Cat --> Age[age: number] Cat --> Breed[breed: string] ``` ## Usage ```ts import type { Cat } from './interfaces/cat.interface'; const createCat = (cat: Cat): Cat => { return { name: cat.name, age: cat.age, breed: cat.breed, }; }; const luna: Cat = createCat({ name: 'Luna', age: 3, breed: 'Siamese', }); console.log(luna.name); // Luna ``` ## AI Coding Instructions - Use the `Cat` interface for values representing complete cat records across routes, services, and repositories. - Provide all required fields: `name` and `breed` must be strings, while `age` must be a number. - Keep this interface focused on the core cat domain model; use separate DTO interfaces for request-specific validation or optional fields. - Update all consumers and API schemas when adding, renaming, or changing a `Cat` field. # 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) **Extends:** `Error` # Cat **Kind:** Interface **Source:** [`sample/14-mongoose-base/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/interfaces/cat.interface.ts#L3) `Cat` defines the core data shape for cat records in the application. It provides a consistent contract for cat-related features, including Mongoose models, services, controllers, and request handling. ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | ## Diagram ```mermaid graph LR Client[Client Request] --> Controller[Cats Controller] Controller --> Service[Cats Service] Service --> Model[Mongoose Cat Model] Model --> Cat[Cat Interface] Cat --> Name[name: string] Cat --> Age[age: number] Cat --> Breed[breed: string] ``` ## Usage ```ts import { Cat } from './interfaces/cat.interface'; const newCat: Cat = { name: 'Milo', age: 3, breed: 'Siamese', }; function describeCat(cat: Cat): string { return `${cat.name} is a ${cat.age}-year-old ${cat.breed}.`; } console.log(describeCat(newCat)); ``` ## AI Coding Instructions - Use the `Cat` interface whenever defining or passing cat data between application layers. - Ensure all cat objects include `name`, `age`, and `breed` with the correct primitive types. - Keep this interface aligned with the corresponding Mongoose schema and model fields. - Add optional or new cat properties here only when the schema, DTOs, and persistence logic are updated accordingly. # CreateCatDto **Kind:** Class **Source:** [`integration/inspector/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/cats/dto/create-cat.dto.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # Cat **Kind:** Interface **Source:** [`sample/36-hmr-esm/src/cats/interfaces/cat.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/interfaces/cat.interface.ts#L1) `Cat` defines the core data shape for cat records in the cats feature module. It ensures that every cat object provides a name, age, and breed, enabling consistent typing across services, controllers, and UI consumers. ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | ## Diagram ```mermaid graph LR Cat[Cat interface] Name[name: string] Age[age: number] Breed[breed: string] Cat --> Name Cat --> Age Cat --> Breed ``` ## Usage ```ts import type { Cat } from './interfaces/cat.interface'; const cat: Cat = { name: 'Mochi', age: 3, breed: 'Siamese', }; function describeCat(cat: Cat): string { return `${cat.name} is a ${cat.age}-year-old ${cat.breed}.`; } console.log(describeCat(cat)); ``` ## AI Coding Instructions - Use `Cat` whenever a value represents a complete cat record within the cats module. - Provide all required fields: `name`, `age`, and `breed`; none are optional. - Keep `age` as a numeric value rather than a string parsed from request input. - Import the interface with `import type` when it is only needed for TypeScript type checking. - Extend this interface carefully if new cat attributes must be shared across API, service, and persistence layers. # CreateCatDto **Kind:** Class **Source:** [`sample/01-cats-app/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/dto/create-cat.dto.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # CreateCatDto **Kind:** Class **Source:** [`sample/10-fastify/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/cats/dto/create-cat.dto.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # InterceptorDelayedSseStats **Kind:** Interface **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L72) `InterceptorDelayedSseStats` tracks lifecycle metrics for delayed Server-Sent Events (SSE) streams in Nest application integration tests. It records request, subscription, active-stream, teardown, and close-event counts so tests can verify that SSE connections are created and cleaned up correctly. ## Properties | Property | Type | |---|---| | `closeEventsObserved` | `number` | | `requestsStarted` | `number` | | `runningStreams` | `number` | | `subscriptionsStarted` | `number` | | `teardownsObserved` | `number` | ## Diagram ```mermaid graph LR Client[SSE Client Request] --> Request[requestsStarted] Request --> Subscription[subscriptionsStarted] Subscription --> Stream[runningStreams] Stream --> Teardown[teardownsObserved] Teardown --> Close[closeEventsObserved] ``` ## Usage ```ts import type { InterceptorDelayedSseStats } from './utils'; const stats: InterceptorDelayedSseStats = { requestsStarted: 0, subscriptionsStarted: 0, runningStreams: 0, teardownsObserved: 0, closeEventsObserved: 0, }; // Example assertions after opening and closing an SSE connection. expect(stats.requestsStarted).toBe(1); expect(stats.subscriptionsStarted).toBe(1); expect(stats.runningStreams).toBe(0); expect(stats.teardownsObserved).toBe(1); expect(stats.closeEventsObserved).toBe(1); ``` ## AI Coding Instructions - Initialize every counter to `0` before starting an SSE test or interceptor scenario. - Increment `requestsStarted` when the HTTP request reaches the delayed SSE interceptor. - Track active subscriptions with `runningStreams`; ensure it returns to `0` after client disconnects. - Assert both `teardownsObserved` and `closeEventsObserved` to verify Observable cleanup and connection closure. - Reset or create fresh stats objects between tests to prevent lifecycle counts from leaking across cases. # CreateCatDto **Kind:** Class **Source:** [`sample/11-swagger/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/11-swagger/src/cats/dto/create-cat.dto.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # NatsSubscriber **Kind:** Interface **Source:** [`sample/03-microservices/src/common/strategies/nats.strategy.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/common/strategies/nats.strategy.ts#L3) `NatsSubscriber` defines a named NATS subscription configuration used by the microservices strategy layer. Each subscriber maps a unique `key` to a message `pattern` and NATS `queue`, allowing consumers to share work through queue groups. ## Properties | Property | Type | |---|---| | `key` | `string` | | `value` | `{ pattern: string; queue: string; }` | ## Diagram ```mermaid graph LR A[NatsSubscriber] --> B[key: string] A --> C[value] C --> D[pattern: string] C --> E[queue: string] D --> F[NATS message subject] E --> G[NATS queue group] ``` ## Usage ```ts import type { NatsSubscriber } from './common/strategies/nats.strategy'; const orderCreatedSubscriber: NatsSubscriber = { key: 'order-created-handler', value: { pattern: 'orders.created', queue: 'order-processing', }, }; // Use the configuration when registering a NATS consumer. natsClient.subscribe( orderCreatedSubscriber.value.pattern, { queue: orderCreatedSubscriber.value.queue }, (message) => { console.log(`Received ${orderCreatedSubscriber.key}:`, message); }, ); ``` ## AI Coding Instructions - Use a stable, descriptive `key` so subscriber configurations can be identified consistently in logs or registries. - Set `value.pattern` to the exact NATS subject used by the publisher; subject mismatches prevent messages from being received. - Use `value.queue` to group equivalent consumers for load-balanced message processing. - Keep queue names consistent across instances that should share processing work; use different queues when each service must receive every message. - Validate subscription registration code passes both `pattern` and `queue` from this interface to the NATS client. # CreateCatDto **Kind:** Class **Source:** [`sample/36-hmr-esm/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/cats/dto/create-cat.dto.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # Post **Kind:** Interface **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.interfaces.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.interfaces.ts#L3) `Post` defines the core data shape for a post in the posts application. It stores the post identifier, title, and the numeric identifier of the author, allowing the GraphQL federation layer or related services to associate posts with users. ## Properties | Property | Type | |---|---| | `id` | `number` | | `title` | `string` | | `authorId` | `number` | ## Diagram ```mermaid graph LR Post[Post] Post --> Id[id: number] Post --> Title[title: string] Post --> AuthorId[authorId: number] AuthorId --> Author[Author/User service] ``` ## Usage ```ts import { Post } from './posts.interfaces'; const post: Post = { id: 42, title: 'Introducing GraphQL Federation', authorId: 7, }; function getAuthorReference(post: Post) { return { id: post.authorId, }; } console.log(getAuthorReference(post)); // { id: 7 } ``` ## AI Coding Instructions - Keep `id` and `authorId` as numeric values; do not replace them with strings unless the schema and consuming services are updated together. - Use `authorId` as the cross-service reference for resolving the post author through the appropriate user or author service. - Ensure objects returned from post repositories, resolvers, or service methods satisfy the complete `Post` shape. - Add new post properties to this interface only when corresponding persistence, GraphQL schema, and resolver layers are updated. # EventsGateway **Kind:** Class **Source:** [`sample/02-gateways/src/events/events.gateway.ts`](https://github.com/nestjs/nest/blob/master/sample/02-gateways/src/events/events.gateway.ts#L12) `EventsGateway` is a WebSocket gateway that exposes event-related operations to connected clients. It provides a streaming `findAll()` handler that returns observable WebSocket responses and an asynchronous `identity()` handler that resolves a numeric identifier. ## Methods | Method | Signature | Returns | |---|---|---| | `findAll` | `findAll(data: any)` | `Observable>` | | `identity` | `identity(data: number)` | `Promise` | ## Properties | Property | Type | |---|---| | `server` | `Server` | ## Diagram ```mermaid graph LR Client[WebSocket Client] --> Gateway[EventsGateway] Gateway --> FindAll[findAll(): Observable>] Gateway --> Identity[identity(): Promise] FindAll --> Response[WebSocket Response Stream] Identity --> Result[Numeric Identifier] ``` ## Usage ```ts import { EventsGateway } from './events.gateway'; const gateway = new EventsGateway(); // Subscribe to streamed WebSocket-style responses. gateway.findAll().subscribe((response) => { console.log('Received event response:', response); }); // Resolve the gateway identity value. const id = await gateway.identity(); console.log('Gateway identity:', id); ``` ## AI Coding Instructions - Keep WebSocket-facing handlers in `EventsGateway`; move reusable business logic into injectable services when complexity grows. - Preserve the declared return types: use `Observable>` for streamed responses and `Promise` for asynchronous single values. - Ensure observable streams complete or are properly managed to avoid retaining client subscriptions unnecessarily. - Return WebSocket-compatible response objects from `findAll()` rather than raw values when extending event handlers. - When adding handlers, follow the gateway's existing WebSocket message/decorator conventions used elsewhere in the application. # PromiseDelayedSseStats **Kind:** Interface **Source:** [`integration/nest-application/sse/e2e/utils.ts`](https://github.com/nestjs/nest/blob/master/integration/nest-application/sse/e2e/utils.ts#L1) `PromiseDelayedSseStats` captures observable lifecycle counters for delayed Server-Sent Events (SSE) streams in Nest application end-to-end tests. It helps verify request creation, subscription behavior, active stream counts, teardown execution, and client close events during asynchronous SSE scenarios. ## Properties | Property | Type | |---|---| | `closeEventsObserved` | `number` | | `requestsStarted` | `number` | | `runningStreams` | `number` | | `subscriptionsStarted` | `number` | | `teardownsObserved` | `number` | ## Diagram ```mermaid graph LR Client[HTTP/SSE Client] --> Request[Request Started] Request --> Subscription[Subscription Started] Subscription --> Stream[Running Stream] Stream --> Close[Client Closes Connection] Close --> Teardown[Stream Teardown] Request --> RS[requestsStarted] Subscription --> SS[subscriptionsStarted] Stream --> RUN[runningStreams] Close --> CE[closeEventsObserved] Teardown --> TO[teardownsObserved] ``` ## Usage ```ts import type { PromiseDelayedSseStats } from './utils'; const stats: PromiseDelayedSseStats = { closeEventsObserved: 0, requestsStarted: 0, runningStreams: 0, subscriptionsStarted: 0, teardownsObserved: 0, }; // Example assertions after an SSE client connects and disconnects. expect(stats.requestsStarted).toBe(1); expect(stats.subscriptionsStarted).toBe(1); expect(stats.runningStreams).toBe(0); expect(stats.closeEventsObserved).toBe(1); expect(stats.teardownsObserved).toBe(1); ``` ## AI Coding Instructions - Initialize every counter to `0` before starting an SSE test or request lifecycle. - Increment `requestsStarted` when the endpoint is invoked and `subscriptionsStarted` when the SSE observable is subscribed. - Maintain `runningStreams` as an active count: increment on stream start and decrement during teardown. - Record `closeEventsObserved` separately from `teardownsObserved`; a client close should trigger teardown, but tests may need to validate both events. - Use these counters in E2E assertions to detect leaked subscriptions or streams that remain active after disconnects. # ConfigModuleOptions **Kind:** Interface **Source:** [`sample/25-dynamic-modules/src/config/config.module.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/config/config.module.ts#L5) `ConfigModuleOptions` defines the configuration accepted by the dynamic configuration module. Its `folder` property identifies the directory from which the module should load configuration files or environment-specific settings. ## Properties | Property | Type | |---|---| | `folder` | `string` | ## Diagram ```mermaid graph LR A[Application Module] --> B[ConfigModule.register options] B --> C[ConfigModuleOptions] C --> D[folder: string] D --> E[Configuration Files Directory] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ConfigModule } from './config/config.module'; import type { ConfigModuleOptions } from './config/config.module'; const configOptions: ConfigModuleOptions = { folder: 'config', }; @Module({ imports: [ ConfigModule.register(configOptions), ], }) export class AppModule {} ``` ## AI Coding Instructions - Provide a valid directory path string for `folder`; keep it relative to the project root unless the module explicitly supports absolute paths. - Reuse a centralized `ConfigModuleOptions` object when multiple modules need consistent configuration loading behavior. - Ensure the referenced folder is included in the runtime build or deployment artifact, especially when compiling TypeScript into a separate output directory. - Avoid hardcoding environment-specific paths in module definitions; derive the folder from environment variables or application configuration when needed. # 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) **Extends:** `RuntimeException` # EnvConfig **Kind:** Interface **Source:** [`sample/25-dynamic-modules/src/config/interfaces/envconfig.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/25-dynamic-modules/src/config/interfaces/envconfig.interface.ts#L1) # 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) **Extends:** `RuntimeException` # Hero **Kind:** Interface **Source:** [`sample/04-grpc/src/hero/interfaces/hero.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/hero/interfaces/hero.interface.ts#L1) `Hero` defines the core data shape for a hero in the gRPC sample application. It provides a shared contract for hero identifiers and names across service handlers, data access code, and API responses. ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | ## Diagram ```mermaid graph LR Client[gRPC Client] --> Service[Hero Service] Service --> Hero[Hero Interface] Hero --> ID[id: number] Hero --> Name[name: string] ``` ## Usage ```ts import { Hero } from './interfaces/hero.interface'; const hero: Hero = { id: 1, name: 'Superman', }; function formatHero(hero: Hero): string { return `${hero.id}: ${hero.name}`; } console.log(formatHero(hero)); // "1: Superman" ``` ## AI Coding Instructions - Use the `Hero` interface whenever passing hero records between service, repository, and transport layers. - Ensure `id` is always a numeric value; do not use string-based identifiers without updating the interface contract. - Provide a non-empty `name` when creating or returning a hero. - Keep gRPC message mapping consistent with this interface, especially field names and numeric ID conversions. # 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) **Extends:** `RuntimeException` # HeroById **Kind:** Interface **Source:** [`sample/04-grpc/src/hero/interfaces/hero-by-id.interface.ts`](https://github.com/nestjs/nest/blob/master/sample/04-grpc/src/hero/interfaces/hero-by-id.interface.ts#L1) `HeroById` defines the payload used to identify a single hero by its numeric ID. It serves as a lightweight contract between gRPC handlers, service methods, and callers that request hero-specific data. ## Properties | Property | Type | |---|---| | `id` | `number` | ## Diagram ```mermaid graph LR Client[Client Request] --> Request[HeroById] Request -->|id: number| HeroService[Hero Service] HeroService --> Hero[Hero Record] ``` ## Usage ```ts import { HeroById } from './interfaces/hero-by-id.interface'; function findHero(request: HeroById) { return heroRepository.findById(request.id); } const heroRequest: HeroById = { id: 1, }; const hero = findHero(heroRequest); ``` ## AI Coding Instructions - Pass hero identifiers using the `HeroById` shape rather than passing raw numeric IDs through request-oriented APIs. - Ensure `id` is a valid number before calling service or repository methods. - Keep this interface aligned with the corresponding gRPC/protobuf request contract if one exists. - Do not add unrelated hero fields to this request type; use separate interfaces for update or creation payloads. # 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) **Extends:** `RuntimeException` # IntegrationModuleOptions **Kind:** Interface **Source:** [`integration/module-utils/src/interfaces/integration-module-options.interface.ts`](https://github.com/nestjs/nest/blob/master/integration/module-utils/src/interfaces/integration-module-options.interface.ts#L1) `IntegrationModuleOptions` defines the connection settings required to configure an integration module. It provides the target service URL and a flag indicating whether the connection should use a secure transport. ## Properties | Property | Type | |---|---| | `url` | `string` | | `secure` | `boolean` | ## Diagram ```mermaid graph LR A[Integration Module] --> B[IntegrationModuleOptions] B --> C[url: string] B --> D[secure: boolean] C --> E[Target Service Endpoint] D --> F[Secure or Non-secure Connection] ``` ## Usage ```ts import type { IntegrationModuleOptions } from './interfaces/integration-module-options.interface'; const integrationOptions: IntegrationModuleOptions = { url: 'https://api.example.com', secure: true, }; function configureIntegration(options: IntegrationModuleOptions) { console.log(`Connecting to ${options.url}`); console.log(`Secure connection enabled: ${options.secure}`); } configureIntegration(integrationOptions); ``` ## AI Coding Instructions - Provide a valid endpoint URL through `url`; avoid passing empty or malformed values. - Set `secure` to `true` when the integration should use HTTPS or another secure transport. - Keep connection-specific configuration centralized in `IntegrationModuleOptions` rather than scattering URL and security flags across module setup code. - Use this interface as the parameter type for integration initialization and configuration functions. # 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) **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) **Extends:** `RuntimeException` # Response **Kind:** Interface **Source:** [`integration/inspector/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/core/interceptors/transform.interceptor.ts#L10) `Response` defines the normalized response shape produced by the inspector transform interceptor. It wraps a payload of type `T` in a `data` property, providing a consistent contract for transformed API responses. ## Properties | Property | Type | |---|---| | `data` | `T` | ## Diagram ```mermaid graph LR A[Controller Result] --> B[Transform Interceptor] B --> C[Response] C --> D[data: T] D --> E[Client Consumer] ``` ## Usage ```ts interface Response { data: T; } interface User { id: string; name: string; } const response: Response = { data: { id: 'user_123', name: 'Ada Lovelace', }, }; console.log(response.data.name); // Ada Lovelace ``` ## AI Coding Instructions - Use `Response` when returning transformed payloads that must follow the `{ data: ... }` response envelope. - Preserve the generic type parameter so consumers retain accurate type information for `data`. - Do not add unrelated top-level fields unless the interceptor contract is updated consistently. - Ensure controller results are compatible with the interceptor’s expected transformation flow. # 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) **Extends:** `RuntimeException` # Response **Kind:** Interface **Source:** [`sample/01-cats-app/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/core/interceptors/transform.interceptor.ts#L10) `Response` defines the standardized shape for transformed API responses in the Cats application. It wraps a payload of type `T` in a `data` property, providing a consistent response contract for interceptors, controllers, and API consumers. ## Properties | Property | Type | |---|---| | `data` | `T` | ## Diagram ```mermaid graph LR Controller[Controller result: T] --> Interceptor[Transform Interceptor] Interceptor --> Response[Response] Response --> Data[data: T] Data --> Client[API client] ``` ## Usage ```ts interface Cat { id: string; name: string; age: number; } const response: Response = { data: { id: 'cat-123', name: 'Milo', age: 3, }, }; console.log(response.data.name); // "Milo" ``` ## AI Coding Instructions - Use `Response` when wrapping successful controller or interceptor output in a consistent `{ data: ... }` envelope. - Preserve the generic type parameter so consumers receive accurate typing for `data`. - Do not add unrelated metadata fields unless the response contract is intentionally expanded across the application. - Ensure transform interceptors return `{ data: value }` rather than the raw controller value. - Update API clients and tests when changing the shape of the wrapped `data` payload. # 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) **Extends:** `RuntimeException` # Response **Kind:** Interface **Source:** [`sample/10-fastify/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/10-fastify/src/core/interceptors/transform.interceptor.ts#L10) `Response` defines the standardized shape returned by the transform interceptor. It wraps a payload in a `data` property, allowing downstream Fastify handlers, clients, and response-processing code to rely on a consistent response envelope. ## Properties | Property | Type | |---|---| | `data` | `T` | ## Diagram ```mermaid graph LR A[Route Handler Result] --> B[Transform Interceptor] B --> C[Response] C --> D[data: T] D --> E[Serialized HTTP Response] ``` ## Usage ```ts interface Response { data: T; } type User = { id: string; name: string; }; const userResponse: Response = { data: { id: "user_123", name: "Ada Lovelace", }, }; // Sent as: // { "data": { "id": "user_123", "name": "Ada Lovelace" } } reply.send(userResponse); ``` ## AI Coding Instructions - Use `Response` whenever returning a successful payload that should follow the application's response-envelope convention. - Keep the actual resource or result inside `data`; do not add unrelated top-level fields unless the interface is intentionally extended. - Preserve the generic type parameter so consumers receive accurate TypeScript inference for `response.data`. - Ensure interceptor logic wraps handler results consistently to avoid mixing raw payloads with `{ data: ... }` responses. - Coordinate API client types and OpenAPI/schema definitions with the `data` wrapper structure. # 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) **Extends:** `RuntimeException` # Response **Kind:** Interface **Source:** [`sample/36-hmr-esm/src/core/interceptors/transform.interceptor.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/core/interceptors/transform.interceptor.ts#L10) `Response` is a generic interface that wraps transformed output produced by the transform interceptor. Its `data` property carries the response payload while preserving the payload's TypeScript type through the interceptor pipeline. ## Properties | Property | Type | |---|---| | `data` | `T` | ## Diagram ```mermaid graph LR A[Controller or Handler Result] --> B[Transform Interceptor] B --> C[Response] C --> D[data: T] D --> E[Serialized Client Response] ``` ## Usage ```ts interface Response { data: T; } type User = { id: string; name: string; }; function transformResponse(value: T): Response { return { data: value, }; } const userResponse = transformResponse({ id: 'user_123', name: 'Ada Lovelace', }); // userResponse.data is typed as User console.log(userResponse.data.name); ``` ## AI Coding Instructions - Use `Response` whenever an interceptor needs to standardize a handler result into a `{ data }` envelope. - Preserve generic type information by passing the original payload type as `T`; avoid using `any` for response data. - Keep the interface focused on response shapingβ€”do not add transport-specific fields unless the interceptor contract requires them. - Ensure downstream serializers and clients read the payload from `response.data`, not directly from the wrapper object. # 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) **Extends:** `RuntimeException` # User **Kind:** Interface **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/users.interfaces.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/users.interfaces.ts#L3) `User` represents a post author or owner within the posts application. It provides a numeric identifier and the collection of `Post` records associated with that user, supporting relationships resolved through the GraphQL federation schema. ## Properties | Property | Type | |---|---| | `id` | `number` | | `posts` | `Post[]` | ## Diagram ```mermaid graph LR U[User] --> ID[id: number] U --> P[posts: Post[]] P --> POST[Post] ``` ## Usage ```ts import type { User } from './users.interfaces'; import type { Post } from './posts.interfaces'; const posts: Post[] = [ { id: 1, title: 'Introducing GraphQL Federation', content: 'A schema-first federation example.', userId: 42, }, ]; const user: User = { id: 42, posts, }; console.log(user.posts.length); // 1 ``` ## AI Coding Instructions - Keep `id` as a numeric user identifier that matches the user reference used by related posts and GraphQL resolvers. - Populate `posts` with objects conforming to the `Post` interface; do not use partial post objects unless the consuming API explicitly permits them. - Resolve the `posts` relationship through the posts data source or federation resolver rather than duplicating post data on the user entity. - Update this interface and the corresponding GraphQL schema together when adding user fields or changing relationship types. # 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) **Extends:** `Error` # 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) **Extends:** `Error` # NewRecipeInput **Kind:** Class **Source:** [`integration/graphql-code-first/src/recipes/dto/new-recipe.input.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/recipes/dto/new-recipe.input.ts#L5) ## Properties | Property | Type | |---|---| | `title` | `string` | | `description` | `string` | | `ingredients` | `string[]` | # NewRecipeInput **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/recipes/dto/new-recipe.input.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/recipes/dto/new-recipe.input.ts#L4) ## Properties | Property | Type | |---|---| | `title` | `string` | | `description` | `string` | | `ingredients` | `string[]` | # NewRecipeInput **Kind:** Class **Source:** [`sample/33-graphql-mercurius/src/recipes/dto/new-recipe.input.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/recipes/dto/new-recipe.input.ts#L4) ## Properties | Property | Type | |---|---| | `title` | `string` | | `description` | `string` | | `ingredients` | `string[]` | # Owner **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/graphql.schema.ts#L32) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | | `age` | `Nullable` | | `cats` | `Nullable` | # Post **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/graphql.schema.ts#L21) ## Properties | Property | Type | |---|---| | `id` | `string` | | `title` | `string` | | `text` | `string` | | `isPublished` | `boolean` | # PostsResolver **Kind:** Class **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/posts/posts.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/posts/posts.resolver.ts#L14) `PostsResolver` exposes GraphQL operations for retrieving individual posts, lists of posts, and associated user data within the posts application. It acts as the GraphQL boundary for the posts domain and participates in the federated schema by resolving post and user-related fields. ## Methods | Method | Signature | Returns | |---|---|---| | `post` | `post(id: number)` | `Post` | | `posts` | `posts()` | `Post[]` | | `user` | `user(post: Post)` | `any` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[PostsResolver] Resolver --> PostQuery[post(): Post] Resolver --> PostsQuery[posts(): Post[]] Resolver --> UserResolver[user(): any] PostQuery --> Post[Post Entity] PostsQuery --> Post UserResolver --> User[User Reference / Entity] ``` ## Usage ```graphql query GetPosts { posts { id title body user { id } } } ``` ```graphql query GetPost { post(id: "post-1") { id title body user { id } } } ``` ```ts // NestJS registers PostsResolver through the posts module. @Module({ providers: [PostsResolver], }) export class PostsModule {} ``` ## AI Coding Instructions - Keep resolver methods focused on GraphQL orchestration; move persistence and business logic into dedicated services when adding functionality. - Preserve the GraphQL return types for `post()` and `posts()` so the generated schema remains compatible with federated consumers. - When resolving `user()` data, return a federation-compatible entity reference (typically containing the user key, such as `id`) rather than duplicating user-service data. - Add arguments, nullability, and field decorators consistently when extending queries to avoid schema generation mismatches. - Update or add GraphQL integration tests whenever changing resolver fields, entity keys, or response shapes. # PostsResolver **Kind:** Class **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/posts.resolver.ts#L12) `PostsResolver` exposes the GraphQL operations for retrieving posts and resolving each post's related user. It connects the posts application service to the federated GraphQL schema, including the `user` field that references an entity owned by another subgraph. ## Methods | Method | Signature | Returns | |---|---|---| | `findPost` | `findPost(id: number)` | `void` | | `getPosts` | `getPosts()` | `void` | | `user` | `user(post: Post)` | `any` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Resolver[PostsResolver] Resolver -->|findPost| PostsService[Posts Service] Resolver -->|getPosts| PostsService Resolver -->|user field resolver| UserReference[User Federation Reference] PostsService --> PostsStore[(Posts Data)] UserReference --> UsersSubgraph[Users Subgraph] ``` ## Usage ```ts // Query the Posts GraphQL API exposed by PostsResolver. const query = ` query GetPosts { getPosts { id title user { id name } } } `; const response = await fetch('http://localhost:3000/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }), }); const { data, errors } = await response.json(); if (errors) { throw new Error(errors.map((error) => error.message).join(', ')); } console.log(data.getPosts); ``` ## AI Coding Instructions - Keep query resolver names aligned with the schema-first GraphQL definitions, especially `findPost` and `getPosts`. - Delegate post retrieval and persistence logic to the posts service; keep resolver methods focused on GraphQL argument handling and response shaping. - Preserve the `user` field resolver as a federation entity reference rather than directly fetching user data from the posts service. - When adding fields to `Post`, update both the GraphQL schema and resolver behavior where a field requires custom resolution. - Ensure federation references include the correct entity key, typically the related user's `id` and `__typename`. # RedisIoAdapter **Kind:** Class **Source:** [`sample/02-gateways/src/adapters/redis-io.adapter.ts`](https://github.com/nestjs/nest/blob/master/sample/02-gateways/src/adapters/redis-io.adapter.ts#L6) `RedisIoAdapter` extends NestJS's Socket.IO adapter to enable Redis-backed WebSocket scaling. It connects Redis publisher and subscriber clients, then applies the Socket.IO Redis adapter so gateway events can be broadcast across multiple application instances. **Extends:** `IoAdapter` ## Methods | Method | Signature | Returns | |---|---|---| | `connectToRedis` | `connectToRedis()` | `Promise` | | `createIOServer` | `createIOServer(port: number, options: ServerOptions)` | `any` | ## When something fails - `RedisIoAdapter` handles failure in 1 place: it turns it into a return value in all 1. ## Diagram ```mermaid graph LR App[NestJS Application] --> Adapter[RedisIoAdapter] Adapter --> Pub[Redis Publisher Client] Adapter --> Sub[Redis Subscriber Client] Pub --> Redis[(Redis)] Sub --> Redis Adapter --> IOServer[Socket.IO Server] IOServer --> Gateways[NestJS Gateways] ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { RedisIoAdapter } from './adapters/redis-io.adapter'; async function bootstrap() { const app = await NestFactory.create(AppModule); const redisIoAdapter = new RedisIoAdapter(app); await redisIoAdapter.connectToRedis(); app.useWebSocketAdapter(redisIoAdapter); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Call `connectToRedis()` before registering the adapter with `app.useWebSocketAdapter()`; otherwise the Socket.IO server may not have a Redis adapter configured. - Keep Redis connection setup asynchronous and ensure both publisher and subscriber clients are connected before creating the Socket.IO adapter. - Use this adapter when running multiple NestJS instances that need to share Socket.IO rooms, broadcasts, and gateway events. - Preserve the call to the parent `createIOServer()` implementation, then attach the Redis adapter to the returned Socket.IO server. - Ensure Redis connection settings match the deployment environment, including host, port, authentication, and TLS requirements. # ServerGateway **Kind:** Class **Source:** [`integration/websockets/src/server.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/server.gateway.ts#L6) `ServerGateway` is a WebSocket gateway used by the integration test application to receive pushed events from connected clients. It exposes `onPush()` as the event handler and tracks the route or path that invoked the gateway through `getPathCalled()`. **Implements:** `OnApplicationShutdown` ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(client: undefined, data: undefined)` | `void` | | `getPathCalled` | `getPathCalled(client: undefined, data: undefined)` | `void` | ## Properties | Property | Type | |---|---| | `onApplicationShutdown` | `any` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|push event| Gateway[ServerGateway] Gateway -->|onPush()| Handler[Push Event Handler] Handler -->|records path| State[Gateway State] State -->|getPathCalled()| Test[Test or Consumer] ``` ## Usage ```ts import { ServerGateway } from './server.gateway'; const gateway = new ServerGateway(); // Typically invoked by the WebSocket framework when a client emits a push event. gateway.onPush({ path: '/notifications', message: 'Hello from the client', }); // Read the path captured by the gateway. const path = gateway.getPathCalled(); console.log(path); // "/notifications" ``` ## AI Coding Instructions - Keep `onPush()` focused on handling the incoming WebSocket event and recording only the state required by consumers or integration tests. - Use `getPathCalled()` to inspect captured routing information instead of accessing gateway state directly. - Preserve the gateway's event contract when changing payload handling; connected WebSocket clients may depend on its current event shape. - When adding handlers, follow the existing WebSocket decorator and event-naming conventions used by the integration application. # 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) **Extends:** `RuntimeException` # 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) **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) **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) **Extends:** `RuntimeException` # UpdatePost **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/graphql.schema.ts#L14) ## Properties | Property | Type | |---|---| | `id` | `string` | | `title` | `Nullable` | | `text` | `Nullable` | | `isPublished` | `Nullable` | # UserDto **Kind:** Class **Source:** [`integration/microservices/src/kafka/dtos/user.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/dtos/user.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `email` | `string` | | `phone` | `string` | | `years` | `number` | # BusinessDto **Kind:** Class **Source:** [`integration/microservices/src/kafka/dtos/business.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka/dtos/business.dto.ts#L3) ## Properties | Property | Type | |---|---| | `name` | `string` | | `phone` | `string` | | `user` | `UserEntity` | # CatsService **Kind:** Class **Source:** [`sample/09-babel-example/src/cats/cats.service.js`](https://github.com/nestjs/nest/blob/master/sample/09-babel-example/src/cats/cats.service.js#L3) `CatsService` provides the core operations for managing cat records in the cats module. It exposes methods to create new cats and retrieve the full collection, typically serving as the business-logic layer between controllers and persistence or in-memory data. ## Methods | Method | Signature | Returns | |---|---|---| | `create` | `create(cat: undefined)` | `void` | | `findAll` | `findAll()` | `void` | ## Diagram ```mermaid graph LR Client[Client Request] --> Controller[Cats Controller] Controller --> Service[CatsService] Service --> Create[create()] Service --> FindAll[findAll()] Create --> Storage[Cat Storage] FindAll --> Storage ``` ## Usage ```javascript import { CatsService } from './cats.service.js'; const catsService = new CatsService(); // Create a cat record. const createdCat = catsService.create({ name: 'Milo', age: 3, breed: 'Tabby', }); // Retrieve all available cats. const cats = catsService.findAll(); console.log(createdCat); console.log(cats); ``` ## AI Coding Instructions - Keep cat-related business logic in `CatsService`; controllers should delegate creation and retrieval operations to this class. - Use `create()` for validating, transforming, and persisting new cat data before returning it. - Use `findAll()` as the single access point for retrieving cat collections rather than accessing storage directly. - Keep method return values consistent so controller and API consumers can reliably handle created records and lists. - When adding persistence, update the service implementation while preserving the public `create()` and `findAll()` method contracts. # ComplexityPlugin **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/common/plugins/complexity.plugin.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/common/plugins/complexity.plugin.ts#L11) `ComplexityPlugin` is an Apollo GraphQL server plugin that evaluates incoming GraphQL operations for query complexity. It hooks into the request lifecycle through `requestDidStart()` and can reject overly expensive queries before they are executed. **Implements:** `ApolloServerPlugin` ## Methods | Method | Signature | Returns | |---|---|---| | `requestDidStart` | `requestDidStart()` | `Promise>` | ## Where it refuses work - `ComplexityPlugin` stops the work with `GraphQLError` when `complexity >= 20`. ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Apollo[Apollo GraphQL Server] Apollo --> Plugin[ComplexityPlugin] Plugin --> Operation[Resolved GraphQL Operation] Operation --> Calculator[Complexity Calculation] Calculator --> Decision{Within limit?} Decision -->|Yes| Resolver[Execute Resolvers] Decision -->|No| Error[Return GraphQL Error] ``` ## Usage ```ts import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; import { GraphQLModule } from '@nestjs/graphql'; import { Module } from '@nestjs/common'; import { ComplexityPlugin } from './common/plugins/complexity.plugin'; @Module({ imports: [ GraphQLModule.forRoot({ driver: ApolloDriver, autoSchemaFile: true, plugins: [new ComplexityPlugin()], }), ], }) export class AppModule {} ``` ```graphql query GetUsersWithPosts { users { id name posts { id title } } } ``` ## AI Coding Instructions - Register `ComplexityPlugin` in the Apollo `plugins` configuration so it participates in every GraphQL request lifecycle. - Keep complexity validation inside `didResolveOperation` or another pre-execution lifecycle hook to avoid running expensive resolvers first. - Update complexity estimators and maximum thresholds carefully; overly restrictive limits can reject valid nested queries. - Ensure schema fields expose appropriate complexity metadata when some fields are significantly more expensive than others. - Return a clear GraphQL error when a query exceeds the allowed complexity so API consumers can simplify their operation. # CreateCatDto **Kind:** Class **Source:** [`integration/mongoose/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/mongoose/src/cats/dto/create-cat.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # CreateCatDto **Kind:** Class **Source:** [`sample/06-mongoose/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/dto/create-cat.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # CreateCatDto **Kind:** Class **Source:** [`sample/14-mongoose-base/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/14-mongoose-base/src/cats/dto/create-cat.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # DurableContextIdStrategy **Kind:** Class **Source:** [`integration/scopes/src/durable/durable-context-id.strategy.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/durable/durable-context-id.strategy.ts#L11) `DurableContextIdStrategy` implements a custom NestJS context ID strategy for durable request-scoped providers. Its `attach()` method associates incoming requests with a reusable context subtree, allowing providers to be shared across related requests instead of being recreated for every request. **Implements:** `ContextIdStrategy` ## Methods | Method | Signature | Returns | |---|---|---| | `attach` | `attach(contextId: ContextId, request: Request)` | `void` | ## Diagram ```mermaid graph LR Request[Incoming Request] --> Factory[ContextIdFactory] Factory --> Strategy[DurableContextIdStrategy] Strategy --> Attach[attach()] Attach --> DurableContext[Durable Context Subtree] DurableContext --> Providers[Request-scoped Providers] ``` ## Usage ```ts import { ContextIdFactory } from '@nestjs/core'; import { DurableContextIdStrategy } from './durable/durable-context-id.strategy'; async function bootstrap() { // Register the strategy before handling application requests. ContextIdFactory.apply(new DurableContextIdStrategy()); // Create and start your Nest application as usual. // const app = await NestFactory.create(AppModule); // await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Register this strategy through `ContextIdFactory.apply()` during application bootstrap, before requests are processed. - Keep `attach()` focused on mapping a request to the correct durable context payload and context subtree. - Ensure the request data used for context reuse is stable and uniquely identifies the intended shared scope, such as a tenant or session identifier. - Do not use highly volatile request values as durable context keys, or request-scoped providers will not be reused effectively. - Verify that providers intended to participate in this lifecycle are configured as request-scoped and support durable context behavior. ## How it works ## `DurableContextIdStrategy` `DurableContextIdStrategy` is a Nest `ContextIdStrategy` implementation whose `attach` method returns a context-ID resolver and a request payload. [integration/scopes/src/durable/durable-context-id.strategy.ts:1-2](integration/scopes/src/durable/durable-context-id.strategy.ts#L1-L2) [integration/scopes/src/durable/durable-context-id.strategy.ts:11-34](integration/scopes/src/durable/durable-context-id.strategy.ts#L11-L34) # EventsGateway **Kind:** Class **Source:** [`sample/16-gateways-ws/src/events/events.gateway.ts`](https://github.com/nestjs/nest/blob/master/sample/16-gateways-ws/src/events/events.gateway.ts#L11) `EventsGateway` is a WebSocket gateway that handles incoming `event` messages and streams responses back to connected clients. Its `onEvent()` handler returns an RxJS `Observable` of `WsResponse` values, allowing the gateway to emit asynchronous event data through the WebSocket connection. ## Methods | Method | Signature | Returns | |---|---|---| | `onEvent` | `onEvent(client: any, data: any)` | `Observable>` | ## Properties | Property | Type | |---|---| | `server` | `Server` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|emit: event| Gateway[EventsGateway] Gateway -->|onEvent()| Stream[Observable>] Stream -->|emit responses| Client ``` ## Usage ```ts import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); socket.emit('event', {}); socket.on('event', (response: number) => { console.log('Received event response:', response); }); ``` ## AI Coding Instructions - Keep WebSocket handlers in `EventsGateway` focused on transport concerns; move reusable business logic into injectable services. - Return `Observable>` when a handler needs to stream multiple asynchronous responses to a client. - Ensure emitted client event names match the `@SubscribeMessage()` event name configured for `onEvent()`. - Use `WsResponse` objects with explicit `event` and `data` fields when sending named responses back to clients. - Handle client disconnects and subscription cleanup when adding long-lived or resource-intensive streams. ## How it works `EventsGateway` is an exported Nest WebSocket gateway class configured with the numeric decorator argument `8080`. [events.gateway.ts:11-12] - The `EventsModule` registers it as a provider, and `AppModule` imports that module. [events.module.ts:4-7] [app.module.ts:4-7] - The application selects Nest’s `WsAdapter` and starts its application listener on port `3000`. [main.ts:5-10] - Its `server` field is declared as a `ws` `Server` and marked with `@WebSocketServer()`. The class itself does not read from or write to this field. [events.gateway.ts:9,13-14] - `onEvent` is marked to handle the `'events'` message name. It accepts `client` and `data` values typed as `any`, but its implementation does not inspect either argument. [events.gateway.ts:16-18] - The handler returns an `Observable>`. Its source sequence is `[1, 2, 3]`, and it maps each value to an object with `event: 'events'` and that value as `data`; the resulting sequence is therefore `{ event: 'events', data: 1 }`, `{ event: 'events', data: 2 }`, and `{ event: 'events', data: 3 }`. [events.gateway.ts:7-8,17-18] - No input validation, conditional handling, explicit error throwing, or direct I/O appears in `onEvent`. [events.gateway.ts:16-18] # IMutation **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/graphql.schema.ts#L34) `IMutation` defines the GraphQL mutation contract for managing `Post` records in the Prisma-backed API. It exposes operations to create, update, and delete posts, returning either a `Post`, a nullable post result when no matching record exists, or a promise of those values. ## Methods | Method | Signature | Returns | |---|---|---| | `createPost` | `createPost(input: NewPost)` | `Post | Promise` | | `updatePost` | `updatePost(input: UpdatePost)` | `Nullable | Promise>` | | `deletePost` | `deletePost(id: string)` | `Nullable | Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[IMutation] Mutation --> Create[createPost] Mutation --> Update[updatePost] Mutation --> Delete[deletePost] Create --> Prisma[Prisma Client] Update --> Prisma Delete --> Prisma Prisma --> Post[(Post)] ``` ## Usage ```ts import type { IMutation } from './graphql.schema'; const mutations: IMutation = { async createPost() { return prisma.post.create({ data: { title: 'Hello GraphQL', content: 'Created through a mutation resolver.', }, }); }, async updatePost() { const post = await prisma.post.findUnique({ where: { id: 'post-id' }, }); if (!post) { return null; } return prisma.post.update({ where: { id: post.id }, data: { title: 'Updated title' }, }); }, async deletePost() { const post = await prisma.post.findUnique({ where: { id: 'post-id' }, }); if (!post) { return null; } return prisma.post.delete({ where: { id: post.id }, }); }, }; ``` ## AI Coding Instructions - Implement each `IMutation` method as a GraphQL resolver backed by the Prisma `post` model. - Return `null` from `updatePost` and `deletePost` when the requested post does not exist; do not throw for expected missing-record cases. - Preserve the declared return types: `createPost` must return a `Post`, while update and delete operations may return `Nullable`. - Keep database access in Prisma calls and validate mutation input before creating or updating records. - Ensure resolver argument types and GraphQL schema fields remain aligned with the `IMutation` interface. # IQuery **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/graphql.schema.ts#L14) `IQuery` defines the GraphQL query contract for retrieving `Cat` data in the schema-first sample. It exposes a collection query via `cats()` and a single-item query via `cat()`, allowing implementations to return either synchronous values or promises while preserving GraphQL nullability. ## Methods | Method | Signature | Returns | |---|---|---| | `cats` | `cats()` | `| Nullable[]> | Promise[]>>` | | `cat` | `cat(id: string)` | `Nullable | Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Query[IQuery] Query --> Cats[cats(): nullable Cat list] Query --> Cat[cat(): nullable Cat] Cats --> CatType[Cat] Cat --> CatType ``` ## Usage ```ts import type { IQuery, Cat } from './graphql.schema'; const query: IQuery = { cats(): Cat[] { return [ { id: '1', name: 'Milo' }, { id: '2', name: 'Luna' }, ]; }, async cat(): Promise { return { id: '1', name: 'Milo' }; }, }; // Use the query implementation as the GraphQL root resolver. const cats = await query.cats(); const cat = await query.cat(); ``` ## AI Coding Instructions - Implement `cats()` to return an array of `Cat` values, allowing individual entries and the entire result to be `null` when required by the schema. - Implement `cat()` to return a `Cat` instance or `null` when no matching record exists. - Both methods may return values directly or wrap results in `Promise`s; keep resolver behavior consistent with the surrounding data-access layer. - Preserve the declared nullability contract rather than throwing errors for normal β€œnot found” query results. - Connect `IQuery` implementations to the GraphQL root query resolver when configuring the schema-first server. # Order **Kind:** Class **Source:** [`sample/30-event-emitter/src/orders/entities/order.entity.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/entities/order.entity.ts#L1) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | | `description` | `string` | # RecipesArgs **Kind:** Class **Source:** [`integration/graphql-code-first/src/recipes/dto/recipes.args.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/recipes/dto/recipes.args.ts#L4) ## Properties | Property | Type | |---|---| | `skip` | `any` | | `take` | `any` | # RecipesArgs **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/recipes/dto/recipes.args.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/recipes/dto/recipes.args.ts#L4) ## Properties | Property | Type | |---|---| | `skip` | `any` | | `take` | `any` | # RecipesArgs **Kind:** Class **Source:** [`sample/33-graphql-mercurius/src/recipes/dto/recipes.args.ts`](https://github.com/nestjs/nest/blob/master/sample/33-graphql-mercurius/src/recipes/dto/recipes.args.ts#L4) ## Properties | Property | Type | |---|---| | `skip` | `any` | | `take` | `any` | # RoleEntity **Kind:** Class **Source:** [`sample/21-serializer/src/entities/role.entity.ts`](https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/entities/role.entity.ts#L1) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | # TestDto **Kind:** Class **Source:** [`integration/hello-world/src/hello/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/hello/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/hello-world/src/host/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/hello-world/src/host-array/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/hello-world/src/host-array/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/inspector/src/circular-hello/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/circular-hello/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/scopes/src/circular-hello/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-hello/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/scopes/src/circular-transient/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/circular-transient/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/scopes/src/hello/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/hello/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/scopes/src/msvc/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/msvc/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # TestDto **Kind:** Class **Source:** [`integration/scopes/src/transient/dto/test.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/scopes/src/transient/dto/test.dto.ts#L3) ## Properties | Property | Type | |---|---| | `string` | `string` | | `number` | `number` | # UpdateCatDto **Kind:** Class **Source:** [`sample/06-mongoose/src/cats/dto/update-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/dto/update-cat.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `age` | `number` | | `breed` | `string` | # User **Kind:** Class **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/posts/models/user.model.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/posts/models/user.model.ts#L4) ## Properties | Property | Type | |---|---| | `id` | `number` | | `posts` | `Post[]` | # User **Kind:** Class **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/models/user.model.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/models/user.model.ts#L4) ## Properties | Property | Type | |---|---| | `id` | `number` | | `posts` | `Post[]` | # User **Kind:** Class **Source:** [`sample/31-graphql-federation-code-first/users-application/src/users/models/user.model.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/users-application/src/users/models/user.model.ts#L3) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | # User **Kind:** Class **Source:** [`sample/32-graphql-federation-schema-first/users-application/src/users/models/user.model.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/users-application/src/users/models/user.model.ts#L3) ## Properties | Property | Type | |---|---| | `id` | `number` | | `name` | `string` | # UsersResolver **Kind:** Class **Source:** [`sample/31-graphql-federation-code-first/users-application/src/users/users.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/users-application/src/users/users.resolver.ts#L5) `UsersResolver` exposes `User` entities through the GraphQL API in a code-first Apollo Federation service. It provides a `getUser` query for retrieving a user and a `resolveReference` handler that lets the federation gateway resolve `User` references originating from other subgraphs. ## Methods | Method | Signature | Returns | |---|---|---| | `getUser` | `getUser(id: number)` | `User` | | `resolveReference` | `resolveReference(reference: { __typename: string; id: number })` | `User` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Gateway[Apollo Federation Gateway] Gateway --> UsersResolver[UsersResolver] UsersResolver --> GetUser[getUser()] UsersResolver --> ResolveReference[resolveReference()] GetUser --> User[User Entity] ResolveReference --> User ``` ## Usage ```ts // Query the Users subgraph through the federation gateway. const query = ` query GetUser { getUser { id name } } `; const response = await fetch('http://localhost:3000/graphql', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query }), }); const { data } = await response.json(); console.log(data.getUser); ``` ## AI Coding Instructions - Keep `UsersResolver` focused on GraphQL concerns; move persistence and business logic into an injected users service when needed. - Ensure `getUser()` returns a value that matches the code-first `User` GraphQL object type. - Maintain the federation entity key fields expected by `resolveReference()` so other subgraphs can resolve `User` references correctly. - Add authorization and validation at resolver boundaries if user data becomes tenant-specific or sensitive. - Register the resolver and its related `User` type in the appropriate NestJS module and federation GraphQL configuration. # UsersResolver **Kind:** Class **Source:** [`sample/32-graphql-federation-schema-first/users-application/src/users/users.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/users-application/src/users/users.resolver.ts#L4) `UsersResolver` exposes user data through the GraphQL API and acts as the federation entity resolver for `User` records. It handles direct user lookup through `getUser()` and resolves federated `User` references through `resolveReference()` by delegating to the users service. ## Methods | Method | Signature | Returns | |---|---|---| | `getUser` | `getUser(id: number)` | `void` | | `resolveReference` | `resolveReference(reference: { __typename: string; id: number })` | `void` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Query[getUser Query] Gateway[Apollo Federation Gateway] --> Reference[User Entity Reference] Query --> UsersResolver[UsersResolver] Reference --> ResolveReference[resolveReference] UsersResolver --> GetUser[getUser] GetUser --> UsersService[UsersService] ResolveReference --> UsersService UsersService --> UserStore[(User Data)] ``` ## Usage ```ts import { UsersResolver } from './users.resolver'; import { UsersService } from './users.service'; const usersService = { findOneById: async (id: string) => ({ id, name: 'Ada Lovelace', }), } as UsersService; const resolver = new UsersResolver(usersService); // Resolve a regular GraphQL query. const user = await resolver.getUser('user-1'); // Resolve a federated entity reference from another subgraph. const referencedUser = await resolver.resolveReference({ __typename: 'User', id: 'user-1', }); console.log(user, referencedUser); ``` ## AI Coding Instructions - Keep resolver methods thin: delegate user retrieval and business logic to `UsersService`. - Ensure `getUser()` and `resolveReference()` use the same identifier lookup behavior so direct queries and federation references return consistent results. - Preserve the federation reference shape, including `__typename` and the entity key (typically `id`). - Register new GraphQL fields and entity keys in the schema-first GraphQL schema before adding matching resolver methods. - Handle missing users consistently with the rest of the application, such as returning `null` or throwing the project’s expected GraphQL error. # CircularModule **Kind:** Class **Source:** [`integration/injector/src/circular-structure-dynamic-module/circular.module.ts`](https://github.com/nestjs/nest/blob/master/integration/injector/src/circular-structure-dynamic-module/circular.module.ts#L4) `CircularModule` is a NestJS dynamic module used to configure providers that participate in a circular dependency structure. Its `forRoot()` factory method returns a `DynamicModule`, allowing the module to register its dependencies during application bootstrap. ## Methods | Method | Signature | Returns | |---|---|---| | `forRoot` | `forRoot()` | `DynamicModule` | ## Diagram ```mermaid graph LR AppModule[Application Module] -->|imports| CircularModule[CircularModule] CircularModule -->|forRoot()| DynamicModule[NestJS DynamicModule] DynamicModule --> Providers[Circular Structure Providers] Providers -->|circular references| Providers ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { CircularModule } from './circular-structure-dynamic-module/circular.module'; @Module({ imports: [ CircularModule.forRoot(), ], }) export class AppModule {} ``` ## AI Coding Instructions - Import `CircularModule.forRoot()` in the root or feature module that needs the circular dependency providers. - Preserve the `DynamicModule` return type and NestJS module metadata structure when extending `forRoot()`. - Use NestJS `forwardRef()` where provider or module imports require explicit circular-reference resolution. - Avoid registering the same circular providers both manually and through `CircularModule.forRoot()`, as this can create duplicate instances. # CoreGateway **Kind:** Class **Source:** [`integration/websockets/src/core.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/core.gateway.ts#L8) `CoreGateway` is the WebSocket integration gateway for core-level push events. Its `onPush()` handler receives or processes push activity and bridges it to connected WebSocket consumers within the application. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(client: undefined, data: undefined)` | `void` | ## Diagram ```mermaid graph LR Core[Core application events] --> Gateway[CoreGateway] Gateway --> Push[onPush()] Push --> Clients[Connected WebSocket clients] ``` ## Usage ```ts import { CoreGateway } from './core.gateway'; // Resolve the gateway through the application's dependency-injection container. const coreGateway = app.get(CoreGateway); // Trigger the gateway's push handling flow. coreGateway.onPush(); ``` ## AI Coding Instructions - Keep WebSocket-specific event handling inside `CoreGateway`; avoid leaking transport concerns into core business services. - Preserve the `onPush()` method contract when adding push-related behavior or integrations. - Resolve the gateway through dependency injection rather than creating it manually when it depends on application services. - Ensure new push flows handle disconnected or unavailable WebSocket clients safely. # CreateCatInput **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/graphql.schema.ts#L9) ## Properties | Property | Type | |---|---| | `name` | `Nullable` | | `age` | `Nullable` | # CreateOrderDto **Kind:** Class **Source:** [`sample/30-event-emitter/src/orders/dto/create-order.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/dto/create-order.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `description` | `string` | # CreateUserDto **Kind:** Class **Source:** [`sample/05-sql-typeorm/src/users/dto/create-user.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/05-sql-typeorm/src/users/dto/create-user.dto.ts#L1) ## Properties | Property | Type | |---|---| | `firstName` | `string` | | `lastName` | `string` | # CreateUserDto **Kind:** Class **Source:** [`sample/07-sequelize/src/users/dto/create-user.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/07-sequelize/src/users/dto/create-user.dto.ts#L1) ## Properties | Property | Type | |---|---| | `firstName` | `string` | | `lastName` | `string` | # DurableContextIdStrategy **Kind:** Class **Source:** [`integration/inspector/src/durable/durable-context-id.strategy.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/durable/durable-context-id.strategy.ts#L6) `DurableContextIdStrategy` defines how NestJS associates incoming requests with dependency-injection context IDs. Its `attach()` method enables durable providers to reuse a stable context subtree while preserving a request-specific context for non-durable providers. **Implements:** `ContextIdStrategy` ## Methods | Method | Signature | Returns | |---|---|---| | `attach` | `attach(contextId: ContextId, request: Request)` | `void` | ## Diagram ```mermaid graph LR R[Incoming request] --> A[DurableContextIdStrategy.attach] A --> C[Request Context ID] A --> D[Durable Context ID] D --> P[Durable provider subtree] C --> N[Non-durable request-scoped providers] ``` ## Usage ```ts import { ContextIdFactory } from '@nestjs/core'; import { DurableContextIdStrategy } from './durable-context-id.strategy'; // Register the strategy during application bootstrap. ContextIdFactory.apply(new DurableContextIdStrategy()); ``` ## AI Coding Instructions - Register this strategy through `ContextIdFactory.apply()` before handling requests. - Keep `attach()` focused on mapping a request context to the appropriate durable and non-durable provider trees. - Return the request context ID for providers that are not marked as durable. - Ensure durable context IDs are stable for the intended reuse boundary, such as a tenant, session, or aggregate key. - Avoid storing unbounded durable contexts without an eviction or cleanup strategy. # ErrorGateway **Kind:** Class **Source:** [`integration/websockets/src/error.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/error.gateway.ts#L8) `ErrorGateway` is a WebSocket gateway used by the integration layer to handle push-style socket interactions that result in an error flow. Its `onPush()` handler is the entry point for the configured push event and helps verify that WebSocket errors are propagated through the application's gateway and exception-handling pipeline. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush()` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|push event| Gateway[ErrorGateway] Gateway -->|onPush()| ErrorFlow[WebSocket Error Flow] ErrorFlow --> Client ``` ## Usage ```ts import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); socket.on('connect', () => { // Sends the event handled by ErrorGateway.onPush(). socket.emit('push', { message: 'Trigger gateway error handling' }); }); socket.on('exception', (error) => { console.error('Gateway returned an error:', error); }); ``` ## AI Coding Instructions - Keep `onPush()` aligned with the WebSocket event name and payload contract expected by connected clients. - Route failures through the framework's WebSocket exception mechanism instead of silently swallowing errors. - When changing error payloads, update integration tests and client-side listeners for emitted error events. - Avoid exposing internal stack traces, implementation details, or sensitive data in socket error responses. ## How it works - `ErrorGateway` is an exported Nest WebSocket gateway class. `@WebSocketGateway(8080)` marks the class with gateway metadata and records port `8080`; the decorator also records an empty options object when none is passed. [integration/websockets/src/error.gateway.ts:8-9](integration/websockets/src/error.gateway.ts#L8-L9) [packages/websockets/decorators/socket-gateway.decorator.ts:20-29](packages/websockets/decorators/socket-gateway.decorator.ts#L20-L29) - Its `onPush` method is mapped to the WebSocket message pattern `'push'` by `@SubscribeMessage('push')`. That decorator stores message-mapping metadata and the `'push'` pattern on the method. [integration/websockets/src/error.gateway.ts:10-11](integration/websockets/src/error.gateway.ts#L10-L11) [packages/websockets/decorators/subscribe-message.decorator.ts:8-17](packages/websockets/decorators/subscribe-message.decorator.ts#L8-L17) - When the mapped handler runs, it returns an RxJS error observable whose error is `new WsException('test')`; it does not produce a normal value. [integration/websockets/src/error.gateway.ts:11-12](integration/websockets/src/error.gateway.ts#L11-L12) The `WsException` constructor stores the string error and sets its `message` to that string. [packages/websockets/errors/ws-exception.ts:3-11](packages/websockets/errors/ws-exception.ts#L3-L11) - Nest’s WebSocket proxy detects observable return values and installs `catchError`; when this observable errors, it sends the error to the WebSocket exceptions handler and replaces the stream with `EMPTY`. [packages/websockets/context/ws-proxy.ts:15-25](packages/websockets/context/ws-proxy.ts#L15-L25) - With the default exception handler, a string-valued `WsException` emits an `'exception'` event to the client with `{ status: 'error', message: 'test' }`. The default filter includes the triggering message’s pattern and data as `cause`, using `{ pattern, data }`. [packages/websockets/exceptions/base-ws-exception-filter.ts:51-55](packages/websockets/exceptions/base-ws-exception-filter.ts#L51-L55) [packages/websockets/exceptions/base-ws-exception-filter.ts:76-92](packages/websockets/exceptions/base-ws-exception-filter.ts#L76-L92) The integration test sends `'push'` with `{ test: 'test' }` and expects the client event payload to include that exact cause. [integration/websockets/e2e/error-gateway.spec.ts:20-35](integration/websockets/e2e/error-gateway.spec.ts#L20-L35) - `onPush` declares no parameters and contains no explicit input validation or alternate error path. [integration/websockets/src/error.gateway.ts:10-13](integration/websockets/src/error.gateway.ts#L10-L13) For Nest to connect the gateway, an instance must appear among module providers; the socket module scans providers and connects only classes carrying gateway metadata. [packages/websockets/socket-module.ts:62-95](packages/websockets/socket-module.ts#L62-L95) # ExamplePathGateway **Kind:** Class **Source:** [`integration/websockets/src/example-path.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/example-path.gateway.ts#L3) `ExamplePathGateway` is a WebSocket gateway that handles inbound `push` messages through its `onPush()` handler. It provides a focused integration point for clients connected through the gateway's configured WebSocket path and delegates message-processing behavior to the gateway layer. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(client: undefined, data: undefined)` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|emit "push"| Gateway[ExamplePathGateway] Gateway -->|onPush()| Handler[Push Message Handling] Handler -->|response or emitted event| Client ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ExamplePathGateway } from './example-path.gateway'; @Module({ providers: [ExamplePathGateway], }) export class AppModule {} ``` ```ts import { io } from 'socket.io-client'; // Use the path configured by ExamplePathGateway. const socket = io('http://localhost:3000', { path: '/example', }); socket.emit('push', { message: 'Hello from the client', }); ``` ## AI Coding Instructions - Keep WebSocket event handling inside `onPush()` focused on validating and processing the incoming payload. - Register `ExamplePathGateway` in the relevant Nest module's `providers` array; do not instantiate it manually. - Ensure clients use the same Socket.IO/WebSocket path configured by the gateway. - Preserve the `push` event contract when changing payloads, emitted events, or handler return values. # HttpExceptionFilter **Kind:** Class **Source:** [`integration/inspector/src/common/filters/http-exception.filter.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/common/filters/http-exception.filter.ts#L8) `HttpExceptionFilter` is a NestJS exception filter that intercepts HTTP exceptions raised during request handling. Its `catch()` method converts exceptions into consistent HTTP error responses, allowing the Inspector service to centralize error formatting and status-code handling. **Implements:** `ExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: HttpException, host: ArgumentsHost)` | `void` | ## Diagram ```mermaid graph LR Client[HTTP Client] --> Controller[NestJS Controller / Service] Controller -->|Throws HttpException| Filter[HttpExceptionFilter] Filter -->|catch()| Context[ArgumentsHost HTTP Context] Context --> Response[Formatted HTTP Error Response] Response --> Client ``` ## Usage ```ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { HttpExceptionFilter } from './common/filters/http-exception.filter'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalFilters(new HttpExceptionFilter()); await app.listen(3000); } bootstrap(); ``` ## AI Coding Instructions - Register `HttpExceptionFilter` globally when consistent error responses are required across Inspector HTTP endpoints. - Keep exception handling inside `catch()` focused on HTTP concerns: status codes, request context, and response serialization. - Throw NestJS `HttpException` subclasses such as `BadRequestException` or `NotFoundException` so the filter can preserve the intended HTTP status. - Do not write directly to the response after an exception has been handled by this filter; a response can only be sent once. # HttpExceptionFilter **Kind:** Class **Source:** [`sample/01-cats-app/src/common/filters/http-exception.filter.ts`](https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/filters/http-exception.filter.ts#L8) `HttpExceptionFilter` is a NestJS exception filter that intercepts `HttpException` instances thrown during HTTP request handling. It converts exceptions into a consistent JSON error response containing the status code, timestamp, and requested path. **Implements:** `ExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: HttpException, host: ArgumentsHost)` | `void` | ## Diagram ```mermaid graph LR A[HTTP Request] --> B[Controller / Service] B -->|Throws HttpException| C[HttpExceptionFilter.catch] C --> D[Extract HTTP Response and Request] D --> E[Return JSON Error Response] ``` ## Usage ```ts import { Controller, Get, HttpException, HttpStatus, UseFilters } from '@nestjs/common'; import { HttpExceptionFilter } from './common/filters/http-exception.filter'; @Controller('cats') @UseFilters(HttpExceptionFilter) export class CatsController { @Get() findAll() { throw new HttpException( 'Cats are temporarily unavailable', HttpStatus.SERVICE_UNAVAILABLE, ); } } ``` ## AI Coding Instructions - Apply this filter with `@UseFilters(HttpExceptionFilter)` or register it globally when consistent HTTP error formatting is required. - Only `HttpException` instances are handled; use NestJS HTTP exception classes such as `NotFoundException` or `BadRequestException`. - Preserve the response shape (`statusCode`, `timestamp`, and `path`) if API consumers depend on it. - Use `host.switchToHttp()` only for HTTP transports; create transport-specific filters for GraphQL, WebSockets, or microservices. # HttpExceptionFilter **Kind:** Class **Source:** [`sample/36-hmr-esm/src/common/filters/http-exception.filter.ts`](https://github.com/nestjs/nest/blob/master/sample/36-hmr-esm/src/common/filters/http-exception.filter.ts#L8) `HttpExceptionFilter` is a NestJS exception filter that intercepts `HttpException` instances thrown during HTTP request handling. Its `catch()` method converts exceptions into a consistent HTTP error response, typically including the status code, request path, and timestamp. **Implements:** `ExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: HttpException, host: ArgumentsHost)` | `void` | ## Diagram ```mermaid graph LR A[HTTP Request] --> B[Controller or Service] B -->|Throws HttpException| C[HttpExceptionFilter] C --> D[catch()] D --> E[Standardized JSON Error Response] ``` ## Usage ```ts import { Controller, Get, HttpException, HttpStatus, UseFilters } from '@nestjs/common'; import { HttpExceptionFilter } from './common/filters/http-exception.filter'; @Controller('users') @UseFilters(HttpExceptionFilter) export class UsersController { @Get(':id') findOne() { throw new HttpException( 'User not found', HttpStatus.NOT_FOUND, ); } } ``` ## AI Coding Instructions - Use `HttpExceptionFilter` for HTTP-specific errors; do not use it for non-HTTP transports without adapting the host context. - Preserve the exception status via `exception.getStatus()` rather than hard-coding response codes. - Access request and response objects through `host.switchToHttp()` inside `catch()`. - Keep the error response shape consistent so API clients can reliably handle failures. - Register the filter with `@UseFilters(HttpExceptionFilter)` or configure it globally when consistent error handling is required across the application. # IQuery **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/graphql.schema.ts#L28) `IQuery` defines the GraphQL query entry points for retrieving posts in the sample Prisma-backed API. It exposes a collection query for all posts and a single-post query, allowing implementations to return values synchronously or asynchronously. ## Methods | Method | Signature | Returns | |---|---|---| | `posts` | `posts()` | `Post[] | Promise` | | `post` | `post(id: string)` | `Nullable | Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Query[IQuery] Query --> Posts[posts(): Post[]] Query --> Post[post(): Nullable] Posts --> Prisma[Prisma Data Access] Post --> Prisma ``` ## Usage ```ts import type { IQuery, Post } from "./graphql.schema"; const query: IQuery = { async posts(): Promise { return prisma.post.findMany(); }, async post(): Promise { return prisma.post.findFirst(); }, }; // Used by the GraphQL server as query resolvers const allPosts = await query.posts(); const singlePost = await query.post(); ``` ## AI Coding Instructions - Implement `posts()` to return an array of `Post` objects; return an empty array when no posts exist. - Implement `post()` to return `null` when a matching post cannot be found, respecting `Nullable`. - Both methods may return direct values or `Promise` values, but prefer `async` implementations when querying Prisma or other I/O services. - Keep database access inside resolver/service implementations rather than adding persistence logic to the `IQuery` type definition. - Ensure GraphQL resolver field names remain aligned with `posts` and `post` when wiring the schema. # KafkaJSBrokerNotFound **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1224) **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) **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) **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) **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) **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) **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) **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) **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) **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) **Extends:** `KafkaJSError` # KafkaJSUnsupportedMagicByteInMessageSet **Kind:** Class **Source:** [`packages/microservices/external/kafka.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L1252) **Extends:** `KafkaJSError` # LoggingPlugin **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/common/plugins/logging.plugin.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/common/plugins/logging.plugin.ts#L4) `LoggingPlugin` is an Apollo GraphQL server plugin that logs request lifecycle activity. It implements `requestDidStart()` to create and return a `GraphQLRequestListener` for each incoming GraphQL operation, allowing request-specific logging hooks to be attached. **Implements:** `ApolloServerPlugin` ## Methods | Method | Signature | Returns | |---|---|---| | `requestDidStart` | `requestDidStart()` | `Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Server[Apollo GraphQL Server] Server --> Plugin[LoggingPlugin] Plugin --> Start[requestDidStart()] Start --> Listener[GraphQLRequestListener] Listener --> Logs[Request Lifecycle Logs] ``` ## Usage ```ts import { ApolloServer } from '@apollo/server'; import { LoggingPlugin } from './common/plugins/logging.plugin'; const server = new ApolloServer({ typeDefs, resolvers, plugins: [ new LoggingPlugin(), ], }); await server.start(); ``` ## AI Coding Instructions - Register `LoggingPlugin` in the Apollo Server `plugins` array so it receives GraphQL request lifecycle events. - Keep `requestDidStart()` asynchronous and return a valid `GraphQLRequestListener`. - Add logging behavior through listener lifecycle hooks such as `didResolveOperation`, `willSendResponse`, or `didEncounterErrors`. - Avoid logging sensitive request headers, variables, authorization tokens, or private error details. - Ensure logging failures do not interrupt GraphQL request handling; logging should remain non-blocking where possible. # LoggingPlugin **Kind:** Class **Source:** [`sample/23-graphql-code-first/src/common/plugins/logging.plugin.ts`](https://github.com/nestjs/nest/blob/master/sample/23-graphql-code-first/src/common/plugins/logging.plugin.ts#L4) `LoggingPlugin` is an Apollo GraphQL server plugin that participates in the request lifecycle through its `requestDidStart()` hook. It creates a `GraphQLRequestListener` for each incoming operation, providing a central integration point for request-level logging and lifecycle instrumentation. **Implements:** `ApolloServerPlugin` ## Methods | Method | Signature | Returns | |---|---|---| | `requestDidStart` | `requestDidStart()` | `Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Server[Apollo GraphQL Server] Server --> Plugin[LoggingPlugin] Plugin --> Start[requestDidStart()] Start --> Listener[GraphQLRequestListener] Listener --> Events[Request Lifecycle Callbacks] Events --> Logs[Logging / Monitoring Output] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; import { GraphQLModule } from '@nestjs/graphql'; import { LoggingPlugin } from './common/plugins/logging.plugin'; @Module({ imports: [ GraphQLModule.forRoot({ driver: ApolloDriver, autoSchemaFile: true, plugins: [new LoggingPlugin()], }), ], }) export class AppModule {} ``` ## AI Coding Instructions - Keep `LoggingPlugin` compatible with Apollo Server's plugin API and return a valid `GraphQLRequestListener` from `requestDidStart()`. - Add logging behavior through listener lifecycle callbacks such as operation resolution, execution start, response sending, or request completion. - Avoid logging sensitive request variables, authorization headers, tokens, or personally identifiable information. - Register the plugin in the GraphQL module configuration so Apollo invokes it for every GraphQL request. # NamespaceGateway **Kind:** Class **Source:** [`integration/websockets/src/namespace.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/namespace.gateway.ts#L3) `NamespaceGateway` is the WebSocket gateway responsible for handling messages within its configured namespace. Its `onPush()` handler receives push events from connected clients and routes them into the application's real-time communication flow. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(client: undefined, data: undefined)` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|push event| Gateway[NamespaceGateway] Gateway --> Handler[onPush()] Handler --> Service[Application Services / Event Handlers] Service -->|broadcast or response| Client ``` ## Usage ```ts import { io } from 'socket.io-client'; // Connect to the namespace exposed by NamespaceGateway. const socket = io('http://localhost:3000/namespace'); socket.on('connect', () => { // Sends a message handled by NamespaceGateway.onPush(). socket.emit('push', { type: 'notification', message: 'Hello from the client', }); }); socket.on('push', (payload) => { console.log('Received push update:', payload); }); ``` ## AI Coding Instructions - Keep `onPush()` focused on validating and routing incoming WebSocket payloads; move business logic into injectable services. - Preserve the existing namespace and event-name contract, since connected clients depend on these values. - Validate untrusted client payloads before broadcasting, persisting, or passing them to downstream services. - Handle disconnected or unauthorized clients gracefully rather than assuming every socket remains available. - When adding new push payload fields, update both server-side DTOs/types and consuming WebSocket clients. # NatsStrategy **Kind:** Class **Source:** [`sample/03-microservices/src/common/strategies/nats.strategy.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/common/strategies/nats.strategy.ts#L11) `NatsStrategy` configures NATS-based event handling for the microservices sample. Its `bindEvents()` method connects application event subscriptions to the appropriate handlers, allowing services to communicate asynchronously through NATS subjects. **Extends:** `ServerNats` ## Methods | Method | Signature | Returns | |---|---|---| | `bindEvents` | `bindEvents(client: any)` | `void` | ## Diagram ```mermaid graph LR A[Application Bootstrap] --> B[NatsStrategy] B --> C[bindEvents()] C --> D[NATS Client / Transport] D --> E[NATS Subjects] E --> F[Microservice Event Handlers] ``` ## Usage ```ts import { NatsStrategy } from './common/strategies/nats.strategy'; // Typically resolved through the application's dependency injection container. const natsStrategy = app.get(NatsStrategy); // Register NATS subscriptions and event handlers during startup. natsStrategy.bindEvents(); ``` ## AI Coding Instructions - Call `bindEvents()` during application startup, after required NATS configuration and dependencies are available. - Keep NATS subject names and event payload contracts consistent across publishing and consuming services. - Add new event subscriptions through `NatsStrategy` rather than creating ad hoc NATS listeners throughout the codebase. - Ensure handlers are resilient to duplicate delivery, malformed payloads, and temporary NATS connection failures. # NewPost **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/graphql.schema.ts#L9) ## Properties | Property | Type | |---|---| | `title` | `string` | | `text` | `string` | # NonFile **Kind:** Class **Source:** [`integration/send-files/src/non-file.ts`](https://github.com/nestjs/nest/blob/master/integration/send-files/src/non-file.ts#L1) `NonFile` represents a value in the send-files integration that is not backed by a physical file. Its `pipe()` method allows the value to participate in stream-style flows where file-like inputs are forwarded to a destination. ## Methods | Method | Signature | Returns | |---|---|---| | `pipe` | `pipe()` | `void` | ## Diagram ```mermaid graph LR A[Send-files integration] --> B[NonFile] B -->|pipe()| C[Destination stream or handler] ``` ## Usage ```ts import { NonFile } from "./non-file"; const nonFile = new NonFile(); // Forward the non-file value through the send-files pipeline. nonFile.pipe(destination); ``` ## AI Coding Instructions - Use `NonFile` when an input must flow through the send-files pipeline without representing an on-disk file. - Treat `pipe()` as the integration boundary for forwarding the value to its destination. - Keep `NonFile` compatible with the same consumption pattern used by other send-files input types. - Verify the destination passed to `pipe()` supports the expected stream or pipe contract. # OrderCreatedEvent **Kind:** Class **Source:** [`sample/30-event-emitter/src/orders/events/order-created.event.ts`](https://github.com/nestjs/nest/blob/master/sample/30-event-emitter/src/orders/events/order-created.event.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | | `description` | `string` | # RequestFilter **Kind:** Class **Source:** [`integration/websockets/src/request.filter.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/request.filter.ts#L4) `RequestFilter` is a WebSocket exception filter that handles errors raised while processing gateway events. It provides a centralized `catch()` hook for converting request-processing failures into an appropriate response for the connected WebSocket client. **Implements:** `ExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: WsException, host: ArgumentsHost)` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] --> Gateway[Gateway Event Handler] Gateway -->|Success| Response[Event Response] Gateway -->|Throws Error| Filter[RequestFilter.catch()] Filter --> ErrorResponse[Client Error Callback / Response] ``` ## Usage ```ts import { UseFilters, WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; import { RequestFilter } from './request.filter'; @WebSocketGateway() @UseFilters(new RequestFilter()) export class EventsGateway { @SubscribeMessage('create-request') createRequest(payload: { name: string }) { if (!payload.name) { throw new Error('A name is required'); } return { success: true, name: payload.name }; } } ``` ## AI Coding Instructions - Apply `RequestFilter` to WebSocket gateways or individual message handlers with `@UseFilters(...)`. - Keep error-handling behavior in `catch()` consistent with the WebSocket transport response format expected by clients. - Do not assume HTTP request/response objects are available; use the WebSocket context from `ArgumentsHost`. - Preserve the original exception information where safe so clients and logs can identify failed events. - Test both successful event handling and thrown exceptions when changing gateway or filter behavior. # SumDto **Kind:** Class **Source:** [`integration/microservices/src/kafka-concurrent/dto/sum.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/microservices/src/kafka-concurrent/dto/sum.dto.ts#L1) ## Properties | Property | Type | |---|---| | `key` | `string` | | `numbers` | `number[]` | # UsersResolver **Kind:** Class **Source:** [`sample/31-graphql-federation-code-first/posts-application/src/posts/users.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/31-graphql-federation-code-first/posts-application/src/posts/users.resolver.ts#L6) `UsersResolver` is a GraphQL resolver in the posts application of a code-first GraphQL Federation setup. It exposes a `posts()` query that returns `Post` entities, allowing other federated services to retrieve post data through the composed GraphQL schema. ## Methods | Method | Signature | Returns | |---|---|---| | `posts` | `posts(user: User)` | `Post[]` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Gateway[Federation Gateway] Gateway --> UsersResolver[UsersResolver] UsersResolver --> PostsMethod[posts()] PostsMethod --> PostEntities[Post[]] ``` ## Usage ```ts import { UsersResolver } from './users.resolver'; const usersResolver = new UsersResolver(); // Invoke the resolver's posts query handler. const posts = usersResolver.posts(); console.log(posts); ``` ## AI Coding Instructions - Keep resolver methods focused on GraphQL query or field resolution; move persistence and business logic into injected services when needed. - Ensure the `posts()` return type remains aligned with the GraphQL `Post` object type and schema decorators. - Preserve Federation-compatible entity fields, especially identifiers used by other subgraphs to reference posts. - Add authentication, authorization, or filtering checks before returning posts if the query becomes user-specific. # UsersResolver **Kind:** Class **Source:** [`sample/32-graphql-federation-schema-first/posts-application/src/posts/users.resolver.ts`](https://github.com/nestjs/nest/blob/master/sample/32-graphql-federation-schema-first/posts-application/src/posts/users.resolver.ts#L5) `UsersResolver` extends the GraphQL `User` type with a `posts()` field in the posts application. It resolves posts associated with a user, allowing this federation subgraph to provide post data for users defined or referenced across the graph. ## Methods | Method | Signature | Returns | |---|---|---| | `posts` | `posts(user: User)` | `void` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> User[User GraphQL Type] User --> UsersResolver[UsersResolver.posts()] UsersResolver --> PostsService[Posts Service] PostsService --> Posts[(Post Records)] UsersResolver --> PostList[posts: Post[]] ``` ## Usage ```ts import { Module } from '@nestjs/common'; import { Resolver, ResolveField, Parent } from '@nestjs/graphql'; type UserReference = { id: string; }; type Post = { id: string; title: string; authorId: string; }; class PostsService { findByAuthorId(authorId: string): Promise { // Load posts belonging to the referenced user. return Promise.resolve([]); } } @Resolver('User') export class UsersResolver { constructor(private readonly postsService: PostsService) {} @ResolveField('posts') posts(@Parent() user: UserReference): Promise { return this.postsService.findByAuthorId(user.id); } } @Module({ providers: [UsersResolver, PostsService], }) export class PostsModule {} ``` ```graphql query GetUserPosts { user(id: "user-123") { id posts { id title } } } ``` ## AI Coding Instructions - Keep `UsersResolver` focused on resolving fields for the GraphQL `User` type; place post lookup and persistence logic in a service. - Use `@Parent()` to access the federated user reference and resolve posts using its stable identifier, typically `id`. - Ensure the resolver field name matches the schema-first GraphQL schema definition, such as `posts`. - Register the resolver and its dependencies in the relevant NestJS module providers. - Avoid returning posts for unrelated users; always filter lookups by the parent user's identifier. # WsPathGateway **Kind:** Class **Source:** [`integration/websockets/src/ws-path.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/ws-path.gateway.ts#L3) `WsPathGateway` is a WebSocket gateway responsible for handling push events received through the WebSocket integration path. Its `onPush()` handler acts as the entry point for incoming push messages and routes them into the application's real-time processing flow. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(client: undefined, data: undefined)` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|push event| Gateway[WsPathGateway] Gateway -->|onPush()| Handler[Push Message Processing] Handler --> Application[Application Services / Consumers] ``` ## Usage ```ts import { WsPathGateway } from './ws-path.gateway'; // WsPathGateway is typically registered and instantiated by the // application's WebSocket framework/container. const gateway = new WsPathGateway(); // Invoke the push handler when integrating with a custom transport. gateway.onPush({ type: 'update', payload: { id: 'resource-123', status: 'ready', }, }); ``` ## AI Coding Instructions - Keep `onPush()` focused on receiving and delegating push events; place business logic in dedicated services where possible. - Preserve the existing WebSocket event and payload contract when changing handler behavior. - Validate or safely handle incoming push payloads before passing them to downstream consumers. - Register the gateway through the application's WebSocket integration so framework lifecycle and event binding are retained. # WsPathGateway2 **Kind:** Class **Source:** [`integration/websockets/src/ws-path2.gateway.ts`](https://github.com/nestjs/nest/blob/master/integration/websockets/src/ws-path2.gateway.ts#L3) `WsPathGateway2` is a WebSocket gateway configured for the application's second WebSocket path. It handles incoming `push` messages through `onPush()`, providing an isolated endpoint for path-specific WebSocket integration and messaging behavior. ## Methods | Method | Signature | Returns | |---|---|---| | `onPush` | `onPush(client: undefined, data: undefined)` | `void` | ## Diagram ```mermaid graph LR Client[WebSocket Client] -->|connects to configured path| Gateway[WsPathGateway2] Client -->|push event| OnPush[onPush()] OnPush --> Response[Gateway response or emitted message] Response --> Client ``` ## Usage ```ts import { io } from 'socket.io-client'; // Connect using the WebSocket path served by WsPathGateway2. const socket = io('http://localhost:3000', { path: '/ws-path2', }); socket.on('connect', () => { socket.emit('push', { message: 'Hello from the client', }); }); socket.on('push', payload => { console.log('Received push payload:', payload); }); ``` ## AI Coding Instructions - Keep the gateway's configured WebSocket path aligned with the client `path` option; a path mismatch prevents clients from connecting. - Route `push` event handling through `onPush()` rather than adding unstructured socket listeners elsewhere. - Preserve the gateway's existing message contract when changing payloads, since connected clients may depend on its event name and response shape. - Test this gateway independently from other WebSocket paths to ensure path-specific routing does not leak between gateways. # CreateCatDto **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/cats/dto/create-cat.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/cats/dto/create-cat.dto.ts#L7) **Extends:** `CreateCatInput` ## Properties | Property | Type | |---|---| | `age` | `number` | # ExceptionFilter **Kind:** Class **Source:** [`sample/03-microservices/src/common/filters/rpc-exception.filter.ts`](https://github.com/nestjs/nest/blob/master/sample/03-microservices/src/common/filters/rpc-exception.filter.ts#L5) `ExceptionFilter` is a microservice RPC exception filter that converts thrown application errors into RxJS error observables. It provides a consistent error-handling boundary for NestJS message handlers, allowing RPC clients to receive structured failures instead of unhandled exceptions. **Implements:** `RpcExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: RpcException)` | `Observable` | ## Diagram ```mermaid graph LR A[Microservice Message Handler] --> B[Throws Error or RpcException] B --> C[ExceptionFilter.catch] C --> D[Extract Exception Details] D --> E[throwError Observable] E --> F[RPC Client Receives Error Response] ``` ## Usage ```ts import { Controller, UseFilters } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; import { ExceptionFilter } from './common/filters/rpc-exception.filter'; @Controller() @UseFilters(new ExceptionFilter()) export class UserController { @MessagePattern('users.findOne') async findOne(userId: string) { const user = await this.userService.findById(userId); if (!user) { throw new Error(`User ${userId} was not found`); } return user; } } ``` ## AI Coding Instructions - Apply `ExceptionFilter` to RPC controllers or individual `@MessagePattern()` handlers using NestJS `@UseFilters()`. - Ensure `catch()` always returns an `Observable`, typically through RxJS `throwError()`, because microservice exception filters use reactive responses. - Preserve meaningful error messages and status metadata when converting exceptions into RPC-compatible errors. - Do not use this filter for HTTP-only controllers; use an HTTP exception filter when handling REST request/response errors. - Keep error payloads safe for clientsβ€”avoid exposing stack traces, database details, or internal service configuration. # IMutation **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/graphql.schema.ts#L22) `IMutation` defines the GraphQL mutation contract for creating cats in the schema-first sample. Its `createCat` resolver is responsible for accepting mutation input through the GraphQL layer and returning either a created `Cat`, `null`, or an asynchronous result. ## Methods | Method | Signature | Returns | |---|---|---| | `createCat` | `createCat(createCatInput: Nullable)` | `Nullable | Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Mutation[IMutation.createCat] Mutation --> Resolver[Mutation Resolver] Resolver --> Cat[Cat Result] Resolver --> Null[null] ``` ## Usage ```ts import type { IMutation, Cat } from './graphql.schema'; const mutations: IMutation = { async createCat(): Promise { const cat: Cat = { id: 'cat-1', name: 'Milo', }; return cat; }, }; const createdCat = await mutations.createCat(); if (createdCat) { console.log(`Created cat: ${createdCat.name}`); } ``` ## AI Coding Instructions - Implement `createCat` as a GraphQL mutation resolver that returns a `Cat`, `null`, or a `Promise` resolving to either value. - Preserve the nullable return contract; do not throw for expected β€œnot created” outcomes when `null` is appropriate. - Keep resolver logic aligned with the schema-first GraphQL definition in `graphql.schema.ts`. - Add validation, persistence, or service-layer calls inside the resolver rather than placing business logic in GraphQL client code. # ISubscription **Kind:** Class **Source:** [`sample/12-graphql-schema-first/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first/src/graphql.schema.ts#L28) `ISubscription` defines the GraphQL subscription contract for cat creation events in the schema-first sample. Its `catCreated()` method provides a nullable `Cat` payload, either synchronously or asynchronously, when a new cat event is delivered. ## Methods | Method | Signature | Returns | |---|---|---| | `catCreated` | `catCreated()` | `Nullable | Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL Client] --> Subscription[ISubscription] Subscription --> CatCreated[catCreated()] CatCreated --> Cat[Cat payload] CatCreated --> Nullable[null when no payload is available] ``` ## Usage ```ts import type { ISubscription } from './graphql.schema'; const subscription: ISubscription = { async catCreated() { return { id: 'cat-123', name: 'Milo', age: 2, }; }, }; // Called by the GraphQL subscription resolver when an event is received. const cat = await subscription.catCreated(); if (cat) { console.log(`New cat created: ${cat.name}`); } ``` ## AI Coding Instructions - Implement `catCreated()` to return a `Cat`, `null`, or a `Promise` resolving to either value. - Preserve the nullable return contract; do not assume every subscription event has a cat payload. - Use this interface as the schema-first TypeScript contract for the corresponding GraphQL subscription resolver. - Ensure returned `Cat` objects match the fields and types defined by the generated GraphQL schema. # ISubscription **Kind:** Class **Source:** [`sample/22-graphql-prisma/src/graphql.schema.ts`](https://github.com/nestjs/nest/blob/master/sample/22-graphql-prisma/src/graphql.schema.ts#L44) `ISubscription` represents the subscription-facing portion of the GraphQL schema. Its `postCreated` method provides the latest created `Post` value, either synchronously or asynchronously, and may return `null` when no post payload is available. ## Methods | Method | Signature | Returns | |---|---|---| | `postCreated` | `postCreated()` | `Nullable | Promise>` | ## Diagram ```mermaid graph LR Client[GraphQL subscription client] --> Subscription[ISubscription] Subscription --> PostCreated[postCreated()] PostCreated --> Post[Post] PostCreated --> Null[null] ``` ## Usage ```ts import { ISubscription, Post } from "./graphql.schema"; class PostSubscription extends ISubscription { async postCreated(): Promise { const latestPost = await postRepository.findLatestCreatedPost(); return latestPost ?? null; } } const subscription = new PostSubscription(); const post = await subscription.postCreated(); if (post) { console.log(`New post created: ${post.title}`); } ``` ## AI Coding Instructions - Implement `postCreated` to return a `Post`, `null`, or a `Promise` resolving to either value. - Preserve nullable behavior: return `null` when there is no post payload instead of throwing for an expected empty result. - Keep subscription data access asynchronous when reading from Prisma, a message broker, or another external source. - Ensure returned objects conform to the GraphQL `Post` shape expected by the schema. - Connect concrete subscription implementations to the GraphQL subscription resolver or event-publishing layer. # SampleDto **Kind:** Class **Source:** [`sample/29-file-upload/src/sample.dto.ts`](https://github.com/nestjs/nest/blob/master/sample/29-file-upload/src/sample.dto.ts#L1) ## Properties | Property | Type | |---|---| | `name` | `string` | # UnauthorizedFilter **Kind:** Class **Source:** [`integration/graphql-code-first/src/common/filters/unauthorized.filter.ts`](https://github.com/nestjs/nest/blob/master/integration/graphql-code-first/src/common/filters/unauthorized.filter.ts#L4) `UnauthorizedFilter` is a GraphQL exception filter that handles unauthorized access errors raised during resolver execution. It translates authentication failures into a consistent GraphQL-friendly error response, allowing the application to centralize authorization error handling. **Implements:** `GqlExceptionFilter` ## Methods | Method | Signature | Returns | |---|---|---| | `catch` | `catch(exception: any, host: ArgumentsHost)` | `void` | ## Diagram ```mermaid graph LR A[GraphQL Resolver] --> B{Authentication/Authorization Check} B -->|Authorized| C[Return Resolver Result] B -->|Unauthorized Error| D[UnauthorizedFilter.catch] D --> E[GraphQL Error Response] ``` ## Usage ```ts import { UseFilters } from '@nestjs/common'; import { Resolver, Query } from '@nestjs/graphql'; import { UnauthorizedFilter } from '../common/filters/unauthorized.filter'; @Resolver() @UseFilters(UnauthorizedFilter) export class ProfileResolver { @Query(() => String) getProfile(): string { // Throw an unauthorized exception when the request is not authenticated. throw new Error('Unauthorized'); } } ``` ## AI Coding Instructions - Apply `UnauthorizedFilter` to GraphQL resolvers or resolver methods that need consistent handling of authentication failures. - Keep authorization checks in guards, services, or resolver logic; use this filter only to format and expose the resulting error. - Ensure the filter is used in a GraphQL execution context, since HTTP-only exception handling may not produce the expected GraphQL response. - Avoid leaking sensitive authentication or internal exception details in the error returned by `catch()`. # UpdateChatDto **Kind:** Class **Source:** [`integration/inspector/src/chat/dto/update-chat.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/chat/dto/update-chat.dto.ts#L4) **Extends:** `PartialType(CreateChatDto)` ## Properties | Property | Type | |---|---| | `id` | `number` | # UpdateExternalSvcDto **Kind:** Class **Source:** [`integration/inspector/src/external-svc/dto/update-external-svc.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/external-svc/dto/update-external-svc.dto.ts#L4) **Extends:** `PartialType(CreateExternalSvcDto)` ## Properties | Property | Type | |---|---| | `id` | `number` | # CatsModule **Kind:** Class **Source:** [`sample/09-babel-example/src/cats/cats.module.js`](https://github.com/nestjs/nest/blob/master/sample/09-babel-example/src/cats/cats.module.js#L5) # AppModule **Kind:** Class **Source:** [`sample/09-babel-example/src/app.module.js`](https://github.com/nestjs/nest/blob/master/sample/09-babel-example/src/app.module.js#L4) # Chat **Kind:** Class **Source:** [`integration/inspector/src/chat/entities/chat.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/chat/entities/chat.entity.ts#L1) # CreateChatDto **Kind:** Class **Source:** [`integration/inspector/src/chat/dto/create-chat.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/chat/dto/create-chat.dto.ts#L1) # CreateDatabaseDto **Kind:** Class **Source:** [`integration/inspector/src/database/dto/create-database.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/dto/create-database.dto.ts#L1) # CreateDogDto **Kind:** Class **Source:** [`integration/inspector/src/dogs/dto/create-dog.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dto/create-dog.dto.ts#L1) # CreateExternalSvcDto **Kind:** Class **Source:** [`integration/inspector/src/external-svc/dto/create-external-svc.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/external-svc/dto/create-external-svc.dto.ts#L1) # CreateUserDto **Kind:** Class **Source:** [`integration/inspector/src/users/dto/create-user.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/dto/create-user.dto.ts#L1) # CreateUserDto **Kind:** Class **Source:** [`integration/repl/src/users/dto/create-user.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/dto/create-user.dto.ts#L1) # Database **Kind:** Class **Source:** [`integration/inspector/src/database/entities/database.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/entities/database.entity.ts#L1) # Dog **Kind:** Class **Source:** [`integration/inspector/src/dogs/entities/dog.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/entities/dog.entity.ts#L1) # ExternalSvc **Kind:** Class **Source:** [`integration/inspector/src/external-svc/entities/external-svc.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/external-svc/entities/external-svc.entity.ts#L1) # IntrinsicException **Kind:** Class **Source:** [`packages/common/exceptions/intrinsic.exception.ts`](https://github.com/nestjs/nest/blob/master/packages/common/exceptions/intrinsic.exception.ts#L7) 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. # UpdateDatabaseDto **Kind:** Class **Source:** [`integration/inspector/src/database/dto/update-database.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/database/dto/update-database.dto.ts#L4) **Extends:** `PartialType(CreateDatabaseDto)` # UpdateDogDto **Kind:** Class **Source:** [`integration/inspector/src/dogs/dto/update-dog.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/dogs/dto/update-dog.dto.ts#L4) **Extends:** `PartialType(CreateDogDto)` # UpdateUserDto **Kind:** Class **Source:** [`integration/inspector/src/users/dto/update-user.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/dto/update-user.dto.ts#L4) **Extends:** `PartialType(CreateUserDto)` # UpdateUserDto **Kind:** Class **Source:** [`integration/repl/src/users/dto/update-user.dto.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/dto/update-user.dto.ts#L4) **Extends:** `PartialType(CreateUserDto)` # User **Kind:** Class **Source:** [`integration/inspector/src/users/entities/user.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/inspector/src/users/entities/user.entity.ts#L1) # User **Kind:** Class **Source:** [`integration/repl/src/users/entities/user.entity.ts`](https://github.com/nestjs/nest/blob/master/integration/repl/src/users/entities/user.entity.ts#L1)