Skip to main content

nestjs-swagger

A simple documentation builder for NestJS Swagger module that simplifies creating OpenAPI documentation for your REST APIs.

Installation

npm install @globalart/nestjs-swagger

Overview

This package provides a convenient SwaggerDocumentation decorator for automatic Swagger documentation generation in NestJS applications. It significantly simplifies the process of adding documentation to your endpoints by providing a unified interface for describing operations and possible errors.

Key Features

  • 📝 Simple decorator for endpoint documentation
  • 🔧 Pre-configured descriptions for standard HTTP errors
  • 📊 Support for paginated responses
  • 🎯 Support for arrays in responses
  • 📋 Automatic schema generation for DTOs
  • 🛡️ Full TypeScript typing

Quick Start

import { Controller, Get } from '@nestjs/common';
import { SwaggerDocumentation, ERROR_DESCRIPTIONS } from '@globalart/nestjs-swagger';

@Controller('users')
export class UsersController {
@Get()
@SwaggerDocumentation({
endpointDescription: 'Get list of all users',
endpointSummary: 'List users',
error400Description: ERROR_DESCRIPTIONS.BAD_REQUEST,
error401Description: ERROR_DESCRIPTIONS.UNAUTHORIZED,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR
})
async getAllUsers() {
return [];
}
}

API Reference

SwaggerDocumentation

Decorator for automatic Swagger documentation generation.

Parameters

ParameterTypeDescription
endpointDescriptionstringDetailed endpoint description
endpointSummarystringBrief endpoint description
responseDtoFunctionDTO class for response
isArraybooleanIndicates that response is an array
isPaginatedbooleanIndicates that response is paginated
error400Descriptionstring400 error description
error401Descriptionstring401 error description
error403Descriptionstring403 error description
error404Descriptionstring404 error description
error409Descriptionstring409 error description
error422Descriptionstring422 error description
error429Descriptionstring429 error description
error500Descriptionstring500 error description
error503Descriptionstring503 error description

ERROR_DESCRIPTIONS

Object with pre-configured error descriptions:

export const ERROR_DESCRIPTIONS = {
BAD_REQUEST: "Invalid request data or parameters",
UNAUTHORIZED: "Authentication required",
FORBIDDEN: "Access denied",
NOT_FOUND: "Resource not found",
CONFLICT: "Resource already exists or conflict detected",
UNPROCESSABLE_ENTITY: "Validation error",
RATE_LIMIT_EXCEEDED: "Rate limit exceeded. Too many requests",
INTERNAL_SERVER_ERROR: "Internal server error",
SERVICE_UNAVAILABLE: "Service temporarily unavailable"
};

Usage Examples

Basic Usage

import { Controller, Get } from '@nestjs/common';
import { SwaggerDocumentation, ERROR_DESCRIPTIONS } from '@globalart/nestjs-swagger';

@Controller()
export class AppController {
@Get('hello')
@SwaggerDocumentation({
endpointDescription: 'Simple greeting endpoint',
endpointSummary: 'Greeting',
error400Description: ERROR_DESCRIPTIONS.BAD_REQUEST,
error401Description: ERROR_DESCRIPTIONS.UNAUTHORIZED,
error403Description: ERROR_DESCRIPTIONS.FORBIDDEN,
error404Description: ERROR_DESCRIPTIONS.NOT_FOUND,
error429Description: ERROR_DESCRIPTIONS.RATE_LIMIT_EXCEEDED,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR
})
async hello() {
return 'Hello World';
}
}

Using with DTO

import { ApiProperty } from '@nestjs/swagger';

export class UserDto {
@ApiProperty()
id: number;

@ApiProperty()
name: string;

@ApiProperty()
email: string;
}

@Controller('users')
export class UsersController {
@Get(':id')
@SwaggerDocumentation({
endpointDescription: 'Get user by ID',
endpointSummary: 'Get user',
responseDto: UserDto,
error404Description: ERROR_DESCRIPTIONS.NOT_FOUND,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR
})
async getUserById(@Param('id') id: number) {
// user retrieval logic
}
}

Working with Arrays

@Controller('users')
export class UsersController {
@Get()
@SwaggerDocumentation({
endpointDescription: 'Get list of all users',
endpointSummary: 'List users',
responseDto: UserDto,
isArray: true,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR
})
async getAllUsers() {
// user list retrieval logic
}
}

Paginated Responses

@Controller('users')
export class UsersController {
@Get()
@SwaggerDocumentation({
endpointDescription: 'Get paginated list of users',
endpointSummary: 'Paginated user list',
responseDto: UserDto,
isPaginated: true,
error400Description: ERROR_DESCRIPTIONS.BAD_REQUEST,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR
})
async getPaginatedUsers(@Query() query: PaginationDto) {
// pagination logic
}
}

Paginated Response Structure

When using isPaginated: true, the response is automatically wrapped in the structure:

{
data: T[], // array of objects of the specified DTO
totalCount: number, // total number of records
offset: number, // offset
limit: number // limit of records per page
}

Best Practices

  1. Use consistent error descriptions: Leverage the pre-configured ERROR_DESCRIPTIONS for consistency across your API.

  2. Provide meaningful descriptions: Write clear and descriptive endpoint descriptions that help API consumers understand the purpose and behavior.

  3. Use DTOs for responses: Always define DTOs for your responses to ensure proper schema generation in Swagger.

  4. Handle all relevant errors: Document all possible error scenarios that your endpoint might encounter.

  5. Use pagination for large datasets: When returning potentially large datasets, use the isPaginated option to provide a consistent pagination structure.