NestJS Documentation

website·Indexed 30 days ago

https://nestjs.xuxo.top

Comprehensive guides and recipes for the NestJS framework, covering fundamentals like lifecycle events and request lifecycles, microservices, and OpenAPI integration. Includes detailed recipes for integrating Prisma, TypeORM, Sequelize, MongoDB (Mongoose), MikroORM, Passport, CQRS, and Sentry, as well as migration guides and FAQ on serverless and hybrid applications.

Tokens
149.2K
Snippets
833
Records
930
Agent score
49%

What's inside NestJS

  1. Overview of GraphQL Federation in NestJS

    GraphQL Federation allows a monolithic GraphQL server to be split into independent microservices. It consists of a gateway and one or more federated microservices (subgraphs). Each microservice holds a partial schema, and the gateway merges them into a single schema for the client.

    Key principles include declarative graph construction, separation of code by concern rather than type, and maintaining a product-centric graph for clients.

    Note: Federation currently does not support subscriptions.

  2. Overview of the NestJS Swagger CLI Plugin

    The NestJS Swagger plugin enhances the TypeScript compilation process to automatically generate OpenAPI documentation, reducing the need to manually add @ApiProperty decorators to every DTO field. It uses Abstract Syntax Tree (AST) analysis to derive metadata from TypeScript types and class-validator decorators.

    Key automated behaviors include:

    • Adding @ApiProperty to DTO properties (unless @ApiHideProperty is used).
    • Setting required: false for optional properties (e.g., name?: string).
    • Determining type or enum based on the TypeScript type.
    • Setting default values based on assigned defaults.
    • Adding validation rules if classValidatorShim is enabled.
    • Adding response decorators to endpoints with correct status codes and types.
    • Generating descriptions and examples from JSDoc comments if introspectComments is enabled.

    Important Constraints:

    • Files must have the suffix .dto.ts or .entity.ts to be analyzed by default.
    • Runtime validation is NOT handled by the plugin; you must still use class-validator decorators (e.g., @IsEmail()) for actual request validation.
    • When using mapped type utilities like PartialType, import them from @nestjs/swagger instead of @nestjs/mapped-types for plugin compatibility.
  3. Overview of NestJS Libraries in Monorepos

    In a NestJS monorepo, a library is a project that cannot run independently; it must be imported into an application to execute. Libraries provide a lightweight way to share modular components (like an AuthModule) across multiple applications within the same organization, ensuring all consumers use the latest version of the shared code without needing to publish separate npm packages.
  4. Overview of the Suites testing framework

    Suites is an open-source unit testing framework for TypeScript dependency injection frameworks. It serves as an alternative to manually creating mock objects or using non-typed test doubles. It reads NestJS service metadata at runtime to automatically generate fully typed mock objects for all dependencies, ensuring type-safe tests and eliminating boilerplate code. While it can work with Test.createTestingModule(), it is specifically optimized for focused unit tests. For verifying module connections, decorators, guards, and interceptors, Test.createTestingModule() remains the recommended approach.
  5. Overview of NestJS Pipes

    Pipes are classes annotated with @Injectable() that implement the PipeTransform interface. They operate on the arguments passed to controller route handlers before the method is executed. Pipes have two primary use cases:

    1. Transformation: Converting input data to a desired format (e.g., string to integer).
    2. Validation: Evaluating input data and throwing an exception if it is invalid, preventing the controller method from executing.

    Pipes run within the exception layer, meaning any exception thrown inside a pipe is handled by global and contextual exception filters.

  6. Overview of the NestJS GraphQL CLI Plugin

    The NestJS GraphQL CLI plugin is an optional tool for code-first GraphQL development. It uses the Abstract Syntax Tree (AST) to automatically add @Field decorators to properties of input objects, object types, and argument classes, reducing the need for manual boilerplate.

    Key automated behaviors include:

    • Adding @Field to all properties unless @HideField is used.
    • Setting nullable: true if a property is marked as optional (e.g., name?: string).
    • Determining the GraphQL type based on the TypeScript type (including arrays).
    • Generating field descriptions from TSDoc comments if introspectComments is enabled.

    Constraint: The plugin only analyzes files with specific suffixes: .input.ts, .args.ts, .entity.ts, or .model.ts (configurable via typeFileNameSuffix).

  7. Overview of NestJS Framework

    NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. It is built with TypeScript (while supporting pure JavaScript) and combines elements of Object-Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP). By default, Nest uses Express as its HTTP server framework but can be optionally configured to use Fastify. It provides an abstraction layer over these frameworks while still exposing their underlying APIs for use with third-party modules.
  8. Understand the Nest CLI build and execution flow

    Nest applications are standard TypeScript applications that must be compiled to JavaScript before execution. The Nest CLI provides a wrapper around standard tools to simplify this process:

    • nest build: A wrapper around the tsc compiler, swc compiler (for standard projects), or ts-loader via webpack (for monorepos). It primarily handles tsconfig-paths out-of-the-box.
    • nest start: Ensures the project is built (via nest build) and then invokes the node command to execute the compiled application.
    • nest generate: Used to scaffold new Nest projects or components.
  9. Monitor MQTT server status updates

    You can subscribe to the status stream of an MQTT server to receive real-time notifications about the server's state. The status updates use the MqttStatus type, which is available in the @nestjs/microservices package.
    import { MqttStatus } from '@nestjs/microservices';
    
    const server = app.connectMicroservice<MicroserviceOptions>(...);
    server.status.subscribe((status: MqttStatus) => {
      console.log(status);
    });
  10. View system and package information using nest info

    The nest info command displays detailed information about the installed Nest packages and the current system environment (e.g., OS version, Node.js version).
    nest info
  11. Understand NestJS Dependency Injection (DI) Basics

    Dependency Injection in NestJS is an Inversion of Control (IoC) technique where the instantiation of dependencies is delegated to the NestJS runtime system (the IoC container) rather than being handled manually in the code.

    The process involves three key steps:

    1. Declaration: Marking a class as a provider using the @Injectable() decorator.
    2. Request: Declaring a dependency in a class constructor (e.g., constructor(private catsService: CatsService) {}).
    3. Registration: Associating the provider token with the class in a module's providers array.

    Nest resolves these dependencies transitively (bottom-up) during application bootstrap to ensure the correct instantiation order.

    // 1. Declaration
    @Injectable()
    export class CatsService {}
    
    // 2. Request
    @Controller('cats')
    export class CatsController {
      constructor(private catsService: CatsService) {}
    }
    
    // 3. Registration
    @Module({
      controllers: [CatsController],
      providers: [CatsService],
    })
    export class AppModule {}
  12. Understand NestJS project organization modes

    NestJS provides two ways to organize code:

    1. Standard Mode: The default mode for single-project applications. It has independent dependencies and settings, suitable for projects that don't require shared modules or complex build pipelines.
    2. Monorepo Mode: Treats code as part of a lightweight monorepo. It is ideal for teams or multi-project environments, automating build processes and facilitating the creation of modular components (libraries) for code reuse and shared configurations (e.g., ESLint rules). This mode uses the concept of a workspace coordinated via nest-cli.json.