【问题标题】:How to write nested DTOs in NestJS如何在 NestJS 中编写嵌套 DTO
【发布时间】:2021-08-23 05:42:33
【问题描述】:

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

我想为那个嵌套的 Data 对象写一个 DTO。我找不到在 NestJS 中编写嵌套 DTO 的可靠示例。我是 NestJS 的初学者,以前从未使用过 DTO。所以请不要以为我知道些什么。我将它与 Mongoose 一起使用。

【问题讨论】:

    标签: javascript typescript nestjs dto


    【解决方案1】:

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

    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

    【讨论】:

    • 天哪,这东西正盯着我的脸,但我看不见。非常感谢。将此标记为已接受的答案。对于未来的读者,这是同一问题的另一个答案 - stackoverflow.com/questions/53786383/…
    • 注意是@ValidateNested(),不是@ValidatedNested()
    【解决方案2】:

    //示例:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-24
      • 2021-05-30
      • 1970-01-01
      • 2019-10-22
      • 2021-12-04
      • 1970-01-01
      • 2011-09-25
      • 2019-05-28
      相关资源
      最近更新 更多