nestjsclass-validatorclass-transformer

Nestjs class validator does not process object


There is dto CreateOrder

When validateIf is triggered for the address object, it throws an error and I can’t understand why. If I remove validateIf, the error still remains; if I remove ValidateNested, the error disappears, since the object is not validated

  @IsOptional()
  @IsString()
  deliveryType: string;

  @IsObject()
  @ValidateIf((o) => o.deliveryType !== 'FREE')
  @ValidateNested()
  @Type(() => CreateOrderAddressDto)
  address: CreateOrderAddressDto;

ошибка

TypeError: Cannot convert undefined or null to object
    at Function.values (<anonymous>)
    at /usr/src/app/dist/common/validations/custom-validation.pipe.js:33:40
    at Array.reduce (<anonymous>)
    at CustomValidationPipe.transform (/usr/src/app/dist/common/validations/custom-validation.pipe.js:28:45)

class CreateOrderAddressDto

import { ApiProperty } from '@nestjs/swagger';
import {
  IsBoolean,
  IsNotEmpty,
  IsNumber,
  IsOptional,
  IsString,
  Length,
} from 'class-validator';

export class CreateOrderAddressDto {        
  @IsString()
  @IsNotEmpty()
  formatted: string;

  @IsString()
  @IsNotEmpty()
  street: string;

  @IsString()
  @IsNotEmpty()
  postalCode: string;

  @IsOptional()
  @IsString()
  @IsNotEmpty()
  apartment: string;

  @IsOptional()
  @IsString()
  floor: string;
}

{
  "client": {
    "name": "User User",
    "phone": "+98023323323"
  },
  "order": [{
    "shopId": 5,
    "payment": "cash",
    "delivery": "",
    "deliveryId": 2,
    "deliveryType": "DISTANCE",
    "deliveryDate": "2023-12-21T13:37:25.788Z",
    "deliveryTime": "09:00 - 09:30 утрa",
    "isOtherRecipient": false,
    "shippingUsername": "",
    "shippingPhone": "",
    "comment": "",
    "address": {
      "countryCode": "",
      "country": "",
      "city": "",
      "formatted": "",
      "street": "",
      "postalCode": "",
      "apartment": "",
      "intercom": "",
      "entrance": "",
      "floor": "",
      "lat": 0,
      "lng": 0
    }
  }]
}

my request payload

{
  "client": {
    "name": "User User",
    "phone": "+98023323323"
  },
  "order": [{
    "shopId": 5,
    "payment": "cash",
    "delivery": "",
    "deliveryId": 2,
    "deliveryType": "DISTANCE",
    "deliveryDate": "2023-12-21T13:37:25.788Z",
    "deliveryTime": "09:00 - 09:30 утрa",
    "isOtherRecipient": false,
    "shippingUsername": "",
    "shippingPhone": "",
    "comment": "",
    "address": {
      "countryCode": "",
      "country": "",
      "city": "",
      "formatted": "",
      "street": "",
      "postalCode": "",
      "apartment": "",
      "intercom": "",
      "entrance": "",
      "floor": "",
      "lat": 0,
      "lng": 0
    }
  }]
}

Solution

  • Sorry)) I forgot about the CustomValidationPipe class) The problem was in this class