npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-swagger-decorator

v1.3.0

Published

Minimal swagger decorator for NestJS

Downloads

264

Readme

nestjs-swagger-decorator

Minimal Swagger decorator for NestJS that simplifies complex response handling in your NestJS applications.

How to install

Install the package via npm or yarn:

npm i nestjs-swagger-decorator
# or
yarn add nestjs-swagger-decorator

Old Swagger Response Approach

Handling multiple ApiResponse decorators can quickly clutter your code:

@ApiResponse({ status: 200, description: 'Success', type: GetUserResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 404, description: 'User not found' })
@ApiOperation({ summary: 'Get User by ID' })
async getUserById(@Param('id') id: string) {
  return this.userService.findById(id);
}

This can be tedious and hard to manage as the number of responses grows.

New Approach Using nestjs-swagger-decorator

With nestjs-swagger-decorator, you can streamline the creation of your Swagger documentation:

Example 1: Basic Usage

/// user.swagger.ts
import { BaseSwaggerDecorator } from 'nestjs-swagger-decorator';
import { GetUserResponseDto } from './dto/get-user-response.dto';

export function GetUserSwagger() {
  return BaseSwaggerDecorator(
    { summary: 'Get User by ID', description: 'Fetch user by their unique ID' },
    [
      {
        statusCode: 200,
        responseOptions: [
          {
            model: GetUserResponseDto,
            exampleTitle: 'Success Response',
            exampleDescription: 'A valid user response',
          },
        ],
      },
      {
        statusCode: 404,
        responseOptions: [
          {
            model: ErrorResponseDto,
            exampleTitle: 'User Not Found',
            exampleDescription: 'No user found with this ID',
          },
        ],
      },
    ],
  );
}
// user.controller.ts
import { GetUserSwagger } from './user.swagger';

@Get(':id')
@GetUserSwagger()
async getUserById(@Param('id') id: string) {
  return this.userService.findById(id);
}

Here, you define your Swagger documentation in a separate file and reuse it across your project, keeping your controller code clean.

Example 2: Handling Multiple Responses

If your API has several response scenarios (e.g., 200, 401, 404), you can handle them more easily using response options:

// auth.swagger.ts
import { BaseSwaggerDecorator } from 'nestjs-swagger-decorator';
import { LoginResponseDto } from './dto/login-response.dto';
import { ErrorResponseDto } from './dto/error-response.dto';

export function LoginSwagger() {
  return BaseSwaggerDecorator(
    { summary: 'User Login', description: 'Authenticate user credentials' },
    [
      {
        statusCode: 200,
        responseOptions: [
          {
            model: LoginResponseDto,
            exampleTitle: 'Successful Login',
            exampleDescription: 'Valid credentials provided',
          },
        ],
      },
      {
        statusCode: 401,
        responseOptions: [
          {
            model: ErrorResponseDto,
            exampleTitle: 'Unauthorized',
            exampleDescription: 'Invalid credentials',
          },
        ],
      },
    ],
  );
}
// auth.controller.ts
import { LoginSwagger } from './auth.swagger';

@Post('login')
@LoginSwagger()
async login(@Body() loginDto: LoginDto) {
  return this.authService.login(loginDto);
}

Example 3: Using a Base Response DTO

When you have a base response format that wraps your data, you can define and reuse it easily:

// base-response.dto.ts
export class BaseResponseDto<T> {
  @ApiProperty({ example: 200 })
  statusCode: number;

  @ApiProperty({ type: () => T })
  data: T;

  @ApiProperty({ example: 'Request was successful' })
  message: string;
}
// project.swagger.ts
import { BaseSwaggerDecorator } from 'nestjs-swagger-decorator';
import { BaseResponseDto } from './dto/base-response.dto';
import { ProjectDto } from './dto/project.dto';

export function GetProjectSwagger() {
  return BaseSwaggerDecorator({ summary: 'Get Project Details' }, [
    {
      statusCode: 200,
      baseResponseDto: BaseResponseDto,
      responseOptions: [
        {
          model: ProjectDto,
          exampleTitle: 'Project Found',
          exampleDescription: 'Project data returned successfully',
        },
      ],
    },
  ]);
}

Example 4: Custom Response Overwriting

You can also customize responses by overwriting values in the response:

// user.swagger.ts
import { BaseSwaggerDecorator } from 'nestjs-swagger-decorator';
import { GetUserResponseDto } from './dto/get-user-response.dto';

export function GetUserSwagger() {
  return BaseSwaggerDecorator({ summary: 'Get User by ID' }, [
    {
      statusCode: 200,
      responseOptions: [
        {
          model: GetUserResponseDto,
          exampleTitle: 'User Found',
          exampleDescription: 'Valid user response',
          overwriteValue: { name: 'John Doe' },
        },
      ],
    },
    {
      statusCode: 404,
      responseOptions: [
        {
          model: ErrorResponseDto,
          exampleTitle: 'User Not Found',
          exampleDescription: 'No user found with this ID',
          overwriteValue: { message: 'No such user exists' },
        },
      ],
    },
  ]);
}

In this case, the response will return a user named “John Doe” in the example.

Conclusion

nestjs-swagger-decorator is designed to keep your code clean and concise while still providing rich Swagger documentation. Whether you’re dealing with multiple responses or need base response formats, this library has you covered.

Please visit my github repository, and star me!

Special thanks to developer @ImNM for reference.