gpt4 book ai didi

typescript - Swagger 的 bool 值作为字符串而不是 NestJS 中的 bool 值发送

转载 作者:行者123 更新时间:2023-12-05 06:05:04 24 4
gpt4 key购买 nike

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

我已将字段的值设置为 Dto 中的 bool 值。

它正在与 Postman 一起发送一个 bool 值,而不是与作为字符串发送的 Swagger 一起工作......

这是我使用 CreateIssueDto

的 Controller
/**
* 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);
}

这是我的带有 Swagger 装饰器的 CreateIssueDto

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;
}

我添加了两个日志来打印 Controller 中的差异

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

最佳答案

使用'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;
///

关于typescript - Swagger 的 bool 值作为字符串而不是 NestJS 中的 bool 值发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66093415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com