Search code examples
javascripttypescriptnestjsdto

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.


Solution

  • 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