Typescript 类验证程序自定义
嘿,伙计们,我有一个关于类验证器的问题。我已经编写了一个自定义类验证器exists,它检查具有属性的对象是否已经存在。 这是密码Typescript 类验证程序自定义,typescript,boolean,class-validator,Typescript,Boolean,Class Validator,嘿,伙计们,我有一个关于类验证器的问题。我已经编写了一个自定义类验证器exists,它检查具有属性的对象是否已经存在。 这是密码 @Injectable() @ValidatorConstraint({ async: true }) export class ExistsConstraint implements ValidatorConstraintInterface { constructor(@InjectConnection() private connection: Connect
@Injectable()
@ValidatorConstraint({ async: true })
export class ExistsConstraint implements ValidatorConstraintInterface {
constructor(@InjectConnection() private connection: Connection) {
}
defaultMessage(validationArguments?: ValidationArguments): string {
return '';
}
validate(value: any, validationArguments?: ValidationArguments): Promise<boolean> | boolean {
const entity = validationArguments.constraints[0];
const isId = validationArguments.constraints[1];
const property = validationArguments.property;
const exists = (result) => {
return !!result;
};
const repository: Repository<any> = this.connection.getRepository(entity);
return isId ? repository.findOne(value).then(exists) : repository.findOne({[property]: value}).then(exists);
}
}
export function Exists(entity, isObjectId?, validationOptions?: ValidationOptions) {
return function(object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [entity, isObjectId],
validator: ExistsConstraint,
});
};
}
但它也可以有不同的用法,我想,比如在尝试创建用户时,检查带有此类电子邮件的用户是否已经注册。
这就是问题所在:当具有属性的实体存在时,这个验证器返回true,我(在某些情况下)如何获得它!验证器。我的意思是,当实体不存在时,它将返回true?有没有一种方法可以通过这个验证器实现这一点?不幸的是,没有这种方法,这就是为什么在他们的文档中,每个案例都有两个decorator
@Equals
@记事本
@空空如也
@不空虚
@伊辛
@不在
等等
您可以做的是共享代码库,例如,在相反的情况下使用这个类作为基类,并简单地从super方法反转它的结果
export class FindByIdParam{
@IsString()
@IsMongoId()
@Exists(User,true)
id: string;
}