nestjs 配置swagger

读者来稿 · song-shao与 batype 的 AI 分身对话整理

·603 字 · 约 2 分钟#NestJS#Swagger

使用 Swagger 在 NestJS 中生成 API 文档是一种常见的做法,可以帮助开发者和用户了解 API 的使用方式和功能。结合你提供的代码片段,下面是如何在 NestJS 项目中使用 Swagger 的详细文档。

安装 Swagger#

首先,确保在你的 NestJS 项目中安装了必要的 Swagger 依赖:

npm install @nestjs/swagger swagger-ui-express

配置 Swagger#

在主模块(通常是 main.ts 或者你应用的入口文件)中进行 Swagger 的配置。根据你的代码片段,配置过程如下:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle(process.env.SWAGGER_TITLE as string)
    .setDescription(
      `<a href='${process.env.SWAGGER_URL}/api-json' target="_blank">api-json</a>`,
    )
    .setVersion('1.0')
    .addBearerAuth({ description: 'auth', type: 'http' })
    .build();

  const document = SwaggerModule.createDocument(app, config, {
    operationIdFactory: (_controllerKey: string, methodKey: string) => {
      const [one, ...other] = methodKey.split('');
      return `${one.toLocaleUpperCase()}${other.join('')}`;
    },
  });

  SwaggerModule.setup('api', app, document, {
    jsonDocumentUrl: 'api-json',
    yamlDocumentUrl: 'api-yaml',
    customSiteTitle: process.env.SWAGGER_TITLE,
    customfavIcon: process.env.SWAGGER_FAVICON,
    swaggerUiEnabled: process.env.SWAGGER_UI_ENABLED === 'true',
  });

  await app.listen(3000);
}

bootstrap();

主要配置解析#

  1. 设置基础信息

    • .setTitle(process.env.SWAGGER_TITLE): 设置 Swagger 文档的标题,通过环境变量 SWAGGER_TITLE 进行配置。
    • .setDescription(...): 设置 API 描述,其中包括一个指向 JSON 格式 API 文档的链接,URL 由环境变量 SWAGGER_URL 决定。
    • .setVersion('1.0'): 设置 API 文档的版本。
  2. 认证设置

    • .addBearerAuth(...): 为 API 文档添加 Bearer token 认证信息,适用于使用 JWT 等认证方式的 API。
  3. 生成文档

    • 使用 SwaggerModule.createDocument 实例化 Swagger 文档,operationIdFactory 用于生成操作 ID,其中格式化方法名为每个方法名的首字母大写。
  4. 设置 API 文档的路径和其他选项

    • SwaggerModule.setup(...) 用于配置 Swagger UI:
      • URL 地址为 /api
      • jsonDocumentUrlyamlDocumentUrl 提供 JSON 和 YAML 格式文档的路径。
      • customSiteTitlecustomfavIcon 可以自定义 Swagger 页面标题和图标。
      • swaggerUiEnabled 决定 Swagger UI 是否可用,通过环境变量 SWAGGER_UI_ENABLED 进行控制。

使用 Swagger#

为 Controller 添加 Swagger 装饰器:

在你的 Controller 中,通过装饰器来注释路由和参数:

   import { Controller, Get, Post, Body, Param } from '@nestjs/common';
   import { ApiTags, ApiOperation, ApiParam, ApiResponse, ApiBody } from '@nestjs/swagger';

   @ApiTags('cats')  // 带有标签的 API 分组
   @Controller('cats')
   export class CatsController {
     @Get()
     @ApiOperation({ summary: '获取所有猫' })
     @ApiResponse({ status: 200, description: '返回所有猫的数组' })
     findAll() {
       return 'This action returns all cats';
     }

     @Post()
     @ApiOperation({ summary: '创建新的猫' })
     @ApiBody({ description: '猫的信息' })
     create(@Body() createCatDto: any) {
       return 'This action adds a new cat';
     }

     @Get(':id')
     @ApiOperation({ summary: '获取指定ID的猫' })
     @ApiParam({ name: 'id', description: '猫的ID' })
     @ApiResponse({ status: 200, description: '返回指定ID的猫' })
     findOne(@Param('id') id: string) {
       return `This action returns a cat with id ${id}`;
     }
   }
  • @ApiTags() 用于将本控制器中的所有路由分组到同一个标签下。
  • @ApiOperation() 用于描述路由的功能。
  • @ApiParam() 描述路由参数。
  • @ApiBody() 用于描述 POST 请求的 body。
  • @ApiResponse() 用于描述可能的响应状态和说明。

借助这些配置,你可以很容易地设置和自定义你的 NestJS API 的 Swagger 文档。这有助于其他开发人员和团队成员理解和使用你的 API。

在你的 NestJS 应用启动后,你可以访问 http://localhost:3000/api 查看自动生成的 Swagger 文档。这将根据你在项目中定义的路由和控制器自动生成漂亮的交互式 API 文档。

确保在生产环境下妥善管理 Swagger 文档的可访问性,以免暴露过多的调试信息。

相关文章

  • nestjs 中 JWT 鉴权登录

    NestJS中实现JWT鉴权和登录的详细指南,包括安装依赖、创建模块、服务、策略和控制器,以及使用Guards保护路由。

  • nestjs 使用nodemailer 编写邮件发送模块服务

    NestJS邮件发送指南:使用Nodemailer和@nestjs-modules/mailer。安装必要包,创建邮件模块和服务,配置SMTP,发送邮件。确保SMTP配置正确,使用环境变量保护敏感信息。