zoukankan      html  css  js  c++  java
  • Nestjs 验证对象数组

    route

      @Patch(':id')
      patch(@Param('id') id: string, @Body() removeEssayDto: RemoveEssayDto) {
        return this.essaysService.patch(id, removeEssayDto);
      }
    

    dto

    import {
      IsNotEmpty,
      IsString,
      Contains,
      IsArray,
      ValidateNested,
      registerDecorator,
      ValidationOptions,
      ValidationArguments,
      IsDefined,
    } from 'class-validator';
    import { Type } from 'class-transformer';
    import { ApiModelProperty } from '@nestjs/swagger';
    
    export class RemoveEssayItemDto {
      @IsString()
      @IsNotEmpty()
      @ApiModelProperty({
        example: 'replace'
      })
      op: string;
    
      @IsString()
      @IsNotEmpty()
      @Contains('/')
      @ApiModelProperty({
        example: '/isDelete'
      })
      path: string;
    
      @IsDefined()
      @ApiModelProperty({
        required: false,
        example: 'false'
      })
      readonly value: any;
    }
    
    export class RemoveEssayDto {
      @IsNotEmpty()
      @IsArray()
      @ApiModelProperty({
        isArray: true,
        type: RemoveEssayItemDto,
      })
      @ValidateNested({ each: true })
      @IsNonPrimitiveArray()
      @Type(() => RemoveEssayItemDto)
      readonly patchs: RemoveEssayItemDto[];
    }
    
    export function IsNonPrimitiveArray(validationOptions?: ValidationOptions) {
      return (object: any, propertyName: string) => {
        registerDecorator({
          name: 'IsNonPrimitiveArray',
          target: object.constructor,
          propertyName,
          constraints: [],
          options: validationOptions,
          validator: {
            validate(value: any, args: ValidationArguments) {
              return (
                Array.isArray(value) &&
                value.reduce(
                  (acc, el) => acc && typeof el === 'object' && !Array.isArray(el),
                  true,
                )
              );
            },
          },
        });
      };
    }
    
  • 相关阅读:
    QT 十六进制字符串转化为十六进制编码
    C语言中函数有输出参数
    QT 字符串相等间距字符间增加字符
    CRC校验算法
    QT 环境下开发socketCan接口程序
    QT 十六进制整数变为字符串自动补0 && 十进制补零
    C语言函数返回数组
    JNI文件中命名类与JAVA文件中匹配
    mini6410-JNI-led
    gis 出现问题解决办法
  • 原文地址:https://www.cnblogs.com/ajanuw/p/11360723.html
Copyright © 2011-2022 走看看