如果我想验证role
是用户发布到api的unique
是关系enterprise
的
@Injectable({ scope: Scope.REQUEST })
@ValidatorConstraint({ name: 'Ddd', async: true })
export class IsUnqiueForEnterpriseConstraint implements ValidatorConstraintInterface {
constructor(@Inject(REQUEST) private request: Request) {}
async validate(value: any, args: ValidationArguments) {
const { enterprise } = this.request.user as any
const { model } = args.constraints[0] as IParams;
if(!enterprise) return false;
if (!model) return false;
const repo = getManager().getRepository(model as ObjectType<any>);
const item = await repo.findOne({
[args.property]: value,
enterprise: { id: enterprise.id },
});
return !item;
}
defaultMessage(args: ValidationArguments) {
const { model } = args.constraints[0];
if (!model) {
return 'Model not been specified!';
}
return `${args.property} of ${model.name} must been unique!`;
}
}
export function IsUnqiueForEnterprise(params: IParams, validationOptions?: ValidationOptions) {
return (object: Record<string, any>, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [params],
validator: IsUnqiueForEnterpriseConstraint,
});
};
}
在main.ts
中
我将像以下那样容器类验证器
useContainer(app, { fallbackOnErrors: true });
和dto
@IsUnqiueForEnterprise({model: Role})
label!: string;
但是在约束request
是undefined
的情况下,我怎么能得到它?