我正在尝试编写一个自定义的验证装饰器,它将禁止用户在单个类别/子类别中创建具有相同标题的条目。为了做到这一点,我将使用class-validator库,并像这样编写一个装饰器:
@ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
@Injectable()
export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
constructor(
private readonly userService: UserService,
) {}
public async validate(val: any, args: ValidationArguments): Promise<boolean> {
return true;
}
public defaultMessage(args: ValidationArguments): string {
return `Entry with such title already exists in this folder`;
}
}
这样做的问题是,我将不得不进行一个相当复杂的数据库查询,以检查数据库中是否已经存在具有这样一个标题的条目。其中一个参数,我需要知道的显然是一个用户id,用户id可以从user jwt令牌中检索到,但是我如何在这个类中访问它?这就是我现在遇到的问题。
发布于 2020-06-18 21:01:38
您可以尝试将验证器设置为请求范围可注入( Request scoped,link on documentation)。
这种方法允许您将请求实例注入到验证器,并通过它访问用户。
简而言之,它看起来就像
import { REQUEST } from '@nestjs/core';
@ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
@Injectable({ scope: Scope.REQUEST })
export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
constructor(
private readonly userService: UserService,
@Inject(REQUEST) private request: Request
) {}
public async validate(val: any, args: ValidationArguments): Promise<boolean> {
return true;
}
public defaultMessage(args: ValidationArguments): string {
return `Entry with such title already exists in this folder`;
}
}
发布于 2020-06-17 13:38:01
我不知道你到底想要什么。但是为了方便起见,您可以使用这个模块nestjs-dbvalidator来检查colmun是唯一的还是存在的
https://stackoverflow.com/questions/62395333
复制