Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write nested DTOs in NestJS

I am a beginner in NestJS and I want to write a DTO for below structure -

{
    something: {
        info: {
            title: string,
            score: number,
            description: string,
            time: string,
            DateOfCreation: string
        },
        Store: {
            item: {
                question: string,
                options: {
                    item: {
                        answer: string,
                        description: string,
                        id: string,
                        key: string,
                        option: string
                    }
                }
            }
        }
    }
}

I want to write a DTO for that nested Data object. I can't find a solid example for writing nested DTO in NestJS. I am a beginner in NestJS and I have never worked with DTO before. So please don't assume that I know something. I am using it with Mongoose.

like image 604
user3399180 Avatar asked Dec 01 '25 20:12

user3399180


1 Answers

You will have to create separate classes for each object in your schema and a main class which will import all the classes.

import { Type } from "class-transformer";

class Info {
    readonly title:string
    readonly score:number
    readonly description:string
    readonly dateOfCreation:Date
}

export class SampleDto {
    @Type(() => Info)
    @ValidateNested()
    readonly info: Info

    ...Follow same for the rest of the schema

}

Refer: https://github.com/typestack/class-validator#validating-nested-objects

like image 55
Istiyak Tailor Avatar answered Dec 04 '25 11:12

Istiyak Tailor