NestJS course Β· Module 11: Swagger and OpenAPI

CLI Plugin - The Automatic Scribe

3 min read Β·
In this lesson8

Imagine that in the imperial chancellery you have a scribe who automatically documents every decree based on its content - you don't need to tell him what to write, he understands the document structure on his own. This is exactly how the @nestjs/swagger CLI Plugin works.

The Problem with Manual Documentation

Without the CLI Plugin, you have to manually add @ApiProperty() to every field in every DTO:

// Without CLI Plugin - lots of repetitive code
export class CreateLegionaryDto {
  @ApiProperty({ description: 'Name of the legionary' })
  name: string;

  @ApiProperty({ description: 'Rank', required: false })
  rank?: string;

  @ApiProperty({ description: 'Experience' })
  experience: number;

  @ApiProperty({ description: 'Is active' })
  isActive: boolean;
}

CLI Plugin - Automatic Generation

The CLI Plugin analyzes TypeScript types and automatically generates Swagger metadata. A simple class is enough:

// With CLI Plugin - clean code, automatic documentation
export class CreateLegionaryDto {
  /** Name of the legionary */
  name: string;

  /** Rank in the legion */
  rank?: string;

  /** Years of experience */
  experience: number;

  /** Whether the legionary is active */
  isActive: boolean;
}

The plugin automatically:

  • Recognizes field types (string, number, boolean)
  • Marks fields with ? as optional
  • Converts JSDoc comments into Swagger descriptions
  • Generates appropriate @ApiProperty() at compile time

Configuration in nest-cli.json

To enable the CLI Plugin, add the appropriate configuration in the nest-cli.json file:

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true,
    "plugins": [
      {
        "name": "@nestjs/swagger",
        "options": {
          "classValidatorShim": true,
          "introspectComments": true,
          "dtoFileNameSuffix": [".dto.ts", ".entity.ts"]
        }
      }
    ]
  }
}

CLI Plugin Options

OptionDescriptionDefault
classValidatorShimAutomatically adds validation rules from class-validatortrue
introspectCommentsUses JSDoc comments as descriptionsfalse
dtoFileNameSuffixWhich files to analyze['.dto.ts', '.entity.ts']
controllerFileNameSuffixController file suffix'.controller.ts'
controllerKeyOfCommentComment key for controllers'description'

introspectComments - Comments as Documentation

When introspectComments is enabled, JSDoc comments become Swagger descriptions:

export class LegionDto {
  /**
   * Unique legion name in the Empire
   * @example 'Legio X Gemina'
   */
  name: string;

  /**
   * Stationing province
   * @example 'Pannonia'
   */
  province: string;

  /**
   * Number of soldiers in the legion
   * @example 5000
   */
  soldiers: number;
}

The @example tag automatically generates an example value in Swagger UI.

classValidatorShim - Integration with Validation

When classValidatorShim is enabled, class-validator decorators affect Swagger documentation:

import { IsString, IsNumber, IsOptional, Min, Max, IsEnum } from 'class-validator';

export class CreateLegionaryDto {
  /** Name of the legionary */
  @IsString()
  name: string;

  /** Rank in the legion */
  @IsEnum(LegionaryRank)
  @IsOptional()
  rank?: LegionaryRank;

  /** Years of experience */
  @IsNumber()
  @Min(0)
  @Max(40)
  experience: number;
}

The plugin automatically:

  • @IsOptional() marks the field as required: false
  • @IsEnum() generates the list of allowed values
  • @Min() / @Max() sets minimum / maximum
  • @IsString() confirms the string type

When to Still Use @ApiProperty?

The CLI Plugin does not replace all use cases of @ApiProperty(). You still need it for:

  • Nested types (type: () => AddressDto)
  • Arrays of objects (type: [LegionaryDto])
  • Complex examples
  • Overriding automatically generated descriptions

Practical Exercise

Configure the CLI Plugin and create a DTO with JSDoc comments:

Code for this lesson: src/nest-cli.config.ts
// CLI Plugin configuration for @nestjs/swagger
// This file presents the nest-cli.json configuration

const nestCliConfig = {
  collection: "@nestjs/schematics",
  sourceRoot: "src",
  compilerOptions: {
    deleteOutDir: true,
    plugins: [
      {
        name: "@nestjs/swagger",
        options: {
          // TODO: Enable classValidatorShim (true)
          // TODO: Enable introspectComments (true)
          // TODO: Set dtoFileNameSuffix to ['.dto.ts', '.entity.ts']
        }
      }
    ]
  }
};

console.log("=== nest-cli.json config ===");
console.log(JSON.stringify(nestCliConfig, null, 2));

// Example DTO with JSDoc comments (instead of @ApiProperty)
class LegionaryDto {
  /** Unique name of the legionary
   * @example 'Marcus Aurelius'
   */
  name: string;

  /** Rank in the legion hierarchy
   * @example 'Centurio'
   */
  rank?: string;

  /** Years of service in the legion
   * @example 8
   */
  experience: number;

  /** Whether the legionary is active in service
   * @example true
   */
  isActive: boolean;
}

console.log("");
console.log("With the CLI Plugin, JSDoc comments become Swagger descriptions");
console.log("The @example tag generates example values");
console.log("Fields with ? are automatically marked as optional");
console.log("classValidatorShim integrates validation with the documentation");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the @nestjs/swagger CLI Plugin do?

  2. 2. What does the introspectComments option do in the @nestjs/swagger CLI Plugin?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Order the steps for enabling the CLI Plugin from the configuration file to the result:

  • Code editor

    Add JSDoc comments with a description and @example to each DTO field

  • Horizontal ordering

    Arrange the elements of a JSDoc comment with the @example tag:

  • Click in order

    Arrange the plugin configuration elements in nest-cli.json from the outer key to the options:

  • Code editor

    Create SenatorResponseDto and CreateSenatorDto, then use them as the type in response decorators

  1. QuestionCLI Plugin Function
  2. Put in orderCLI Plugin Configuration
  3. Coding taskDTO with JSDoc Comments
  4. QuestionThe introspectComments Option
  5. Put in orderThe @example Tag in JSDoc
  6. Click in orderPlugin Configuration in nest-cli.json
  7. QuestionThe classValidatorShim Option
  8. Coding taskResponse DTO with Type in Controller

Useful articles