【问题标题】:ValidationPipe in NestJS for a key-value pair objectNestJS 中的 ValidationPipe 用于键值对对象
【发布时间】:2021-02-23 05:14:55
【问题描述】:

我的 NestJS 控制器中有以下 DTO 对象作为请求正文的一部分:

export class UserPropertiesDto {
  [key: string]: boolean;
}

例如:{campaignActive: true, metadataEnabled: false}

这是一个键值对object,其中键是唯一的string,其值为boolean

我想应用class-validator 注释以确保正确的验证和转换,但它一直显示错误Decorators are not valid here

export class UserPropertiesDto {
  @IsOptional()
  @IsString() // `key` should be a string
  @MaxLength(20) // `key` should have no more than 20 characters
  @IsBoolean() // `value` has to be a `boolean`
  [key: string]: boolean;
}

您能否就最好的方法提出建议:

  • 确保保留所有对象的属性
  • 验证密钥以确保它是长度不超过 20 个字符的字符串
  • 验证值以确保它是boolean

【问题讨论】:

    标签: javascript typescript nestjs dto class-validator


    【解决方案1】:

    我建议您使用自定义验证器,我尝试为您做一些工作:

    iskeyvalue-validator.ts

       import { ValidatorConstraint, ValidatorConstraintInterface, 
     ValidationArguments } 
     from 
      "class-validator";
       import { Injectable } from '@nestjs/common';
    
      @Injectable()
      @ValidatorConstraint({ async: true })
      export class IsKeyValueValidate implements ValidatorConstraintInterface {
    
    
    
        async validate(colmunValue: Object, args: ValidationArguments) {
          try {
             if(this.isObject(colmunValue))
                  return false; 
    
           var isValidate = true;
           Object.keys(colmunValue)
           .forEach(function eachKey(key) {  
              if(key.length > 20 || typeof key  != "string" || typeof colmunValue[key] != 
            "boolean")
              {
                isValidate = false;
              }
            });
           return isValidate ;
    
    
            } catch (error) {
         console.log(error);
          } 
    
           }
    
    isObject(objValue) {
    return objValue && typeof objValue === 'object' && objValue.constructor === Object;
       }
    
        defaultMessage(args: ValidationArguments) { // here you can provide default error 
          message if validation failed
         const params = args.constraints[0];
      if (!params.message)
         return `the ${args.property} is not validate`;
      else
         return params.message;
       }
       }
    

    要实现它,您必须在模块提供程序中添加 IsKeyValueValidate :

    providers: [...,IsKeyValueValidate],
    

    在你的 Dto 中:

       @IsOptional()
      @Validate(IsKeyValueValidate, 
        [ { message:"Not valdiate!"}] )
      test: Object;
    

    【讨论】:

    • 谢谢!通过一些小的改动,它运行良好。不幸的是,这不允许严格的类型,但没关系。
    【解决方案2】:

    我建议关注custom validator。在验证期间,它可以访问已验证对象的所有属性和值。

    您可以将所有验证参数作为第二个参数传递并在验证器内部使用它们来控制流程。

    export class Post {
     
        @Validate(CustomTextLength, {
            keyType: String,
            maxLength: 20
           ...
        })
        title: string;
     
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 2022-11-17
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2021-06-11
      相关资源
      最近更新 更多