NestJS-根据一个属性有条件地验证正文 [英] NestJS - Validating body conditionally, based on one property

查看:224
本文介绍了NestJS-根据一个属性有条件地验证正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种使用DTO(使用出色的class-validatorclass-transformer库)验证主体的好方法.即使是嵌套结构,它也确实能很好地工作,但就我而言,我希望基于某些条件具有body属性.

I'm trying to find a nice way to validate a body using DTO (using the brilliant class-validator and class-transformer libraries). It works really well, even for nested structures but in my case I'd like to have the body property based on some conditions.

可能会帮助您理解的示例:

Example that will probably help to understand:

让我们想象我的身体应该总是有selectedCategory. 根据该字段,内容可以来自包含prop1的类别1,也可以来自包含prop2的类别2.

Let's imagine my body should always have selectedCategory. Based on that field, the content could either be from category 1, which contains prop1 OR from category 2, which contains prop2.

我不想为他们两个都使用null,我真的想必须定义prop1或基于selectedCategoryprop2.

I do not want to allow a null for both of them, I really want to have to either have prop1 defined or prop2 based on the selectedCategory.

我认为我可以使用管道,但是如何指定要使用的正确DTO?

I think that I could use a pipe, but then how can I specify the correct DTO to use?

我建立了一个具有所有常用属性的基"类,以及从其继承的其他几个类.

I've built a "base" class with all the common properties and few other classes that inherit from it.

我可以基于属性selectedCategory手动实例化管道,这是理想的选择,但我不知道要作为管道的第二个参数(元数据)传递什么.

I could instantiate the pipe manually based on the property selectedCategory, that'd be ideal but I have no clue what to pass as a second argument of the pipe (metadata).

感谢您的帮助.

推荐答案

您是否尝试过使用? 您不必创建多个DTO,而只需创建一个DTO.每个属性都分配给一个或多个组:

Have you tried using groups? Instead of having multiple DTOs, you just create one DTO. Every property is assigned to one or multiple groups:

@Min(12, {groups: ['registration', 'update']})
age: number;
@Length(2, 20, {groups: ['registration']})
name: string;

然后您可以有条件地将组传递给类转换器/验证器:

You can then conditionally pass the groups to class transformer / validator:

@Injectable()
export class ConditionalValidationPipe implements PipeTransform {
  async transform(entity: any, metadata: ArgumentMetadata) {
    // Dynamically determine the groups
    const groups = [];
    if (entity.selectedCategory === 1) {
      groups.push('registration');
    }

    // Transform to class with groups
    const entityClass = plainToClass(EntityDto, entity, { groups })

    // Validate with groups
    const errors = await validate(entityClass, { groups });
    if (errors.length > 0) {
      throw this.createError(errors);
    }
    return entityClass;
  }
}

这篇关于NestJS-根据一个属性有条件地验证正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆