Skip to content

Nest 使用 Swagger

入门

安装

bash

pnpm install --save @nestjs/swagger

增加配置

  • 修改 main.ts
ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
// 增加Swagger文档
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
// 改变端口 增加跨域
async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  /* 增加Swagger文档开始 */
  const config = new DocumentBuilder()
    .setTitle("Test example")
    .setDescription("The cats API description")
    .setVersion("1.0")
    .addTag("test")
    .build();
  // 创建指定的文档目录
  const document = SwaggerModule.createDocument(app, config);
  // 指定接口文档访问路径 http://localhost:5000/docall#/
  SwaggerModule.setup("docall", app, document);
  /* 增加Swagger文档结束 */
  await app.listen(process.env.PORT ?? 5000);
}
bootstrap();

参数

ApiOperation

  • 接口描述
ts
 @ApiOperation({ summary: '测试aaa', description: 'aaa描述' })

ApiQuery

  • 接口参数描述, 有几个就写几个
ts
  @ApiQuery({
    name: 'a1',
    type: String,
    required: false,
    description: 'a1描述',
    example: '1111',
  })
  @ApiQuery({
    name: 'a2',
    type: Number,
    required: true,
    description: 'a2描述',
    example: 2222,
  })

ApiParam

  • 接口参数描述, 有几个就写几个
ts
  @ApiParam({
    name: 'id',
    type: String,
    required: false,
    description: 'id描述',
    example: '222',
  })

ApiResponse

  • 代码
ts
  @ApiResponse({ status: HttpStatus.OK, description: 'aaa 成功', type: String })
  • 如图

汇总

ts
import { ApiOperation, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger';
  /* ------ 测试swagger文档   */
  /* 接口描述 */
  @ApiOperation({ summary: '测试aaa', description: 'aaa描述' })
  /* 接口参数描述 */
  @ApiQuery({
    name: 'a1',
    type: String,
    required: false,
    description: 'a1描述',
    example: '1111',
  })
  @ApiQuery({
    name: 'a2',
    type: Number,
    required: true,
    description: 'a2描述',
    example: 2222,
  })
  /* 接口返回值描述 */
  @ApiResponse({ status: HttpStatus.OK, description: 'aaa 成功', type: String })
  @Get('aaa')
  aaa(@Query('a1') a1, @Query('a2') a2) {
    return {
      data: {
        a1,
        a2,
      },
    };
  }

    /* 接口描述 */
  @ApiOperation({ summary: '测试bbb', description: 'bbb描述' })
  /* 接口参数描述 */
  @ApiParam({
    name: 'id',
    type: String,
    required: false,
    description: 'id描述',
    example: '222',
  })
  /* 接口返回值描述 */
  @ApiResponse({ status: HttpStatus.OK, description: 'bbb 成功', type: String })
  @Get('bbb/:id')
  bbb(@Param('id') id) {
    console.log(id);
    return {
      data: {
        id,
      },
    };
  }

复杂版本

  • 这里介绍的 就是 ApiBody

新建一个 DTO

  • ApiProperty 就是标识

  • ApiPropertyOptional 就是可填可不填

ts
// Ccc.dto
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty } from "class-validator";
export class CccDto {
  @ApiProperty({ name: "aaa", enum: ["a", "b", "c"] })
  @IsNotEmpty()
  aaa: string;

  @ApiPropertyOptional({ name: "bbb" })
  @IsNotEmpty()
  bbb: number;

  @ApiPropertyOptional({ name: "ccc", enum: [["g", "h", "i"]] })
  ccc: Array<string>;
}

新建一个 Ccc.entity.ts

  • 返回格式
ts
import { ApiProperty } from "@nestjs/swagger";
export class CccVo {
  @ApiProperty({ name: "aaa" })
  aaa: number;
  @ApiProperty({ name: "bbb" })
  bbb: number;
}

控制器

  • @ApiBody 里面 type 就是参数类型

  • @ApiResponse 里面 type 就是返回类型

ts

import {
  ApiBody,
  ApiOperation,
  ApiParam,
  ApiQuery,
  ApiResponse,
} from '@nestjs/swagger';
import { CccDto } from './dto/Ccc.dto';
import { CccVo } from './entities/Ccc.entity';

  @ApiOperation({ summary: '测试 ccc' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: 'ccc 成功',
    type: CccVo,
  })
  @ApiBody({
    type: CccDto,
  })
  @Post('ccc')
  async ccc(@Body() ccc: CccDto) {
    console.log(ccc);
    const cccVo = new CccVo();
    cccVo.aaa = 111;
    cccVo.bbb = 222;
    return {
      data: cccVo,
    };
  }

分类

ApiTags

  • 分类
ts
 @ApiTags('xxx2')

main.js 改造

ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
// 增加Swagger文档
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
// 改变端口 增加跨域
async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  /* 增加Swagger文档开始 */
  const config = new DocumentBuilder()
    .setTitle("Test example")
    .setDescription("The cats API description")
    .setVersion("1.0")
    .addTag("test")
    .addBasicAuth({
      type: "http",
      name: "basic",
      description: "用户名 + 密码",
    })
    .addCookieAuth("sid", {
      type: "apiKey",
      name: "cookie",
      description: "基于 cookie 的认证",
    })
    .addBearerAuth({
      type: "http",
      description: "基于 jwt 的认证",
      name: "bearer",
    })
    .build();
  // 增加文档指定的路径
  const document = SwaggerModule.createDocument(app, config);
  // 增加文档指定的路径 localhost:5000/docall
  SwaggerModule.setup("docall", app, document);
  /* 增加Swagger文档结束 */
  await app.listen(process.env.PORT ?? 5000);
}
bootstrap();

要是基于用户名密码

  • @ApiBasicAuth('basic')
ts
  @ApiBasicAuth('basic')
  @ApiOperation({ summary: '测试bbb', description: 'bbb描述' })
  /* 接口参数描述 */
  @ApiParam({
    name: 'id',
    type: String,
    required: false,
    description: 'id描述',
    example: '222',
  })
  /* 接口返回值描述 */
  @ApiResponse({ status: HttpStatus.OK, description: 'bbb 成功', type: String })
  @Get('bbb/:id')
  bbb(@Param('id') id) {
    console.log(id);
    return {
      data: {
        id,
      },
    };
  }
  • @ApiCookieAuth('cookie')
ts

  @ApiCookieAuth('cookie')
  @ApiOperation({ summary: '测试bbb', description: 'bbb描述' })
  /* 接口参数描述 */
  @ApiParam({
    name: 'id',
    type: String,
    required: false,
    description: 'id描述',
    example: '222',
  })
  /* 接口返回值描述 */
  @ApiResponse({ status: HttpStatus.OK, description: 'bbb 成功', type: String })
  @Get('bbb/:id')
  bbb(@Param('id') id) {
    console.log(id);
    return {
      data: {
        id,
      },
    };
  }

要是基于 jwt

  • @ApiBearerAuth('bearer')
ts

  @ApiBearerAuth('bearer')
  @ApiOperation({ summary: '测试bbb', description: 'bbb描述' })
  /* 接口参数描述 */
  @ApiParam({
    name: 'id',
    type: String,
    required: false,
    description: 'id描述',
    example: '222',
  })
  /* 接口返回值描述 */
  @ApiResponse({ status: HttpStatus.OK, description: 'bbb 成功', type: String })
  @Get('bbb/:id')
  bbb(@Param('id') id) {
    console.log(id);
    return {
      data: {
        id,
      },
    };
  }