2

I'm working with NestJS and using class-validator to validate data. I have an array of objects in my DTO, but I need to ensure that empty objects (objects with no properties) are eliminated from the array. I've used class-transformer it to transform the array to the desired form.

Example Input Array:

[
    {
        id: 1,
        name: "Uni A"
    },
    {},
    {}
]

Desired Output Array:

[
    {
        id: 1,
        name: "Uni A"
    }
]

In my DTO, the education array is defined like this:

@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => University)
education: University[] | null;
class University {
  @IsOptional()
  @IsInt()
  @IsPositive()
  id: number;

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

I've tried to transform the value using the @Transform decorator.

@Transform(({ value }) => isArrayContainsEmptyObject(value))
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => Education)
education: Education[] | null;

And defined the function like this:

const isArrayContainsEmptyObject = (array: any[]) => {
  const newArr = [];
  for (const obj of array) {
    if (obj && typeof obj === 'object' && Object.keys(obj).length !== 0)
      newArr.push(obj);
  }

  console.log(newArr)
  
  return newArr;
};

This function is actually transforming the array into the desired form. But the end result is not the same. This is actually creating the record with the unwanted empty object in the database (that is being send by the client!). I should get the desired form before going to the next layer.

Note: The DTO is being called in the controller layer like this:

create(@Body() createCandidateDto: CreateCandidateDto)

What am I doing wrong? If wrong, what else should I do? Move the transformation logic to anywhere else?

Thanks.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.