简体   繁体   English

如何在 NestJS 中编写嵌套 DTO

[英]How to write nested DTOs in NestJS

I am a beginner in NestJS and I want to write a DTO for below structure -我是 NestJS 的初学者,我想为以下结构编写一个 DTO -

{
    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.我想为嵌套数据 object 编写一个 DTO。 I can't find a solid example for writing nested DTO in NestJS.我找不到在 NestJS 中编写嵌套 DTO 的可靠示例。 I am a beginner in NestJS and I have never worked with DTO before.我是 NestJS 的初学者,以前从未使用过 DTO。 So please don't assume that I know something.所以请不要以为我知道些什么。 I am using it with Mongoose.我将它与 Mongoose 一起使用。

You will have to create separate classes for each object in your schema and a main class which will import all the classes.您必须为架构中的每个 object 和一个主要的 class 创建单独的类,它将导入所有类。

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

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

    ...Follow same for the rest of schema

}

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

//example: //例子:

export class UserBaseDto {
  @ApiProperty({
    type: String,
    required: true,
    description: 'email user, minlength(4), maxlength(40)',
    default: "test@email.com",
  })
  @IsString()
  @MinLength(4)
  @MaxLength(40)
  @IsNotEmpty() 
  email: string;
//....enter code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM