3-2:迁移至fastify,使用swagger

4 阅读1分钟

回忆一下之前是如何使用swagger的。

配置swagger

1.安装swagger

执行命令pnpm add @nestjs/swagger

2.配置

nest-cli中添加配置项:

{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true,
    "plugins": ["@nestjs/swagger"]
  }
}

3.修改导入

不要忘记将update.dto中的导入修改,将原本的import { PartialType } from '@nestjs/mapped-types'; 修改为:import { PartialType } from '@nestjs/swagger';

4.修改main.ts,初始化swagger

写入下面的配置,并根据自己的项目名称进行修改

const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, documentFactory);

安装静态文件托管

如果直接访问http://localhost:3000/api,会发现访问失败。这是因为express自带静态文件托管服务,但是fastify并没有,因此需要安装一个依赖fastify-static。pnpm add @fastify/static