【发布时间】:2021-01-25 10:30:42
【问题描述】:
我正在尝试验证一组 Id,为了验证我在 nestjs 项目中使用自定义验证器。我将回调函数中的 id 数组传递给我的服务类,以从数据库中查询 id 是否存在于表中并返回一个布尔值。每次我收到 boolean true 即使我传递了错误的 id。
这是自定义验证器中的验证函数
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, registerDecorator, ValidationOptions } from "class-validator";
import { DeviceService } from "../device/device.service";
import { Injectable } from "@nestjs/common";
@ValidatorConstraint({ async: true })
@Injectable()
export class DevicesArrayValidatorConstraint implements ValidatorConstraintInterface {
constructor(private deviceService: DeviceService) { }
async validate(devices: Array<number>, args: ValidationArguments) {
let result = devices.every(async (deviceId) => await this.deviceService.validateDevice(deviceId));
if(result){
return true;
}
else{
return false;
}
}
defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed
return "Here is an error";
}
}
export function ValidDevices(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: DevicesArrayValidatorConstraint
});
};
}
它来自服务类的功能
async validateDevice(deviceId: number) {
try {
let result = await this.deviceRepository.findOneOrFail(deviceId)
if(result){
console.log(`In try block,This is id ${ deviceId}`)
}
} catch (error) {
return false;
}
return true;
}
如果我传递devices: [1,4] 的数组,其中1 有效,4 无效。如果我 console.log() 返回值,我会得到一个双布尔结果。
附加控制台消息
【问题讨论】:
-
every不理解异步函数。它只是将返回的承诺视为真实值。 -
有什么办法解决?
-
if(result) { return true; } else { return false; }-result已经是一个布尔值,所以你可以简单地return result -
也这样做了,但总是收到 boolean true;
标签: javascript express nestjs typeorm class-validator