【问题标题】:Boolean in swagger sent as string instead of boolean in NestJS大摇大摆的布尔值作为字符串而不是 NestJS 中的布尔值发送
【发布时间】:2021-05-11 13:47:04
【问题描述】:

我不明白为什么 Swagger 将我的布尔值作为字符串而不是布尔值发送。

我已在 Dto 中将该字段的值设置为布尔值。

它与 Postman 一起发送布尔值,但不适用于 Swagger,它作为字符串发送...

这是我使用CreateIssueDto的控制器

/**
   * Create an issue
   * @param image
   * @param issue
   */
  @ApiBearerAuth()
  @ApiOperation({ description: 'Create an issue' })
  @UseInterceptors(FileInterceptor('image'))
  @ApiConsumes('multipart/form-data')
  @Roles(Role.HeadOfPole, Role.Corrector, Role.Editor)
  @Post('create')
  createIssue(@UploadedFile() image, @Body() issue: CreateIssueDto) {
    image ? (issue.image = image.path) : null;
    return this.issuesService.createIssue(issue);
  }

这是我的 CreateIssueDto 和 Swagger 装饰器

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

export class CreateIssueDto {
  @ApiProperty()
  @IsNotEmpty()
  userId: number;

  @ApiProperty()
  @IsNotEmpty()
  description: string;

  @ApiPropertyOptional()
  isCritical: boolean;

  @ApiPropertyOptional({ type: 'string', format: 'binary' })
  image: string;
}

我添加了两个日志来打印控制器中的差异

console.log(issue);
console.log(issue.isCritical, typeof issue.isCritical);

所以这里是使用 Swagger 的 isCritial 的对象和类型

[Object: null prototype] {
  userId: '1',
  description: 'There is a problem',
  isCritical: 'true'
}
true string

这里是使用 Postman 的 isCritial 的对象和类型

{ userId: 1, description: 'There is a problem', isCritical: true }
true boolean

【问题讨论】:

    标签: typescript swagger postman nestjs


    【解决方案1】:

    使用'class-transformer'中的Transform函数来修复它,有两种方法:

    第一种,直接在dto文件中转换值:

    @Transform(value => {
      return value === 'true' || value === true || value === 1 || value === '1'
    })
    isCritical: boolean;
    

    强烈推荐的第二种方法是在 decorators 存储库下导出 ToBoolean 函数,并在任何地方使用它:

     export function ToBoolean(): (target: any, key: string) => void {
        return Transform((value: any) => value === 'true' || value === true || value === 1 || value === '1');
    }
    

    CreateIssueDto 文件:

    export class CreateIssueDto {
      ///
      @ApiPropertyOptional()
      @ToBoolean()
      isCritical: boolean;
      ///
    

    【讨论】:

    • 我不得不在函数包装器“export function ToBoolean(): (target: any, key: string) => void { return Transform(({ value, . ..props }: any) => { return ( value === 'true' || value === true || value === 1 || value === '1' ); }); }"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2019-08-17
    相关资源
    最近更新 更多