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,
                )
              );
            },
          },
        });
      };
    }
    
  • 相关阅读:
    mysql 每条数据增加随机数
    Linux 的VSFTP报错
    Linux 常见命令指南
    Python文件
    Python合并2个文件
    J2ME获取移动手机号码
    不同角度来理解面向对象的几个关键性概念
    打印字符串中第一个只出现一次的字符(C语言)
    ftp上传文件
    ftp上传到nas
  • 原文地址:https://www.cnblogs.com/ajanuw/p/11360723.html
Copyright © 2011-2022 走看看