如何在NestJS中编写嵌套DTO

问题描述 投票:0回答:2

我是 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
                    }
                }
            }
        }
    }
}

我想为该嵌套数据对象编写一个 DTO。我找不到在 NestJS 中编写嵌套 DTO 的可靠示例。我是 NestJS 的初学者,之前从未使用过 DTO。所以请不要假设我知道一些事情。我正在将它与 Mongoose 一起使用。

javascript typescript nestjs dto
2个回答
32
投票

您必须为架构中的每个对象创建单独的类,以及将导入所有类的主类。

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

}

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


-3
投票

//示例:

export class UserBaseDto {
  @ApiProperty({
    type: String,
    required: true,
    description: 'email user, minlength(4), maxlength(40)',
    default: "[email protected]",
  })
  @IsString()
  @MinLength(4)
  @MaxLength(40)
  @IsNotEmpty() 
  email: string;
//....enter code here
}
© www.soinside.com 2019 - 2024. All rights reserved.