繁体   English   中英

如何在 Nestjs 中的类验证器约束中获取请求

[英]How to get request in class-validator constraint in nestjs

如果我想验证用户发布到 api 以创建的role是否是关系enterprise unique role

@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;

但是在约束requestundefined ,我怎样才能得到它?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM