我正在尝试为 Typestack 类验证器创建一个新约束。“IsUnique”约束将实体作为类型,它的列作为参数来检查该列是否在数据库中不存在并且是唯一的。
我已经尝试了下面的代码,但不知何故我无法通过 registerDecorator 中的验证器键将类型传递给“IsUniqueConstraint”。因为,我是 Typescript 的新手,所以我不太了解它的概念。
有人可以帮我知道我们该怎么做吗?
is-unique.constraint.ts
import { registerDecorator, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, ValidationOptions } from 'class-validator';
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
@ValidatorConstraint({ name: 'isUnique', async: true })
@Injectable()
export class IsUniqueConstraint<T> implements ValidatorConstraintInterface {
constructor(private readonly repository: Repository<T>) { }
async validate(value: string, args: ValidationArguments) {
const [column] = args.constraints;
const result = await this.repository.findOne({ where: { [column]: value } });
if (result) {
return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
return `"${args.value}" already exists for ${args.constraints[0]}`;
}
}
export function IsUnique<T>(column: string, validationOptions?: ValidationOptions) {
return (object: object, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [column],
validator: IsUniqueConstraint,
});
};
}
用户.dto.ts
import { IsNotEmpty } from 'class-validator';
import { IsUnique } from './../shared/constraints/is-unique.constraint';
import { User } from './user.entity';
export class CreateUserDto {
@IsNotEmpty()
@IsUnique<User>('username')
readonly username: string;
}
MMMHUHU
心有法竹
相关分类