Skip to main content

@globalart/nestjs-swagger

Streamline OpenAPI documentation generation with intuitive decorators and pre-configured error descriptions.

Installation

npm install @globalart/nestjs-swagger

Overview

The @globalart/nestjs-swagger package provides a unified SwaggerDocumentation decorator that simplifies endpoint documentation in NestJS applications. It eliminates boilerplate code while ensuring consistent API documentation across your application.

Key Features

  • Simple Decorator - Single decorator for complete endpoint documentation
  • Pre-configured Errors - Standard HTTP error descriptions included
  • Response Types - Support for arrays, pagination, and custom DTOs
  • Type Safety - Full TypeScript support with IntelliSense

Quick Start

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

@Controller("users")
export class UsersController {
@Get()
@SwaggerDocumentation({
endpointDescription: "Retrieve all users from the system",
endpointSummary: "Get users",
error401Description: ERROR_DESCRIPTIONS.UNAUTHORIZED,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR,
})
async getAllUsers() {
return [];
}
}

API Reference

SwaggerDocumentation Options

ParameterTypeRequiredDescription
endpointSummarystringYesBrief endpoint summary
endpointDescriptionstringNoDetailed endpoint description
operationIdstringNoUnique operation identifier
responseDtoFunctionNoResponse DTO class
isArraybooleanNoResponse is an array
isPaginatedbooleanNoResponse is paginated
deprecatedbooleanNoMark endpoint as deprecated
error400DescriptionstringNo400 Bad Request error description
error401DescriptionstringNo401 Unauthorized error description
error403DescriptionstringNo403 Forbidden error description
error404DescriptionstringNo404 Not Found error description
error409DescriptionstringNo409 Conflict error description
error422DescriptionstringNo422 Unprocessable Entity error description
error429DescriptionstringNo429 Too Many Requests error description
error500DescriptionstringNo500 Internal Server Error description
error503DescriptionstringNo503 Service Unavailable error description

ERROR_DESCRIPTIONS

Pre-configured error descriptions object:

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: "Returns a greeting message",
endpointSummary: "Get greeting",
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR,
})
async hello() {
return { message: "Hello World" };
}
}

Response DTOs

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

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

@ApiProperty({ example: "John Doe" })
name: string;

@ApiProperty({ example: "john@example.com" })
email: string;
}

@Controller("users")
export class UsersController {
@Get(":id")
@SwaggerDocumentation({
endpointDescription: "Retrieve user by unique identifier",
endpointSummary: "Get user by ID",
responseDto: UserDto,
error404Description: ERROR_DESCRIPTIONS.NOT_FOUND,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR,
})
async getUserById(@Param("id") id: number): Promise<UserDto> {
return this.userService.findById(id);
}
}

Array Responses

@Controller("users")
export class UsersController {
@Get()
@SwaggerDocumentation({
endpointDescription: "Retrieve all users in the system",
endpointSummary: "List all users",
responseDto: UserDto,
isArray: true,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR,
})
async getAllUsers(): Promise<UserDto[]> {
return this.userService.findAll();
}
}

Paginated Responses

@Controller("users")
export class UsersController {
@Get()
@SwaggerDocumentation({
endpointDescription: "Retrieve users with pagination support",
endpointSummary: "Get paginated users",
responseDto: UserDto,
isPaginated: true,
error400Description: ERROR_DESCRIPTIONS.BAD_REQUEST,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR,
})
async getPaginatedUsers(
@Query() query: PaginationDto
): Promise<PaginatedResponse<UserDto>> {
return this.userService.findPaginated(query);
}
}

Paginated Response Structure

When using isPaginated: true, the response is automatically wrapped in the PaginatedResponseDto 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
}

The PaginatedResponseDto class is automatically included in the Swagger schema when using isPaginated: true.

Using operationId

@Get(":id")
@SwaggerDocumentation({
endpointDescription: "Retrieve user by unique identifier",
endpointSummary: "Get user by ID",
operationId: "getUserById",
responseDto: UserDto,
error404Description: ERROR_DESCRIPTIONS.NOT_FOUND,
})
async getUserById(@Param("id") id: number): Promise<UserDto> {
return this.userService.findById(id);
}

Deprecated Endpoints

@Get("old-endpoint")
@SwaggerDocumentation({
endpointDescription: "This endpoint is deprecated, use /new-endpoint instead",
endpointSummary: "Deprecated endpoint",
deprecated: true,
error500Description: ERROR_DESCRIPTIONS.INTERNAL_SERVER_ERROR,
})
async oldEndpoint() {
return { message: "Use /new-endpoint" };
}

Best Practices

  • Consistent Errors - Use ERROR_DESCRIPTIONS for standardized error messages
  • Clear Descriptions - Write descriptive summaries and detailed descriptions
  • Type Safety - Always define response DTOs with proper typing
  • Relevant Errors - Document only the errors your endpoint actually returns
  • Pagination - Use isPaginated for endpoints returning large datasets
  • Operation IDs - Provide unique operationId for better API client generation