当body包含布尔值时,后端(nestjs)将其解析为字符串有一个装饰器来验证参数是否具有布尔值作为字符串
@IsBooleanString()
myVariable:boolean;
在你的情况下你可以做什么:
您可以将您的身体值从布尔值转换为数字
From { "string": true } To { "string": 1 }
您可以使用额外的validate 装饰器,@IsNotIn(values: any[])
例如:
@IsString()
@IsNotIn(["FALSE", "TRUE"])
myVariable: string;
您可以创建自己的装饰器
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';
export function IsNotBoolean(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'IsNotBoolean',
target: object.constructor,
propertyName: propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
if(value.toUpperCase() == 'TRUE' || value.toUpperCase() == 'FALSE'){
return false
} else {
return true
}
},
},
});
};
}
在 DTO 上
import { IsString } from "class-validator";
import { IsNotBoolean } from "the path of your custom validate decorator"
export class TestDTO {
@IsString({myErrorKey:'My error message'})
@IsNotBoolean({the optional error message object})
string: string;
}
在控制器上
public testing(@Body(ValidationPipe) test: TestDTO): string {
return test.string;
}