Swagger api 接口管理 使用总结

安装

yarn add @nestjs/swagger swagger-ui-express -D

配置

在main.ts引入并配置

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

//引入
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  
  //配置swagger
  const swaggerOptions = new DocumentBuilder()
    .setTitle('nestjs-api-文档')  //文档标题
    .setDescription('nestjs-api-说明')  //文档描述
    .setVersion('1.0')  //文档版本
    .addBasicAuth() //鉴权,可以输入token
    .build(); //创建
    
  //创建swagger
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  //启动swagger
  SwaggerModule.setup('doc', app, document); 访问路径为 localhost:8000/doc

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


swagger装饰器

@ApiTags('user')   设置模块接口的分类,不设置默认分配到default
@ApiOperation({ summary: '标题', description: '详细描述'})  单个接口描述

传参
@ApiQuery({ name: 'limit', required: true})    query参数
@ApiQuery({ name: 'role', enum: UserRole })    query参数
@ApiParam({ name: 'id' })      parma参数
@ApiBody({ type: UserCreateDTO, description: '输入用户名和密码' })   请求体

响应
@ApiResponse({
    status: 200,
    description: '成功返回200,失败返回400',
    type: UserCreateDTO,
})

验证
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;


在controller配置

user.controller.ts

import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Query,
  Param,
  Delete,
  HttpCode,
  HttpStatus,
  ParseIntPipe,
} from '@nestjs/common';
import {
  ApiOperation,
  ApiTags,
  ApiQuery,
  ApiBody,
  ApiResponse,
} from '@nestjs/swagger';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Controller('user')
@ApiTags('user')  设置分类
export class UserController {
  constructor(private readonly userService: UserService) { }

  @Post()
  @ApiOperation({ summary: '创建用户', description: '创建用户' })  该接口
  @HttpCode(HttpStatus.OK)
  async create(@Body() user: CreateUserDto) {
    return await this.userService.create(user);
  }

  @Get()
  @ApiOperation({ summary: '查找全部用户', description: '创建用户' })
  @ApiQuery({ name: 'limit', required: true })  请求参数
  @ApiQuery({ name: 'offset', required: true }) 请求参数
  async findAll(@Query() query) {
    console.log(query);
    const [data, count] = await this.userService.findAll(query);
    return { count, data };
  }

  @Get(':id')
  @ApiOperation({ summary: '根据ID查找用户' })
  async findOne(@Param('id', new ParseIntPipe()) id: number) {
    return await this.userService.findOne(id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新用户' })
  @ApiBody({ type: UpdateUserDto, description: '参数可选' })  请求体
  @ApiResponse({   响应示例
    status: 200,
    description: '成功返回200,失败返回400',
    type: UpdateUserDto,
  })
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() user: UpdateUserDto,
  ) {
    return await this.userService.update(id, user);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除用户' })
  async remove(@Param('id', new ParseIntPipe()) id: number) {
    return await this.userService.remove(id);
  }
}


编写dto

创建用列

import { IsNotEmpty, MinLength, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class CreateUserDto {
  @ApiProperty({ example: 'kitty', description: '用户名' })  添加这里即可
  @IsNotEmpty({ message: '用户名不能为空' })
  username: string;

  @ApiProperty({ example: '12345678', description: '密码' })
  @IsNotEmpty({ message: '密码不能为空' })
  @MinLength(6, {
    message: '密码长度不能小于6位',
  })
  @MaxLength(20, {
    message: '密码长度不能超过20位',
  })
  password: string;
}


更新用列

import {
  IsEnum,
  MinLength,
  MaxLength,
  IsOptional,
  ValidateIf,
  IsEmail,
  IsMobilePhone,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';

export class UpdateUserDto {
  @ApiProperty({ description: '用户名', example: 'kitty', required: false })  不是必选的
  @IsOptional()
  username: string;

  @ApiProperty({ description: '密码', example: '12345678', required: false })
  @IsOptional()
  @MinLength(6, {
    message: '密码长度不能小于6位',
  })
  @MaxLength(20, {
    message: '密码长度不能超过20位',
  })
  password: string;

  @ApiProperty({
    description: '邮箱',
    example: 'llovenest@163.com',
    required: false,
  })
  @IsOptional()
  @IsEmail({}, { message: '邮箱格式错误' })
  @ValidateIf((o) => o.username === 'admin')
  email: string;

  @ApiProperty({
    description: '手机号码',
    example: '13866668888',
    required: false,
  })
  @IsOptional()
  @IsMobilePhone('zh-CN', {}, { message: '手机号码格式错误' })
  mobile: string;

  @ApiProperty({
    description: '性别',
    example: 'female',
    required: false,
    enum: ['male', 'female'],
  })
  @IsOptional()
  @IsEnum(['male', 'female'], {
    message: 'gender只能传入字符串male或female',
  })
  gender: string;

  @ApiProperty({
    description: '状态',
    example: 1,
    required: false,
    enum: [0, 1],
  })
  @IsOptional()
  @IsEnum(
    { 禁用: 0, 可用: 1 },
    {
      message: 'status只能传入数字0或1',
    },
  )
  @Type(() => Number)
  status: number;
}


测试接口 界面调试

接口调试截图

接口参数调试截图

posted @ 2021-12-28 17:08  boygdm  阅读(350)  评论(0编辑  收藏  举报