2

I am using NestJs framework for my project. In my controller I accept POST request and through ValidationPipe I transform body into my CreateHouseDTO. ValidationPipe is using whitelist and transform.

When I try api with JSON like this:

{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}

This is what my app logs (console.log output):

CreateHouseDTO{
    name:'Test',
    floors[ {} ]
}

It does even validate the nested objects when I make some mistakes in them. For example if I set name property in Floor object to Null or to some number without quotes.

Is it a bug or am I doing something wrong? Please help me.

My code:


//My DTOs
import {ValidateNested, IsString, IsArray} from "class-validator";
import {Body, Controller, Post} from "@nestjs/common";

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    public floors?: CreateFloorDTO[];
}

export class CreateFloorDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;

    @ValidateNested({each: true})
    @IsNotEmpty()
    @IsArray()
    public rooms?: CreateRoomDTO[];
}

export class CreateRoomDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;
}

//My Controller
@Controller("house")
export class HouseController {
    @Post()
    async create(
        @Body()
            body: CreateHouseDTO
    ) {
        console.log(body); //output I mentioned
        return body;
    }
}

1 Answer 1

9

You should do it like this:

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    @Type(()=>CreateFloorDTO)
    public floors?: CreateFloorDTO[];
}
Sign up to request clarification or add additional context in comments.

Comments

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.