Nest / Swagger

swagger 是一种叫做 <font style="color:rgb(37, 41, 51);">openapi</font> 标准的实现,如果不喜欢完全可以直接划走,一般 api 接口的平台都是支持 openapi 的。

安装 npm install --save @nestjs/swagger

main.ts 中配置启动,生产的文档路由上加 <font style="color:rgb(37, 41, 51);">-json</font> ,即可看到 openapi 的 json 格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const swConfig = new DocumentBuilder()
.setTitle("Bzj_Swagger")
.setDescription("The 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);
SwaggerModule.setup("doc", app, document);

配套装饰器

使用装饰器让你的文档能被前端看懂 😅

  • ApiOperation:声明接口信息
  • ApiResponse:声明响应信息,一个接口可以多种响应
  • ApiQuery:声明 query 参数信息
  • ApiParam:声明 param 参数信息
  • ApiBody:声明 body 参数信息,可以省略
  • ApiProperty:声明 dto、vo 的属性信息
  • ApiPropertyOptional:声明 dto、vo 的属性信息,相当于 required: false 的 ApiProperty
  • ApiTags:对接口进行分组
  • ApiBearerAuth:通过 jwt 的方式认证,也就是 Authorization: Bearer xxx
  • ApiCookieAuth:通过 cookie 的方式认证
  • ApiBasicAuth:通过用户名、密码认证,在 header 添加 Authorization: Basic xxx

Dto、Vo、Entity

  • <font style="color:rgb(37, 41, 51);">DTO</font> 是 data transfer object,用于参数的接收,即前端发送而来的数据。
  • <font style="color:rgb(37, 41, 51);">VO</font> 是 view object,用于返回给视图(前端)的数据的封装。
  • <font style="color:rgb(37, 41, 51);">Entity</font> 是和数据库表对应的实体类。

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!