CLI Plugin

TypeScript’s metadata reflection system has several limitations which make it impossible to, for instance, determine what properties a class consists of or recognize whether a given property is optional or required. However, some of these constraints can be addressed at compilation time. Nest provides a plugin that enhances the TypeScript compilation process to reduce the amount of boilerplate code required.

info Hint This plugin is opt-in. If you prefer, you can declare all decorators manually, or only specific decorators where you need them.

Overview

The Swagger plugin will automatically:

  • annotate all DTO properties with @ApiProperty unless @ApiHideProperty is used
  • set the required property depending on the question mark (e.g. name?: string will set required: false)
  • set the type or enum property depending on the type (supports arrays as well)
  • set the default property based on the assigned default value
  • set several validation rules based on class-validator decorators (if classValidatorShim set to true)
  • add a response decorator to every endpoint with a proper status and type (response model)
  • generate descriptions for properties and endpoints based on comments (if introspectComments set to true)
  • generate example values for properties based on comments (if introspectComments set to true)

Please, note that your filenames must have one of the following suffixes: ['.dto.ts', '.entity.ts'] (e.g., create-user.dto.ts) in order to be analysed by the plugin.

If you are using a different suffix, you can adjust the plugin’s behavior by specifying the dtoFileNameSuffix option (see below).

Previously, if you wanted to provide an interactive experience with the Swagger UI, you had to duplicate a lot of code to let the package know how your models/components should be declared in the specification. For example, you could define a simple CreateUserDto class as follows:

  1. export class CreateUserDto {
  2. @ApiProperty()
  3. email: string;
  4. @ApiProperty()
  5. password: string;
  6. @ApiProperty({ enum: RoleEnum, default: [], isArray: true })
  7. roles: RoleEnum[] = [];
  8. @ApiProperty({ required: false, default: true })
  9. isEnabled?: boolean = true;
  10. }

While not a significant issue with medium-sized projects, it becomes verbose & hard to maintain once you have a large set of classes.

By enabling the Swagger plugin, the above class definition can be declared simply:

  1. export class CreateUserDto {
  2. email: string;
  3. password: string;
  4. roles: RoleEnum[] = [];
  5. isEnabled?: boolean = true;
  6. }

The plugin adds appropriate decorators on the fly based on the Abstract Syntax Tree. Thus you won’t have to struggle with @ApiProperty decorators scattered throughout the code.

info Hint The plugin will automatically generate any missing swagger properties, but if you need to override them, you simply set them explicitly via @ApiProperty().

Comments introspection

With the comments introspection feature enabled, CLI plugin will generate descriptions and example values for properties based on comments.

For example, given an example roles property:

  1. /**
  2. * A list of user's roles
  3. * @example ['admin']
  4. */
  5. @ApiProperty({
  6. description: `A list of user's roles`,
  7. example: ['admin'],
  8. })
  9. roles: RoleEnum[] = [];

You must duplicate both description and example values. With introspectComments enabled, the CLI plugin can extract these comments and automatically provide descriptions (and examples, if defined) for properties. Now, the above property can be declared simply as follows:

  1. /**
  2. * A list of user's roles
  3. * @example ['admin']
  4. */
  5. roles: RoleEnum[] = [];

Using the CLI plugin

To enable the plugin, open nest-cli.json (if you use Nest CLI) and add the following plugins configuration:

  1. {
  2. "collection": "@nestjs/schematics",
  3. "sourceRoot": "src",
  4. "compilerOptions": {
  5. "plugins": ["@nestjs/swagger"]
  6. }
  7. }

You can use the options property to customize the behavior of the plugin.

  1. "plugins": [
  2. {
  3. "name": "@nestjs/swagger",
  4. "options": {
  5. "classValidatorShim": false,
  6. "introspectComments": true
  7. }
  8. }
  9. ]

The options property has to fulfill the following interface:

  1. export interface PluginOptions {
  2. dtoFileNameSuffix?: string[];
  3. controllerFileNameSuffix?: string[];
  4. classValidatorShim?: boolean;
  5. introspectComments?: boolean;
  6. }
OptionDefaultDescription
dtoFileNameSuffix[‘.dto.ts’, ‘.entity.ts’]DTO (Data Transfer Object) files suffix
controllerFileNameSuffix.controller.tsController files suffix
classValidatorShimtrueIf set to true, the module will reuse class-validator validation decorators (e.g. @Max(10) will add max: 10 to schema definition)
introspectCommentsfalseIf set to true, plugin will generate descriptions and example values for properties based on comments

If you don’t use the CLI but instead have a custom webpack configuration, you can use this plugin in combination with ts-loader:

  1. getCustomTransformers: (program: any) => ({
  2. before: [require('@nestjs/swagger/plugin').before({}, program)]
  3. }),

Integration with ts-jest (e2e tests)

To run e2e tests, ts-jest compiles your source code files on the fly, in memory. This means, it doesn’t use Nest CLI compiler and does not apply any plugins or perform AST transformations.

To enable the plugin, create the following file in your e2e tests directory:

  1. const transformer = require('@nestjs/swagger/plugin');
  2. module.exports.name = 'nestjs-swagger-transformer';
  3. // you should change the version number anytime you change the configuration below - otherwise, jest will not detect changes
  4. module.exports.version = 1;
  5. module.exports.factory = (cs) => {
  6. return transformer.before(
  7. {
  8. // @nestjs/swagger/plugin options (can be empty)
  9. },
  10. cs.tsCompiler.program,
  11. );
  12. };

With this in place, import AST transformer within your jest configuration file. By default (in the starter application), e2e tests configuration file is located under the test folder and is named jest-e2e.json.

  1. {
  2. ... // other configuration
  3. "globals": {
  4. "ts-jest": {
  5. "astTransformers": {
  6. "before": ["<path to the file created above>"],
  7. }
  8. }
  9. }
  10. }

Troubleshooting jest (e2e tests)

In case jest does not seem to pick up your configuration changes, it’s possible that Jest has already cached the build result. To apply the new configuration, you need to clear Jest’s cache directory.

To clear the cache directory, run the following command in your NestJS project folder:

  1. $ npx jest --clearCache

In case the automatic cache clearance fails, you can still manually remove the cache folder with the following commands:

  1. # Find jest cache directory (usually /tmp/jest_rs)
  2. # by running the following command in your NestJS project root
  3. $ npx jest --showConfig | grep cache
  4. # ex result:
  5. # "cache": true,
  6. # "cacheDirectory": "/tmp/jest_rs"
  7. # Remove or empty the Jest cache directory
  8. $ rm -rf <cacheDirectory value>
  9. # ex:
  10. # rm -rf /tmp/jest_rs