๐Ÿ“ฆ Kimsoo0119 / nest-swagger-builder

Streamlined API documentation for NestJS applications

โ˜… 4 stars โ‘‚ 0 forks ๐Ÿ‘ 4 watching โš–๏ธ MIT License
builderdocumentnestjsswagger
๐Ÿ“ฅ Clone https://github.com/Kimsoo0119/nest-swagger-builder.git
HTTPS git clone https://github.com/Kimsoo0119/nest-swagger-builder.git
SSH git clone git@github.com:Kimsoo0119/nest-swagger-builder.git
CLI gh repo clone Kimsoo0119/nest-swagger-builder
Kimsoo0119 Kimsoo0119 Merge pull request #7 from Kimsoo0119/refactor/#6 da7c387 9 months ago ๐Ÿ“ History
๐Ÿ“‚ main View all commits โ†’
๐Ÿ“ examples
๐Ÿ“ src
๐Ÿ“„ .gitignore
๐Ÿ“„ .npmignore
๐Ÿ“„ LICENSE
๐Ÿ“„ package.json
๐Ÿ“„ README.ko.md
๐Ÿ“„ README.md
๐Ÿ“„ tsconfig.json
๐Ÿ“„ README.md

Nest Swagger Builder

npm version License: MIT

A utility library that makes Swagger documentation in NestJS functional, type-safe, and intuitive.

ํ•œ๊ตญ์–ด

โœจ Key Features

  • Reduce Boilerplate: Simplify complex Swagger decorator configurations
  • Type Safety: Generate API keys based on Nest controller methods
  • Readability & Consistency: Clear, declarative Swagger configurations
  • Improved Maintainability: Separate Swagger configs into dedicated files
  • Flexible Customization: Adjust response structure (statusKey, wrapperKey) as needed

๐Ÿ“ฆ Installation

npm install nest-swagger-builder

Required Peer Dependencies:

npm install @nestjs/common @nestjs/swagger class-transformer class-validator

โœ… Supported Versions

  • NestJS: ^8.0.0, ^9.0.0, ^10.0.0
  • Swagger: ^5.0.0 ~ ^8.0.0
  • class-validator: ^0.13.2 ~ ^0.14.0
  • class-transformer: ^0.5.1

๐Ÿš€ Quick Start

1. Create a Swagger Declaration File

// src/controllers/swagger/user.swagger.ts
import { HttpStatus } from "@nestjs/common";
import { ApiDecoratorBuilder, ApiOperator } from "nest-swagger-builder";
import { UserController } from "../user.controller";
import { UserDto } from "../../dto/user.dto";

export const ApiUser: ApiOperator<keyof UserController> = {
  GetUsers: (apiOperationOptions) =>
    new ApiDecoratorBuilder()
      .withOperation(apiOperationOptions)
      .withBearerAuth()
      .withBodyResponse(HttpStatus.OK, "ApiUser_GetUsers", [UserDto])
      .build(),
};

2. Use in Your Controller

@ApiTags("users")
@Controller("users")
export class UserController {
  @ApiUser.GetUsers({ summary: "Get all users" })
  @Get()
  getUsers() {
    return this.users;
  }
}

๐Ÿงฉ Customizing Response Structure (New)

In professional environments, each team/service may return different JSON structures from their interceptors.

Examples:

// Service A
{ "statusCode": 200, "data": { ... } }

// Service B
{ "status": 200, "result": { ... } }

By default, nest-swagger-builder returns pure Swagger structure ({}). However, you can easily reflect customized response structures in Swagger in two ways:

โœ… Direct Configuration in Individual Responses

new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBodyResponse(HttpStatus.OK, "UserDetail", UserDto, {
    statusKey: "status",
    wrapperKey: "data",
  })
  .build();

โœ… Using a Common Configuration Builder

// src/config/custom-swagger-builder.ts
export const CustomSwaggerBuilder = new ApiDecoratorBuilder({
  statusKey: "status",
  wrapperKey: "data",
});

Usage example:

CustomSwaggerBuilder.withOperation(apiOperationOptions)
  .withBodyResponse(HttpStatus.OK, "UserDetail", UserDto)
  .build();

๐Ÿ“ API Response Patterns

Response with Status Code Only

new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBearerAuth()
  .withStatusResponse(HttpStatus.CREATED, "UserCreated", {
    statusKey: "statusCode",
  })
  .build();

Response with Data

new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBearerAuth()
  .withBodyResponse(HttpStatus.OK, "UserProfile", UserDto, {
    statusKey: "status",
    wrapperKey: "data",
  })
  .build();

Array Response

new ApiDecoratorBuilder()
  .withOperation({ summary: "Get all users" })
  .withBearerAuth()
  .withBodyResponse(HttpStatus.OK, "UsersList", [UserDto], {
    statusKey: "status",
    wrapperKey: "data",
  })
  .build();

Error Responses

new ApiDecoratorBuilder()
  .withOperation({ summary: "Delete user" })
  .withBearerAuth()
  .withStatusResponse(HttpStatus.NO_CONTENT, "UserDeleted")
  .withUnauthorizedResponse([
    {
      name: "InvalidToken",
      error: "Invalid Token",
      description: "The provided authentication token is invalid",
    },
  ])
  .withNotFoundResponse([
    {
      name: "UserNotFound",
      error: "User Not Found",
      description: "The user with the given ID was not found",
    },
  ])
  .build();

File Upload (Multipart Form Data)

// Single File Upload
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withFormDataRequest("ProfileImage", "image")
  .withBodyResponse(HttpStatus.CREATED, "ImageUploaded", ImageDto)
  .build();

// Multiple Files Upload
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withFormDataRequest("GalleryImages", "images", { isArray: true })
  .withBodyResponse(HttpStatus.CREATED, "ImagesUploaded", [ImageDto])
  .build();

Usage example in controller:

import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';

@ApiUser.UploadImageFile({ summary: "Upload single image" })
@UseInterceptors(FileInterceptor('image'))
@Post('upload')
uploadFile(@UploadedFile() file: Express.Multer.File) {
  return { filename: file.originalname, size: file.size };
}

๐Ÿ“š API Reference

ApiDecoratorBuilder

A class that creates Swagger decorators through method chaining.

Constructor

new ApiDecoratorBuilder(config?: ApiDecoratorBuilderConfig)

ParameterDescriptionType
configDefault response format configuration (optional)ApiDecoratorBuilderConfig

ApiDecoratorBuilderConfig

interface ApiDecoratorBuilderConfig {
  wrapperKey?: string | undefined; // Property name that wraps response data (e.g., "data")
  statusKey?: string | undefined; // Status code property name (e.g., "statusCode")
}

Key Methods

MethodDescriptionParameters
withOperationAdd API operation informationoptions: ApiOperationOptions
withBearerAuthAdd Bearer authenticationname?: string
withStatusResponseAdd response with status code onlystatus: number, key: string, options?: ResponseOptions
withBodyResponseAdd response with datastatus: number, key: string, type: Type \| Type[], options?: ResponseOptions
withFormDataRequestAdd file upload supportkey: string, fileFieldName: string, options?: Record<string, any>
withErrorResponsesAdd 400 error responseserrors: ApiErrorResponse[]
withUnauthorizedResponseAdd 401 error responseserrors: ApiErrorResponse[]
withForbiddenResponseAdd 403 error responseserrors: ApiErrorResponse[]
withNotFoundResponseAdd 404 error responseserrors: ApiErrorResponse[]
withDecoratorAdd custom decoratordecorator: MethodDecorator \| PropertyDecorator
buildCombine all decorators and return-

Interfaces

ResponseOptions

interface ResponseOptions {
  statusKey?: string; // Status code field name in the response
  wrapperKey?: string; // Data field name in the response
}

ApiOperator

type ApiOperator<M extends string> = {
  [key in Capitalize<M>]: (
    apiOperationOptions: Required<Pick<ApiOperationOptions, "summary">> & ApiOperationOptions
  ) => PropertyDecorator;
};

๐Ÿ” Examples

The repository includes an example NestJS application demonstrating how to use the library:

# Clone the repository
git clone https://github.com/Kimsoo0119/nest-swagger-builder.git

# Install dependencies in the main project
cd nest-swagger-builder
npm install
npm run build

# Run the example application
cd examples
npm install
npm run start:dev

# Access Swagger UI
Open http://localhost:3000/api in your browser

๐Ÿ“‹ License

This library is licensed under the MIT License - see the LICENSE file for details.