@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
| Parameter | Type | Required | Description |
|---|---|---|---|
endpointSummary | string | Yes | Brief endpoint summary |
endpointDescription | string | No | Detailed endpoint description |
operationId | string | No | Unique operation identifier |
responseDto | Function | No | Response DTO class |
isArray | boolean | No | Response is an array |
isPaginated | boolean | No | Response is paginated |
deprecated | boolean | No | Mark endpoint as deprecated |
error400Description | string | No | 400 Bad Request error description |
error401Description | string | No | 401 Unauthorized error description |
error403Description | string | No | 403 Forbidden error description |
error404Description | string | No | 404 Not Found error description |
error409Description | string | No | 409 Conflict error description |
error422Description | string | No | 422 Unprocessable Entity error description |
error429Description | string | No | 429 Too Many Requests error description |
error500Description | string | No | 500 Internal Server Error description |
error503Description | string | No | 503 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_DESCRIPTIONSfor 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
isPaginatedfor endpoints returning large datasets - Operation IDs - Provide unique
operationIdfor better API client generation