nest使用swagger文档

211 阅读1分钟

OpenAPI(Swagger)规范是一种用于描述 RESTful API 的强大定义格式。 Nest 提供了一个专用模块来使用它。

安装

npm安装

npm install --save @nestjs/swagger swagger-ui-express

yarn 安装

yarn add @nestjs/swagger swagger-ui-express

引入

使用 SwaggerModule 类初始化 Swagger main.ts

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

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

  const options = new DocumentBuilder()
    .setTitle('User example')//标题
    .setDescription('The user API description')//文档描述
    .setVersion('4.0')//文档版本号
    .addTag('user')//标签名
    .build();
  const document = SwaggerModule.createDocument(
  	app,//应用程序实例
  	options//Swagger 选项对象
  );
  
  SwaggerModule.setup(
    'api',//api就是Swagger UI 的挂载路径
    app,//应用程序实例
    document//上面已经实例化的文档对象
  );

  await app.listen(3000);
}
bootstrap();

访问文档

应用程序运行时,打开浏览器并导航到 http://localhost:3000/api 。 你应该可以看到 Swagger UI 在这里插入图片描述

路由参数

SwaggerModule 在路由处理程序中查找所有使用的 @Body() , @Query() 和 @Param() 装饰器来生成 API 文档。该模块利用反射创建相应的模型定义

	
  @Post('add')// [Post请求] 路由:/user/add
  async findOne(@Body() param: User) {

      // 使用userService的add方法
      return this.userService.add(param)
  }

基于 User,将创建模块定义: 在这里插入图片描述

用@ApiProperty() 装饰器对其进行注释后

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';

@Entity()
export class User {
  @ApiProperty()
  @PrimaryGeneratedColumn()
  id: number;

  @ApiProperty({
    description: '名称',
    type: String
  })
  @Column()
  name: string;

  @ApiProperty({
    description: '状态',
    default: '1'
  })
  @Column({ default: '1' })
  status: string;

}

在这里插入图片描述