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,
                )
              );
            },
          },
        });
      };
    }
    
  • 相关阅读:
    KMP算法精髓
    习题
    JavaScript function函数种类介绍
    街景地图 API
    电脑网卡
    框架的设计之IRepository还是IRepository<T>
    顺序线性表
    hdu4284之字典树
    pt-table-checksum
    C++中输入输出流及文件流操作笔记
  • 原文地址:https://www.cnblogs.com/ajanuw/p/11360723.html
Copyright © 2011-2022 走看看