如何在 NestJS 中编写嵌套 DTO

use*_*180 17 javascript dto typescript nestjs

我是 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
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ist*_*lor 36

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

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

}

Run Code Online (Sandbox Code Playgroud)

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

  • 哦天哪,这个东西正盯着我的脸,但我看不到它。非常感谢。将此标记为已接受的答案。这是未来读者对同一问题的另一个答案 - /sf/ask/3765046841/ (2认同)
  • 请注意,它是@ValidateNested(),而不是@ValidatedNested() (2认同)