NestJS中的数据传输对象的目的是什么? [英] What is the purpose of a Data Transfer Object in NestJS?

查看:76
本文介绍了NestJS中的数据传输对象的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个问题而苦苦挣扎.我正在遵循NestJS的文档.NodeJS的后端框架.该文档提到了DTO(数据传输对象).我创建了一个用于创建用户的DTO:

Im struggling with a problem. Im following the documentation of NestJS. The back-end framework for NodeJS. The documentation mentions a DTO (Data Transfer Object). I created a DTO for creating a user:

export class CreateUserDto {
    readonly email: string;
    readonly password: string;
}

与此结合:

@Post('create')
createUser(@Body() userData: CreateUserDto): User {
    return this.usersService.createUser(userData);
}

由于某种原因,我可以使用任何类型的机构向该路线发出发布请求.我可以在体内放置任何类型的信息而不会出错.这种DTO的全部目的是仅允许体内某些信息,对吗?除了使用导出类CreateUserDTO之外,我还尝试了导出接口CreateUserDTO,但这也不起作用.我也是Typescript和NestJS的新手.有没有人能够解释为什么它无法按我预期的方式工作,或者这种数据传输对象的目的是什么?

For some reason, I am able to make a post request to this route with any type of body. I can place any type of information in the body without getting an error. The whole point of such a DTO is to allow only certain information in the body, right? Instead of using export class CreateUserDTO i also tried export interface CreateUserDTO, but this isn't working either. I am new to typescript and NestJS as well. Is there anyone who might be able to explain why it's not working the way I expected or what the purpose is of such a Data Transfer Object?

推荐答案

对于开发人员和使用API​​的人来说,DTO本身更是一个指南,它知道请求主体期望的形状是什么,它实际上并不会自行运行任何验证.但是,使用Typescript,您可以从 class-validator 库中添加装饰器,然后使用内置ValidationPipe ,并对传入的请求运行验证,以便只有预期的请求正文可以进入.

The DTO on it's own is more of a guideline for the developer and those who consume the API to know what kind of shape the request body expects to be, it doesn't actually run any validations on its own. However, with Typescript you can add in decorators from the class-validator library and and use the built-in ValidationPipe and have validations run on your incoming requests so that only the expected request body can come in.

简而言之,DTO是请求的外观的定义,但是由于JavaScript是一种动态语言,因此您可以发送任何内容.这就是为什么存在像 class-validator runtypes 这样的库的原因.

In short, the DTO is the definition of what the request should look like, but because JavaScript is a dynamic language, you can send in anything. That's why libraries like class-validator and runtypes exist.

这篇关于NestJS中的数据传输对象的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆