Nest js 中的 DTO、接口和架构有什么区别

Raj*_*die 7 nestjs

我是 Nest js 的新手,我们有一些主题,例如 Dto、接口和架构,任何人都可以提供有关这些主题的清晰信息。

小智 13

Dto、接口和 Schema 并不是 Nestjs 独有的。

数据传输对象是一种用于封装数据并将其从应用程序的一个子系统发送到另一个子系统的对象。通俗地说,它以定义的方式格式化数据。示例:您需要在正文中传递的注册路由的数据。然后,您可以使用 DTO 来仅过滤掉所需的信息并剔除其余信息。

//signUp.dto.ts
export class signUpDto {
    @IsNotEmpty({message: "Email cannot be empty."})
    @IsEmail() //class-validators can be ignored here.
    email: string;

    @IsNotEmpty({message: "Password cannot be Empty."})
    @MinLength(6,{message: "Password must be 6 characters."})
    @MaxLength(128,{message: "Password must be less than 128."})
    password: string;
}
Run Code Online (Sandbox Code Playgroud)

现在,当您验证传入的请求正文时,它将检查正文中的这两个字段以及类验证器规则(如果已定义)。

接口:接口用于类型检查和定义可以传递给控制器​​或 Nest 服务的数据类型。来自 NestJs 文档:

接口是一种抽象类型,包含一组特定的字段,类型必须包含这些字段才能实现接口

假设你有一个人机界面,你可以实现一个医生、教授和每个人示例:

interface Human {
    eyeColor: string;
    hairColor: string;
}
class Doctor implements Human{
    eyeColor: string;
    hairColor: string;
}
Run Code Online (Sandbox Code Playgroud)

此外,模式是您在数据库中定义实体、完整性约束、关系等的方式。一个模式可以有多个表并有许多关系,例如 OneToMany、ManyToOne、ManyToMany。

希望这能消除您的疑虑。