NestJS Documentation

repository·master·Indexed 23 days ago

https://github.com/nestjs/docs.nestjs.com

Official documentation for NestJS, covering the Nest CLI, project structures (Standard and Monorepo modes), library management, and the creation of standalone applications using NestFactory.createApplicationContext. This repository also contains the documentation engine source code, built with Angular CLI and Dgeni.

Tokens
189.1K
Snippets
640
Records
779
Agent score
79%

What's inside NestJS Documentation

  1. Overview of Dgeni Templates

    master

    The tools/transforms/templates directory contains Dgeni templates used for generating API and content documentation.

    Key characteristics of these templates include:

    • DocType Specificity: Generally, there is a dedicated template for each docType.
    • Composition: Templates can extend or include other templates to share structure.
    • Macros: Templates can import macros from other template files to reuse logic.
  2. What is NestJS?

    master

    NestJS is a framework for building efficient, scalable Node.js server-side applications. It is designed to solve the problem of architecture in Node.js applications by providing an out-of-the-box application architecture that is highly testable, scalable, loosely coupled, and easily maintainable.

    Key characteristics:

    • Language Support: Built with and fully supports TypeScript, but also enables development in pure JavaScript.
    • Programming Paradigms: Combines elements of Object-Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP).
    • Underlying Engines: Uses robust HTTP server frameworks like Express (default) or can be configured to use Fastify.
    • Abstraction: Provides a high-level abstraction over Express/Fastify while still exposing their APIs directly for third-party module compatibility.
    • Inspiration: The architecture is heavily inspired by Angular.
  3. Overview of docs.nestjs.com project tooling

    master
    The docs.nestjs.com website content and certain configuration files are generated from source files using Dgeni, a general-purpose documentation generation tool. Markdown files located in the content directory undergo a transformation process to produce the final files consumed by the docs.nestjs.com web frontend.
  4. What is Middleware in NestJS

    master

    Middleware is a function called before the route handler. It has access to the request and response objects, and the next() function to pass control to the next middleware in the stack. If the current middleware does not end the request-response cycle, it must call next() to avoid leaving the request hanging.

    Middleware can:

    • Execute any code.
    • Make changes to the request and response objects.
    • End the request-response cycle.
    • Call the next middleware function in the stack.

    Note: Express and Fastify handle middleware differently and provide different method signatures.

  5. Overview of the NestJS Swagger CLI Plugin

    master

    The NestJS Swagger CLI plugin is an opt-in tool that enhances the TypeScript compilation process to reduce boilerplate code for OpenAPI documentation. It automatically adds @ApiProperty decorators to DTOs and response decorators to endpoints by analyzing the Abstract Syntax Tree (AST).

    Key capabilities:

    • Automatically annotates DTO properties with @ApiProperty (unless @ApiHideProperty is used).
    • Sets required status based on TypeScript optionality (e.g., name?: string becomes required: false).
    • Infers type, enum, and default values from TypeScript types and assignments.
    • Maps class-validator decorators to OpenAPI validation rules (if classValidatorShim is enabled).
    • Adds response decorators to endpoints with appropriate status codes and types.
    • Generates descriptions and example values from code comments (if introspectComments is enabled).

    Important Requirements:

    • File Suffixes: By default, the plugin only analyzes files ending in .dto.ts or .entity.ts. You can customize this via dtoFileNameSuffix.
    • Runtime Validation: The plugin only generates documentation. You must still use class-validator decorators (like @IsEmail()) for actual runtime validation.
    • Mapped Types: When using utilities like PartialType, import them from @nestjs/swagger instead of @nestjs/mapped-types to ensure the plugin picks up the schema.
    export class CreateUserDto {
      email: string;
      password: string;
      roles: RoleEnum[] = [];
      isEnabled?: boolean = true;
    }
  6. Overview of NestJS Dgeni packages

    master

    The NestJS documentation tooling is modularized into several Dgeni packages, each with a specific responsibility in the transformation pipeline:

    • nestjs-package: The orchestrator. It manages the other packages and sets the final configuration. It is also responsible for file system cleanup.
    • nestjs-base-package: Provides common configurations, services, and processors. It handles path resolution for inputs, outputs, and templates.
    • nestjs-content-package: Manages hand-written documentation content. It processes markdown files in content folders and handles JSON files within those folders (e.g., content/discover/who-uses.json).
    • content-package: A specialized package for handling markdown files. It defines a content DocType that extracts a content body and a title from each markdown file.
  7. Merge metadata from Controller and Handler levels

    master

    When metadata is applied at both the Controller level (class) and the Method level (handler), you can use Reflector to merge them using two different strategies:

    1. getAllAndOverride(): If metadata exists at both levels, the method-level metadata overrides the class-level metadata. Use this when you want to set a default at the class level but override it for specific routes.
    2. getAllAndMerge(): Combines metadata from both levels (e.g., merging arrays or objects). Use this when you want to accumulate permissions or roles.

    Both methods accept an array of contexts (e.g., [context.getHandler(), context.getClass()]) as the second argument.

  8. What are Guards and when to use them

    master

    A Guard is a class annotated with @Injectable() that implements the CanActivate interface. Its single responsibility is to determine whether a request will be handled by a route handler based on runtime conditions like permissions, roles, or ACLs (authorization).

    Key differences from Middleware:

    • Context Awareness: Unlike middleware, Guards have access to the ExecutionContext, meaning they know exactly which handler will be executed next.
    • Execution Order: Guards are executed after all middleware, but before any interceptor or pipe.

    Use Guards for authorization logic to keep your code declarative and DRY.

    import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
      canActivate(
        context: ExecutionContext,
      ): boolean | Promise<boolean> | Observable<boolean> {
        const request = context.switchToHttp().getRequest();
        return validateRequest(request);
      }
    }
  9. How context and event decorators work in Necord

    master

    Necord uses decorators to handle Discord events within NestJS providers:

    • @Once(eventName): Triggers only the first time the specified event occurs (e.g., 'ready').
    • @On(eventName): Triggers every time the specified event occurs (e.g., 'warn').
    • @Context(): Injects the event context into the method. The context type can be explicitly typed using ContextOf<'eventName'> to ensure type safety for the arguments.
    • @TargetUser() and @TargetMessage(): Used in context menu commands to inject the specific user or message being interacted with.
    import { Injectable, Logger } from '@nestjs/common';
    import { Context, On, Once, ContextOf } from 'necord';
    import { Client } from 'discord.js';
    
    @Injectable()
    export class AppService {
      private readonly logger = new Logger(AppService.name);
    
      @Once('ready')
      public onReady(@Context() [client]: ContextOf<'ready'>) {
        this.logger.log(`Bot logged in as ${client.user.username}`);
      }
    
      @On('warn')
      public onWarn(@Context() [message]: ContextOf<'warn'>) {
        this.logger.warn(message);
      }
    }
  10. Enable automatic payload transformation

    master
    By setting transform: true in the ValidationPipe options, Nest will automatically convert plain JavaScript objects from the network into instances of your DTO classes. It also performs primitive type conversion (e.g., converting a path parameter string to a number if the method signature specifies number).
  11. Resolve request-scoped providers within a Passport strategy

    master

    Passport strategies are not designed to be request-scoped. To use a request-scoped provider (like an AuthService) inside a strategy, inject ModuleRef and use ContextIdFactory.getByRequest(request) to create a context ID from the current request. Then, use moduleRef.resolve() to asynchronously obtain the request-scoped instance. Note that you must set passReqToCallback: true in the strategy configuration.

    constructor(private moduleRef: ModuleRef) {
      super({
        passReqToCallback: true,
      });
    }
    
    async validate(request: Request, username: string, password: string) {
      const contextId = ContextIdFactory.getByRequest(request);
      // AuthService is a request-scoped provider
      const authService = await this.moduleRef.resolve(AuthService, contextId);
      // ...
    }
  12. Implement health checks with @nestjs/terminus

    master

    Health checks are essential for monitoring the status of your application in production. You can implement these using the @nestjs/terminus package. It allows you to create endpoints that verify the health of various components, including:

    • Database connections
    • External services
    • Custom logic/checks