### Install NestJS Testing Package Source: https://docs.nestjs.cn/fundamentals/unit-testing Installs the necessary NestJS testing utilities as development dependencies using npm. ```bash npm i --save-dev @nestjs/testing ``` -------------------------------- ### Install Prisma Client Source: https://docs.nestjs.cn/recipes/prisma Installs the @prisma/client package, which provides a type-safe database client tailored to your Prisma schema. The installation process also automatically triggers `prisma generate`. ```bash npm install @prisma/client ``` -------------------------------- ### Install BullMQ and NestJS Adapter Source: https://docs.nestjs.cn/techniques/queues Installs the necessary packages for BullMQ integration with NestJS. This includes the official NestJS adapter and the BullMQ library itself. ```bash $ npm install --save @nestjs/bullmq bullmq ``` -------------------------------- ### Install NestJS Sentry SDK Source: https://docs.nestjs.cn/recipes/sentry Installs the necessary Sentry packages for NestJS, including the optional profiling package for performance analysis. ```bash npm install --save @sentry/nestjs @sentry/profiling-node ``` -------------------------------- ### Create NestJS Project with CLI Source: https://docs.nestjs.cn/recipes/prisma Installs the NestJS CLI globally and creates a new NestJS project named 'hello-prisma'. This command scaffolds the basic file structure for a NestJS application. ```bash npm install -g @nestjs/cli nest new hello-prisma ``` -------------------------------- ### Install Apollo Gateway for NestJS Federation Source: https://docs.nestjs.cn/graphql/federation Installs the necessary dependency for setting up an Apollo Gateway in a NestJS application. This package enables the gateway to introspect and compose schemas from multiple subgraphs. ```bash npm install --save @apollo/gateway ``` -------------------------------- ### Install NestJS Bull Package Source: https://docs.nestjs.cn/techniques/queues Provides the npm command to install the necessary packages for using BullMQ with NestJS. This includes `@nestjs/bull` and `bull`. ```bash $ npm install --save @nestjs/bull bull ``` -------------------------------- ### Install NestJS GraphQL Packages Source: https://docs.nestjs.cn/graphql/quick-start Installs the necessary packages for integrating GraphQL with NestJS. Supports both Apollo (default) and Mercurius drivers, for Express and Fastify. ```bash # For Express and Apollo (default) $ npm i @nestjs/graphql @nestjs/apollo @apollo/server graphql # For Fastify and Apollo # npm i @nestjs/graphql @nestjs/apollo @apollo/server @as-integrations/fastify graphql # For Fastify and Mercurius # npm i @nestjs/graphql @nestjs/mercurius graphql mercurius ``` -------------------------------- ### Installation Source: https://docs.nestjs.cn/microservices/mqtt Install the MQTT package using npm or yarn. ```APIDOC ## Installation To start building MQTT-based microservices, first install the required package: ```bash $ npm i --save mqtt ``` ``` -------------------------------- ### Running Start Script with npm Source: https://docs.nestjs.cn/cli/scripts Starts a Nest.js application using npm scripts after the build process. This command uses the locally installed `nest` binary to run `nest start`, providing a standardized way to execute the compiled application. ```bash npm run start ``` -------------------------------- ### Installing Nest CLI Globally and Locally for Migration Source: https://docs.nestjs.cn/cli/scripts Installs the latest version of the Nest CLI both globally and as a development dependency in a project. This is a prerequisite for migrating `package.json` scripts to use the new `nest build` and `nest start` commands. ```bash npm install -g @nestjs/cli cd /some/project/root/folder npm install -D @nestjs/cli ``` -------------------------------- ### Install NestJS JWT Package Source: https://docs.nestjs.cn/security/authentication Installs the @nestjs/jwt package, which provides utilities for handling JWT operations. This is a prerequisite for JWT-based authentication in NestJS. ```bash npm install --save @nestjs/jwt ``` -------------------------------- ### Microservice Installation Source: https://docs.nestjs.cn/microservices/basics Installs the necessary package for NestJS microservices. ```APIDOC ## Install Microservices Package ### Description Installs the `@nestjs/microservices` package, which is required to start building microservices with NestJS. ### Method ```bash npm install --save @nestjs/microservices ``` ``` -------------------------------- ### NestJS Module Setup for BullMQ Queue Source: https://docs.nestjs.cn/techniques/queues Illustrates the configuration of a BullMQ queue named 'audio' within a NestJS application module. It shows how to register the queue and specify the processor file using `join`. ```typescript import { Module } from '@nestjs/common'; import { BullModule } from '@nestjs/bull'; import { join } from 'path'; @Module({ imports: [ BullModule.registerQueue({ name: 'audio', processors: [join(__dirname, 'processor.js')], }), ], }) export class AppModule {} ``` -------------------------------- ### Install NestJS CLI and Create Project Source: https://docs.nestjs.cn/techniques/mvc Installs the NestJS CLI globally and creates a new NestJS project. This is the initial step for building any NestJS application. ```bash $ npm i -g @nestjs/cli $ nest new project ``` -------------------------------- ### Install Prisma CLI as Dev Dependency (npm) Source: https://docs.nestjs.cn/recipes/prisma Installs the Prisma CLI as a development dependency in your project using npm. Prisma CLI is used for database migrations and client generation. ```bash cd hello-prisma npm install prisma --save-dev ``` -------------------------------- ### Install NestJS Microservices Package Source: https://docs.nestjs.cn/microservices/basics This command installs the necessary package for building microservices with NestJS. It is a prerequisite for using NestJS microservice features. ```bash npm i --save @nestjs/microservices ``` -------------------------------- ### Install MQTT Package with npm Source: https://docs.nestjs.cn/microservices/mqtt Installs the necessary MQTT package for NestJS microservices using npm. This is the initial step to enable MQTT communication. ```bash $ npm i --save mqtt ``` -------------------------------- ### Install NestJS WebSocket Packages Source: https://docs.nestjs.cn/websockets/gateways Installs the necessary packages for building WebSocket-based applications in NestJS, including the core websockets package and the platform-socket.io adapter. ```bash $ npm i --save @nestjs/websockets @nestjs/platform-socket.io ``` -------------------------------- ### RabbitMQ Installation Source: https://docs.nestjs.cn/microservices/rabbitmq Installs the required packages for RabbitMQ integration. ```APIDOC ## RabbitMQ Installation ### Description Installs the necessary packages for building RabbitMQ-based microservices. ### Method ```bash npm install --save amqplib amqp-connection-manager ``` ``` -------------------------------- ### Start NestJS App with SWC Builder Source: https://docs.nestjs.cn/recipes/swc Starts a NestJS application using the SWC builder. This command significantly speeds up the build process. ```bash $ nest start -b swc # OR nest start --builder swc ``` -------------------------------- ### Verify Node.js and npm Installation Source: https://docs.nestjs.cn/overview/first-steps Commands to verify if Node.js and npm have been successfully installed on the system. These are essential prerequisites for using NestJS. ```bash $ node --version $ npm --version ``` -------------------------------- ### NestJS REPL Native Function Help Source: https://docs.nestjs.cn/recipes/repl This example shows how to get help for a specific native REPL function, like '$' (which is an alias for `get`). It displays the function's description and its TypeScript type signature. ```typescript > $.help Retrieves an instance of either injectable or controller, otherwise, throws exception. Interface: $(token: InjectionToken) => any ``` -------------------------------- ### Installation Source: https://docs.nestjs.cn/recipes/terminus Install the necessary dependencies for @nestjs/terminus. ```APIDOC ## Installation ### Description To begin using the Terminus integration, install the required package. ### Command ```bash npm install --save @nestjs/terminus ``` ``` -------------------------------- ### Install SWC for NestJS Source: https://docs.nestjs.cn/recipes/swc Installs the necessary SWC packages for the NestJS CLI. This enables faster compilation during development. ```bash $ npm i --save-dev @swc/cli @swc/core ``` -------------------------------- ### Install NestJS CQRS Module Source: https://docs.nestjs.cn/recipes/cqrs Installs the necessary @nestjs/cqrs package using npm. This is the first step to enable CQRS capabilities in your NestJS application. ```bash npm install --save @nestjs/cqrs ``` -------------------------------- ### Install NestJS Event Emitter Source: https://docs.nestjs.cn/techniques/events Install the `@nestjs/event-emitter` package using npm. This is the first step to enable event emission and listening in your NestJS application. ```bash npm i --save @nestjs/event-emitter ``` -------------------------------- ### Install @nestjs/swagger Source: https://docs.nestjs.cn/openapi/introduction Install the necessary dependency for Swagger integration. ```APIDOC ## Install @nestjs/swagger To begin using the Swagger module, install the required dependency: ```bash $ npm install --save @nestjs/swagger ``` ``` -------------------------------- ### NestJS GraphQL: Asynchronous Configuration with UseExisting Source: https://docs.nestjs.cn/graphql/quick-start Configures the GraphQLModule asynchronously by reusing an existing configuration provider using the `useExisting` syntax. This is useful for leveraging pre-existing configuration setups. ```typescript GraphQLModule.forRootAsync({ imports: [ConfigModule], useExisting: ConfigService, }) ``` -------------------------------- ### NestJS E2E Test with Fastify Adapter Source: https://docs.nestjs.cn/fundamentals/unit-testing This snippet illustrates end-to-end testing for a NestJS application configured with the Fastify HTTP adapter. It shows the necessary setup for Fastify, including initializing the application and its adapter, and then using the application's inject method to simulate HTTP requests and assert responses. This approach is specific to Fastify-based NestJS applications. ```typescript import { Test } from '@nestjs/testing'; import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { AppModule } from './app.module'; // Assuming AppModule is your root module let app: NestFastifyApplication; beforeAll(async () => { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleRef.createNestApplication( new FastifyAdapter() ); await app.init(); await app.getHttpAdapter().getInstance().ready(); }); it(`/GET cats`, () => { return app .inject({ method: 'GET', url: '/cats', }) .then((result) => { expect(result.statusCode).toEqual(200); expect(result.payload).toEqual(/* expectedPayload */); }); }); afterAll(async () => { await app.close(); }); ``` -------------------------------- ### Install KafkaJS Source: https://docs.nestjs.cn/microservices/kafka Instructions to install the necessary kafkajs package for Kafka integration. ```APIDOC ## Install KafkaJS ### Description To begin building Kafka-based microservices, install the required package using npm. ### Method ```bash npm i --save kafkajs ``` ### Endpoint N/A ``` -------------------------------- ### Install Fastify Platform for NestJS Source: https://docs.nestjs.cn/techniques/performance Installs the necessary package for integrating Fastify with NestJS. This command should be run in your project's terminal. ```bash npm i --save @nestjs/platform-fastify ``` -------------------------------- ### Start Nest Project (`nest start`) Source: https://docs.nestjs.cn/cli/usages Compiles and runs the NestJS application or the default project in a workspace. Supports watch mode, debugging, and environment variable loading. ```bash $ nest start [options] ``` -------------------------------- ### Install Fastify Dependencies for NestJS Source: https://docs.nestjs.cn/techniques/mvc Installs necessary packages for using Fastify as the HTTP provider in NestJS, including static asset handling and Handlebars view integration. ```bash $ npm i --save @fastify/static @fastify/view handlebars ``` -------------------------------- ### Install SWC Loader for Webpack in Monorepo Source: https://docs.nestjs.cn/recipes/swc Installs the swc-loader package, which is required to use SWC with Webpack in a monorepo setup. ```bash $ npm i --save-dev swc-loader ``` -------------------------------- ### Install MikroORM and Drivers Source: https://docs.nestjs.cn/recipes/mikroorm Installs the core MikroORM packages and the SQLite driver. Other supported drivers like `postgres` and `mongo` can be used instead of `sqlite`. ```bash $ npm i @mikro-orm/core @mikro-orm/nestjs @mikro-orm/sqlite ``` -------------------------------- ### Install nest-commander Source: https://docs.nestjs.cn/recipes/nest-commander This command installs the nest-commander package using npm. It's a prerequisite for using the library in your project. ```bash $ npm i nest-commander ``` -------------------------------- ### GET Endpoint with Specific Route Source: https://docs.nestjs.cn/overview/controllers Shows how to define a specific route for a GET request by combining the controller prefix and the path in the method decorator. This example handles GET requests to '/cats/breed'. ```APIDOC ## GET /cats/breed ### Description Retrieves a specific cat breed. (Example assumes a breed-related endpoint). ### Method GET ### Endpoint /cats/brees ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **string**: A string indicating the action performed. #### Response Example ``` "This action returns a cat breed" ``` ``` -------------------------------- ### Manual Client Initialization Source: https://docs.nestjs.cn/microservices/basics Shows how to manually establish a connection using the connect() method within the onApplicationBootstrap lifecycle hook. ```APIDOC ## Manual Client Initialization ### Description Manually initialize the connection to the microservice using the `client.connect()` method within the `onApplicationBootstrap` lifecycle hook. This ensures the connection is established before the first microservice call. ### Method `client.connect()` ### Endpoint N/A (Lifecycle Hook) ### Parameters N/A ### Request Example ```typescript import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; import { ClientProxy } from '@nestjs/microservices'; @Injectable() export class AppService implements OnApplicationBootstrap { constructor(private client: ClientProxy) {} async onApplicationBootstrap() { await this.client.connect(); } } ``` ### Response N/A #### Error Handling - The `connect()` method will reject with an error object if the connection creation fails. ``` -------------------------------- ### Install NestJS Swagger Dependency Source: https://docs.nestjs.cn/openapi/introduction Installs the necessary @nestjs/swagger package using npm. This is the first step to enable OpenAPI documentation generation in your NestJS project. ```bash $ npm install --save @nestjs/swagger ``` -------------------------------- ### Install NATS Microservice Package Source: https://docs.nestjs.cn/microservices/nats This command installs the necessary NATS package for NestJS microservices. It is a prerequisite for using NATS with NestJS. ```bash npm i --save nats ``` -------------------------------- ### Install gRPC Packages with npm Source: https://docs.nestjs.cn/microservices/grpc Installs the necessary packages for gRPC communication in a NestJS project. These include the gRPC runtime and a loader for Protocol Buffers definitions. ```bash $ npm i --save @grpc/grpc-js @grpc/proto-loader ``` -------------------------------- ### gRPC Installation Source: https://docs.nestjs.cn/microservices/grpc Install the necessary packages for gRPC microservices in your NestJS project. ```APIDOC ## gRPC Installation To start building gRPC-based microservices, first install the required packages: ```bash $ npm i --save @grpc/grpc-js @grpc/proto-loader ``` ``` -------------------------------- ### GET /feed Source: https://docs.nestjs.cn/recipes/prisma Retrieves a list of all published posts. ```APIDOC ## GET /feed ### Description Retrieves a list of all published posts. ### Method GET ### Endpoint /feed ### Response #### Success Response (200) - **PostModel[]** (array) - An array of published post objects. #### Response Example ```json [ { "id": 1, "title": "First Published Post", "content": "Content of the first post.", "published": true, "authorEmail": "user1@example.com" }, { "id": 2, "title": "Second Published Post", "content": "Content of the second post.", "published": true, "authorEmail": "user2@example.com" } ] ``` ``` -------------------------------- ### Install Validation Dependencies Source: https://docs.nestjs.cn/techniques/validation Installs the necessary class-validator and class-transformer packages for using the ValidationPipe. ```bash $ npm i --save class-validator class-transformer ``` -------------------------------- ### Creating a Basic Microservice Source: https://docs.nestjs.cn/microservices/basics Demonstrates how to create a basic microservice using the `createMicroservice` method and TCP transport. ```APIDOC ## Create a Basic Microservice ### Description Illustrates the creation of a microservice instance using `NestFactory.createMicroservice()`. It defaults to the TCP transport layer. ### Method ```typescript import { NestFactory } from '@nestjs/core'; import { Transport, MicroserviceOptions } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.createMicroservice( AppModule, { transport: Transport.TCP, }, ); await app.listen(); } bootstrap(); ``` ### Parameters #### Options Object - **transport** (Transport) - Specifies the transport layer to use (e.g., `Transport.TCP`, `Transport.NATS`). - **options** (object) - Transport-specific configuration options. - **host** (string) - The hostname for the connection. - **port** (number) - The port for the connection. - **retryAttempts** (number) - Number of times to retry sending a message (default: 0). - **retryDelay** (number) - Delay in milliseconds between retry attempts (default: 0). - **serializer** (object) - Custom serializer for outgoing messages. - **deserializer** (object) - Custom deserializer for incoming messages. - **socketClass** (object) - Custom Socket class inheriting from `TcpSocket` (default: `JsonSocket`). - **tlsOptions** (object) - Options for configuring the TLS protocol. ``` -------------------------------- ### NestJS Application Bootstrap Logic Source: https://docs.nestjs.cn/overview/first-steps The main entry point for a NestJS application, demonstrating how to create an application instance using NestFactory and start the HTTP listener. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(process.env.PORT ?? 3000); } bootstrap(); ``` -------------------------------- ### Install RabbitMQ Dependencies for NestJS Source: https://docs.nestjs.cn/microservices/rabbitmq Installs the necessary npm packages 'amqplib' and 'amqp-connection-manager' to enable RabbitMQ functionality within a NestJS application. ```bash $ npm i --save amqplib amqp-connection-manager ``` -------------------------------- ### Install Prisma CLI as Dev Dependency (Yarn) Source: https://docs.nestjs.cn/recipes/prisma Installs the Prisma CLI as a development dependency using Yarn. This is an alternative to npm for managing project dependencies. ```bash yarn add prisma --dev ``` -------------------------------- ### Creating an MQTT Client Instance Source: https://docs.nestjs.cn/microservices/mqtt Learn how to create MQTT `ClientProxy` instances using `ClientsModule`. ```APIDOC ## Creating an MQTT Client Instance Similar to other microservice transports, there are multiple ways to create an MQTT `ClientProxy` instance. One way to create an instance is by using the `ClientsModule`. To create a client instance through `ClientsModule`, you need to import this module and use the `register()` method, passing the options object that contains the same properties as the `createMicroservice()` method above, along with a `name` property that will be used as the injection token. ```typescript @Module({ imports: [ ClientsModule.register([ { name: 'MATH_SERVICE', transport: Transport.MQTT, options: { url: 'mqtt://localhost:1883', } }, ]), ] ... }) export class AppModule {} ``` Other ways to create clients (using `ClientProxyFactory` or `@Client()`) are also applicable. You can learn more about them here. ``` -------------------------------- ### GET /post/:id Source: https://docs.nestjs.cn/recipes/prisma Retrieves a single post by its unique identifier. ```APIDOC ## GET /post/:id ### Description Retrieves a single post by its unique identifier. ### Method GET ### Endpoint /post/:id #### Path Parameters - **id** (string) - Required - The ID of the post to retrieve. ### Response #### Success Response (200) - **PostModel** (object) - The requested post object. #### Response Example ```json { "id": 1, "title": "Example Post", "content": "This is the content of the example post.", "published": true, "authorEmail": "user@example.com" } ``` ``` -------------------------------- ### NestJS REST Controller Example (Generated) Source: https://docs.nestjs.cn/recipes/crud-generator Example of a generated controller for a REST API resource. It defines standard CRUD routes (POST, GET, PATCH, DELETE) and integrates with the corresponding service. ```typescript @Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {} @Post() create(@Body() createUserDto: CreateUserDto) { return this.usersService.create(createUserDto); } @Get() findAll() { return this.usersService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.usersService.findOne(+id); } @Patch(':id') update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { return this.usersService.update(+id, updateUserDto); } @Delete(':id') remove(@Param('id') id: string) { return this.usersService.remove(+id); } } ``` -------------------------------- ### Install Jest and SWC for NestJS Source: https://docs.nestjs.cn/recipes/swc Installs the necessary packages for using SWC with Jest in a NestJS project. This includes Jest, SWC core, and the SWC Jest transformer. ```bash $ npm i --save-dev jest @swc/core @swc/jest ``` -------------------------------- ### Install Nest CLI and Create New Project Source: https://docs.nestjs.cn/overview/first-steps Global installation of the NestJS command-line interface and the command to generate a new NestJS project. The `--strict` flag enables stricter TypeScript configurations. ```bash $ npm i -g @nestjs/cli $ nest new project-name ``` -------------------------------- ### Install Nest CLI globally Source: https://docs.nestjs.cn/cli/overview Installs the Nest CLI globally using npm. This method makes the `nest` command available system-wide. Ensure you manage the correct version if you have multiple projects. ```bash $ npm install -g @nestjs/cli ``` -------------------------------- ### Install Mercurius and Apollo Subgraph for NestJS Federation Source: https://docs.nestjs.cn/graphql/federation Installs the required packages for implementing GraphQL federation with Mercurius in a NestJS application. '@apollo/subgraph' is essential for building subgraph schemas and defining federation features. ```bash npm install --save @apollo/subgraph @nestjs/mercurius ``` -------------------------------- ### GET /filtered-posts/:searchString Source: https://docs.nestjs.cn/recipes/prisma Filters posts based on a search string in their title or content. ```APIDOC ## GET /filtered-posts/:searchString ### Description Filters posts based on a search string that appears in their title or content. ### Method GET ### Endpoint /filtered-posts/:searchString #### Path Parameters - **searchString** (string) - Required - The string to search for within post titles and content. ### Response #### Success Response (200) - **PostModel[]** (array) - An array of post objects matching the search criteria. #### Response Example ```json [ { "id": 3, "title": "Example Search Post", "content": "This post contains the search string.", "published": true, "authorEmail": "user3@example.com" } ] ``` ``` -------------------------------- ### Create and run a new Nest project Source: https://docs.nestjs.cn/cli/overview Commands to create a new Nest project named 'my-nest-project', navigate into its directory, and start the development server. The application automatically recompiles and reloads on source file changes. ```bash $ nest new my-nest-project $ cd my-nest-project $ npm run start:dev ``` -------------------------------- ### NestJS BullMQ Event Listener Example Source: https://docs.nestjs.cn/techniques/queues Demonstrates how to use NestJS decorators like @Processor and @OnQueueActive to listen for BullMQ events within a consumer class. The example shows logging when a job becomes active. ```typescript import { Processor, Process, OnQueueActive } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('audio') export class AudioConsumer { @OnQueueActive() onActive(job: Job) { console.log( `Processing job ${job.id} of type ${job.name} with data ${job.data}...`, ); } ... ``` -------------------------------- ### NestJS Guard Execution Order Example Source: https://docs.nestjs.cn/faq/request-lifecycle Demonstrates the execution order of guards in NestJS. Guards are executed sequentially, starting from global guards, then controller guards, and finally route guards. The example shows how multiple guards applied at different levels are resolved. ```typescript import { Controller, Get, UseGuards } from '@nestjs/common'; // Assume Guard1, Guard2, Guard3 are defined elsewhere and implement the Guard interface. @UseGuards(Guard1, Guard2) @Controller('cats') export class CatsController { constructor(private catsService: CatsService) {} @UseGuards(Guard3) @Get() getCats(): Cats[] { return this.catsService.getCats(); } } ``` -------------------------------- ### Load Environment File Before App Start with Nest CLI Source: https://docs.nestjs.cn/techniques/configuration Uses the Nest CLI's `--env-file` option to load a specified `.env` file before the Nest application starts. This is useful for providing configuration needed during the application bootstrapping phase, such as for microservice setup. ```bash $ nest start --env-file .env ``` -------------------------------- ### Configure GraphQLModule with Apollo Driver Source: https://docs.nestjs.cn/graphql/quick-start Configures the GraphQLModule to use the Apollo driver. This is the basic setup for integrating GraphQL into a NestJS application. ```typescript import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; @Module({ imports: [ GraphQLModule.forRoot({ driver: ApolloDriver, }), ], }) export class AppModule {} ``` -------------------------------- ### 创建 NestJS 独立应用程序 Source: https://docs.nestjs.cn/standalone-applications 使用 `NestFactory.createApplicationContext` 创建一个 NestJS 独立应用程序实例。此方法返回一个应用程序上下文对象,可用于访问应用程序中的服务和提供者。 ```typescript async function bootstrap() { const app = await NestFactory.createApplicationContext(AppModule); // 您的应用程序逻辑在这里... } bootstrap(); ``` -------------------------------- ### NestJS REPL Setup Source: https://docs.nestjs.cn/recipes/repl This snippet demonstrates how to set up the NestJS REPL by creating a `repl.ts` file and importing the `repl` function from `@nestjs/core`. This allows for interactive inspection of the application's dependency graph. ```typescript import { repl } from '@nestjs/core'; import { AppModule } from './src/app.module'; async function bootstrap() { await repl(AppModule); } bootstrap(); ``` -------------------------------- ### Route with Wildcard Path Source: https://docs.nestjs.cn/overview/controllers Illustrates using a wildcard '*' in a route path to match any characters at the end of the path. This example matches any route starting with 'abcd/'. ```APIDOC ## GET /abcd/* ### Description Matches any route starting with 'abcd/'. ### Method GET ### Endpoint /abcd/* ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **string**: A string indicating the route matched. #### Response Example ``` "This route uses a wildcard" ``` ``` -------------------------------- ### Get Nest CLI help Source: https://docs.nestjs.cn/cli/overview Displays a list of available Nest CLI commands. This is useful for understanding the CLI's capabilities and syntax. ```bash $ nest --help ``` -------------------------------- ### Test Sentry Integration in NestJS Source: https://docs.nestjs.cn/recipes/sentry Adds a simple GET endpoint to deliberately throw an error, allowing verification that Sentry is correctly capturing and reporting errors to the Sentry dashboard. ```typescript @Get("debug-sentry") getError() { throw new Error("My first Sentry error!"); } ``` -------------------------------- ### NATS Microservice Setup Source: https://docs.nestjs.cn/microservices/nats Demonstrates how to create a NestJS microservice using the NATS transport layer. This involves importing `Transport` and configuring the NATS server details. ```APIDOC ## NATS Microservice Setup ### Description This example shows how to configure a NestJS application to use NATS as its microservice transport mechanism. ### Method `createMicroservice()` ### Endpoint N/A (Server-side configuration) ### Parameters #### Request Body - **transport** (Transport.NATS) - Required - Specifies the NATS transport. - **options** (object) - Required - Configuration options for the NATS transport. - **servers** (string[]) - Required - Array of NATS server URLs (e.g., `['nats://localhost:4222']`). - **queue** (string) - Optional - The name of the queue group for load balancing. - **gracefulShutdown** (boolean) - Optional - Enables graceful shutdown. Defaults to `false`. - **gracePeriod** (number) - Optional - Milliseconds to wait for servers after unsubscribing. Defaults to `10000`. ### Request Example ```typescript const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.NATS, options: { servers: ['nats://localhost:4222'], }, }); ``` ### Response N/A (This is a configuration step, not an API request/response). ``` -------------------------------- ### Automatic Dependency Mocking with useMocker (NestJS) Source: https://docs.nestjs.cn/fundamentals/unit-testing Shows how to use the `useMocker()` method with `Test.createTestingModule()` to automatically mock missing dependencies using a factory function. This example mocks the `CatsService` dependency for the `CatsController`. ```typescript // ... import { ModuleMocker, MockFunctionMetadata } from 'jest-mock'; const moduleMocker = new ModuleMocker(global); describe('CatsController', () => { let controller: CatsController; beforeEach(async () => { const moduleRef = await Test.createTestingModule({ controllers: [CatsController], }) .useMocker((token) => { const results = ['test1', 'test2']; if (token === CatsService) { return { findAll: jest.fn().mockResolvedValue(results) }; } if (typeof token === 'function') { const mockMetadata = moduleMocker.getMetadata( token ) as MockFunctionMetadata; const Mock = moduleMocker.generateFromMetadata(mockMetadata); return new Mock(); } }) .compile(); controller = moduleRef.get(CatsController); }); }); ``` -------------------------------- ### Get LazyModuleLoader from Application Instance Source: https://docs.nestjs.cn/fundamentals/lazy-loading-modules Shows how to obtain a reference to the LazyModuleLoader provider directly from the Nest application instance, typically in the application's bootstrap file (e.g., main.ts). ```typescript // "app" represents the Nest application instance const lazyModuleLoader = app.get(LazyModuleLoader); ``` -------------------------------- ### Schema-First: AppModule Configuration Source: https://docs.nestjs.cn/graphql/federation Configures the `GraphQLModule` for the schema-first approach using `MercuriusFederationDriver`. It enables federation metadata and specifies the location of GraphQL schema files. This setup is essential for integrating with a federated GraphQL architecture. ```typescript import { MercuriusFederationDriver, MercuriusFederationDriverConfig, } from '@nestjs/mercurius'; import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { PostsResolver } from './posts.resolver'; @Module({ imports: [ GraphQLModule.forRoot({ driver: MercuriusFederationDriver, federationMetadata: true, typePaths: ['**/*.graphql'], }), ], providers: [PostsResolver], }) export class AppModule {} ``` -------------------------------- ### NestJS Mercurius Federation - Schema First Module Configuration Source: https://docs.nestjs.cn/graphql/federation Configures the GraphQLModule in NestJS to use the Mercurius Federation driver in a schema-first setup. It specifies the location of GraphQL schema files and enables federation metadata. ```typescript import { MercuriusFederationDriver, MercuriusFederationDriverConfig, } from '@nestjs/mercurius'; import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { UsersResolver } from './users.resolver'; @Module({ imports: [ GraphQLModule.forRoot({ driver: MercuriusFederationDriver, typePaths: ['**/*.graphql'], federationMetadata: true, }), ], providers: [UsersResolver], }) export class AppModule {} ``` -------------------------------- ### Adding a Basic Job to a Bull Queue Source: https://docs.nestjs.cn/techniques/queues Provides an example of adding a job to a Bull queue using the 'add' method. The job data is passed as a JavaScript object, which must be serializable as it will be stored in Redis. ```typescript const job = await this.audioQueue.add({ foo: 'bar', }); ``` -------------------------------- ### SWC Configuration File (.swcrc) Source: https://docs.nestjs.cn/recipes/swc Example configuration for SWC, specifying parser settings, source maps, and minification options. ```json { "$schema": "https://swc.rs/schema.json", "sourceMaps": true, "jsc": { "parser": { "syntax": "typescript", "decorators": true, "dynamicImport": true }, "baseUrl": "./" }, "minify": false } ``` -------------------------------- ### NestJS REPL Interaction Examples Source: https://docs.nestjs.cn/recipes/repl These examples showcase how to interact with the NestJS REPL. You can retrieve service instances, call their methods, and inspect controllers. It also shows how to list available methods and debug the application's structure. ```typescript > get(AppService).getHello() 'Hello World!' ``` ```typescript > appController = get(AppController) AppController { appService: AppService {} } > await appController.getHello() 'Hello World!' ``` ```typescript > methods(AppController) Methods: ◻ getHello ``` ```typescript > debug() AppModule: - controllers: ◻ AppController - providers: ◻ AppService ``` -------------------------------- ### Wildcard Route Matching - NestJS Source: https://docs.nestjs.cn/overview/controllers Implements wildcard routing using the asterisk (*) in a route path. This allows a single handler to match multiple paths that share a common prefix. The example matches any route starting with 'abcd/'. ```typescript @Get('abcd/*') findAll() { return 'This route uses a wildcard'; } ``` -------------------------------- ### Compose Multiple Decorators with applyDecorators (NestJS) Source: https://docs.nestjs.cn/overview/custom-decorators Shows how to combine multiple NestJS decorators into a single reusable decorator using the `applyDecorators` helper. This example creates an '@Auth' decorator that applies role-based access control and Swagger decorators. ```typescript import { applyDecorators, SetMetadata, UseGuards } from '@nestjs/common'; import { ApiBearerAuth, ApiUnauthorizedResponse } from '@nestjs/swagger'; // Assuming AuthGuard and RolesGuard are defined elsewhere // import { AuthGuard } from './auth.guard'; // import { RolesGuard } from './roles.guard'; // type Role = 'admin' | 'user'; export function Auth(...roles: Role[]) { return applyDecorators( SetMetadata('roles', roles), UseGuards(AuthGuard, RolesGuard), ApiBearerAuth(), ApiUnauthorizedResponse({ description: 'Unauthorized' }), ); } // Example usage: // @Get('users') // @Auth('admin') // findAllUsers() {} ``` -------------------------------- ### Creating a Client Proxy with ClientProxyFactory Source: https://docs.nestjs.cn/microservices/basics Illustrates creating a custom ClientProxy provider using the ClientProxyFactory.create() method. ```APIDOC ## Creating a Client Proxy with ClientProxyFactory ### Description Create a custom `ClientProxy` provider using the `ClientProxyFactory.create()` static method, allowing for dynamic configuration retrieval. ### Method `ClientProxyFactory.create()` ### Endpoint N/A (Provider Configuration) ### Parameters #### Provider Configuration - **provide** (string) - Required - The injection token for the `ClientProxy`. - **useFactory** (Function) - Required - A factory function that creates the `ClientProxy`. - **inject** (Array) - Optional - Dependencies for the `useFactory` function. ### Request Example ```typescript @Module({ providers: [ { provide: 'MATH_SERVICE', useFactory: (configService: ConfigService) => { const mathSvcOptions = configService.getMathSvcOptions(); return ClientProxyFactory.create(mathSvcOptions); }, inject: [ConfigService], } ] ... }) export class AppModule {} ``` ### Response N/A ``` -------------------------------- ### Code-First: UsersResolver for Post Field Source: https://docs.nestjs.cn/graphql/federation Implements the `UsersResolver` to resolve the `posts` field for the `User` entity in a code-first setup. The `posts` field is resolved by calling the `postsService.forAuthor` method, passing the user's `id` to fetch related posts. ```typescript import { Parent, ResolveField, Resolver } from '@nestjs/graphql'; import { PostsService } from './posts.service'; import { Post } from './post.entity'; import { User } from './user.entity'; @Resolver(() => User) export class UsersResolver { constructor(private readonly postsService: PostsService) {} @ResolveField(() => [Post]) public posts(@Parent() user: User): Post[] { return this.postsService.forAuthor(user.id); } } ``` -------------------------------- ### NestJS Mercurius Federation - Code First Module Configuration Source: https://docs.nestjs.cn/graphql/federation Configures the GraphQLModule in NestJS to use the Mercurius Federation driver in a code-first setup. It enables automatic schema generation and federation metadata, integrating the User resolver and service. ```typescript import { MercuriusFederationDriver, MercuriusFederationDriverConfig, } from '@nestjs/mercurius'; import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { UsersResolver } from './users.resolver'; import { UsersService } from './users.service'; // 本示例未包含此内容 @Module({ imports: [ GraphQLModule.forRoot({ driver: MercuriusFederationDriver, autoSchemaFile: true, federationMetadata: true, }), ], providers: [UsersResolver, UsersService], }) export class AppModule {} ``` -------------------------------- ### Create Custom Apollo Plugin in NestJS Source: https://docs.nestjs.cn/graphql/plugins Demonstrates how to create a custom Apollo Server plugin in NestJS. It uses the `@Plugin` decorator from `@nestjs/apollo` and implements the `ApolloServerPlugin` interface from `@apollo/server`. The example plugin logs messages when a request starts and when the response is about to be sent. ```typescript import { ApolloServerPlugin, GraphQLRequestListener } from '@apollo/server'; import { Plugin } from '@nestjs/apollo'; @Plugin() export class LoggingPlugin implements ApolloServerPlugin { async requestDidStart(): Promise> { console.log('Request started'); return { async willSendResponse() { console.log('Will send response'); }, }; } } ``` -------------------------------- ### Initialize Prisma Configuration Source: https://docs.nestjs.cn/recipes/prisma Initializes Prisma in your project by creating a 'prisma' directory with 'schema.prisma' and '.env' files. This command sets up the basic Prisma configuration. ```bash npx prisma init ``` -------------------------------- ### POST /user Source: https://docs.nestjs.cn/recipes/prisma Creates a new user. ```APIDOC ## POST /user ### Description Creates a new user. ### Method POST ### Endpoint /user #### Request Body - **email** (string) - Required - The email address of the new user. - **name** (string) - Optional - The name of the new user. ### Request Example ```json { "email": "newuser@example.com", "name": "New User Name" } ``` ### Response #### Success Response (201) - **UserModel** (object) - The newly created user object. #### Response Example ```json { "id": 1, "email": "newuser@example.com", "name": "New User Name" } ``` ``` -------------------------------- ### Implement Job Processing Logic in a BullMQ Consumer Source: https://docs.nestjs.cn/techniques/queues Shows a NestJS consumer extending `WorkerHost` to process jobs. The `process` method receives a `Job` object and can update its progress using `job.updateProgress()`. This example simulates a transcoding process with 100 steps. ```typescript import { Processor, WorkerHost } from '@nestjs/bullmq'; import { Job } from 'bullmq'; @Processor('audio') export class AudioConsumer extends WorkerHost { async process(job: Job): Promise { let progress = 0; for (let i = 0; i < 100; i++) { await doSomething(job.data); progress += 1; await job.updateProgress(progress); } return {}; } } ``` -------------------------------- ### Create New Nest Project (`nest new`) Source: https://docs.nestjs.cn/cli/usages Initializes a new NestJS project with a standard structure. It prompts for package manager selection and sets up folders for source code and end-to-end tests. ```bash $ nest new [options] $ nest n [options] ``` -------------------------------- ### Access Provider from a Lazy Loaded Module Source: https://docs.nestjs.cn/fundamentals/lazy-loading-modules Explains how to retrieve an instance of a provider (e.g., LazyService) from a dynamically loaded module. After loading the module using LazyModuleLoader, you can use the module reference's get() method with the provider's class or token. ```typescript const { LazyModule } = await import('./lazy.module'); const moduleRef = await this.lazyModuleLoader.load(() => LazyModule); const { LazyService } = await import('./lazy.service'); const lazyService = moduleRef.get(LazyService); ``` -------------------------------- ### Registering a Microservice Client Source: https://docs.nestjs.cn/microservices/basics Demonstrates how to register a microservice client using ClientsModule.register() with TCP transport. ```APIDOC ## Registering a Microservice Client ### Description Register a microservice client using the `ClientsModule.register()` static method. This method accepts an array of microservice transporter configurations. ### Method `ClientsModule.register()` ### Endpoint N/A (Module Registration) ### Parameters #### Request Body - **name** (string) - Required - The injection token for the `ClientProxy` instance. - **transport** (Transport) - Optional - The transport layer to use (defaults to `Transport.TCP`). - **options** (object) - Optional - Configuration options for the transport layer. ### Request Example ```typescript @Module({ imports: [ ClientsModule.register([ { name: 'MATH_SERVICE', transport: Transport.TCP }, ]), ], }) export class AppModule {} ``` ### Response N/A ``` -------------------------------- ### Set Custom HTTP Status Code - NestJS Source: https://docs.nestjs.cn/overview/controllers Configures a custom HTTP status code for a specific route handler using the @HttpCode() decorator. This overrides the default status codes (e.g., 200 for GET, 201 for POST). The example sets the status code to 204. ```typescript @Post() @HttpCode(204) create() { return 'This action adds a new cat'; } ``` -------------------------------- ### Filter Subscription Events with 'filter' Property (Schema-First) Source: https://docs.nestjs.cn/graphql/subscriptions This example demonstrates filtering subscription events in a schema-first setup. The 'filter' property is used with the @Subscription() decorator to specify a filtering logic based on payload and variables. It also shows how to access injected providers within the filter function. ```typescript @Subscription('commentAdded', { filter: (payload, variables) => payload.commentAdded.title === variables.title, }) commentAdded(@Context('pubsub') pubSub: PubSub) { return pubSub.subscribe('commentAdded'); } ``` ```typescript @Subscription('commentAdded', { filter(this: AuthorResolver, payload, variables) { // "this" refers to an instance of "AuthorResolver" return payload.commentAdded.title === variables.title; } }) commentAdded(@Context('pubsub') pubSub: PubSub) { return pubSub.subscribe('commentAdded'); } ```