nestjs中使用小技巧

1.当有多个Query参数时可以定义成对象, ApiQuery的type值设定为该对象类型。例如:

// xxx.dto.ts
export class QueryUserDto {
  @ApiProperty({ description: '用户姓名' })
  @IsString()
  @IsOptional()
  name: string

  @ApiProperty({ description: 'limit, 默认为20' })
  @Type(() => Number)
  @IsNumber()
  @IsOptional()
  @Min(10)
  @Max(200)
  limit: number

  @ApiProperty({ description: 'offset, 默认为0' })
  @Type(() => Number)
  @IsNumber()
  @IsOptional()
  @Min(0)
  offset: number
}

// xxx.controller.ts
@ApiQuery({
    type: QueryUserDto
  })
  1. 好像Query参数不会自动转类型(我的项目中是这样的,不知道是设定问题还是BUG,需要手动添加Pipe,当Query参数使用Class定义时很不方便)这时我们可以自己定义一个Pipe,使用plainToClass将对象转成对应的类型。
// parse-query.pipe.ts
import type { ArgumentMetadata, PipeTransform } from '@nestjs/common'
import { Injectable } from '@nestjs/common'
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
import { ClassConstructor, plainToClass } from 'class-transformer'

@Injectable()
export class ParseQueryPipe implements PipeTransform<string> {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    const obj = plainToClass(metatype as ClassConstructor<any>, value)
    console.log('metatype ---> ', metatype)
    return obj
  }
}

使用方法:

@Query(new ParseQueryPipe()) queryUserDto: QueryUserDto
  1. controller返回值统一使用固定的结构时,生成swagger文档可以参考https://docs.nestjs.com/openapi/operations#advanced-generic-apiresponse,使用泛型的方式。
class BaseResponse<T> {
   data: T
   status: number
    message: string
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容