Vue3 + Nest 实现博客管理系统 后端篇(四):生成swagger接口文档

332 阅读1分钟

接口开发好之后需要一个接口文档以便前端,最主要的就是要报告是什么方式的请求,以及请求入参、接口名、字段的意思等等

安装swagger的包

pnpm install --save @nestjs/swagger

然后修改 main.ts

image.png

  const options = new DocumentBuilder()
    .setTitle('博客系统Swagger')
    .setDescription('博客系统文档')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('doc', app, document);

然后重启项目,在http://localhost:3000/doc 端口号是在main.ts 里面这只的端口号,就可以看到生成的swagger文档了

image.png 然后我们测试login接口

image.png 能够正常返回token,但是都没有 param 的描述和 response 的描述:

image.png 然后我们在user.controller.ts里面给注册接口添加 @ApiOperation 和 @ApiResponse 的装饰器。

image.png

image.png 然后我们修改user.controller.ts

image.png

  @ApiQuery({
    name: 'username',
    required: true,
    description: '用户名',
  })
  @ApiQuery({
    name: 'password',
    required: true,
    description: '密码',
  })

再次看下swagger

image.png

但是我们其他的接口查询都需要token,所以需要配置一下让swagger可以在请求里面添加token,修改main.ts

image.png

image.png 然后在swagger里面添加token

image.png image.png 然后再次查询数据能够勘察请求头的token以及数据正常返回

image.png