What is the purpose of a Data Transfer Object in NestJS?

让人想犯罪 __ 提交于 2021-01-02 18:05:14

问题


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;
}

In combination with this:

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

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?


回答1:


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.

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.




回答2:


At runtime all types are lost, so the controller accepts whatever JSON comes from request body. If you want a type check, you should enable a ValidationPipe that leverages class-trasformer and class-validator libraries:

app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
      validationError: { target: false, value: false },
    })
  ); 


来源:https://stackoverflow.com/questions/59397687/what-is-the-purpose-of-a-data-transfer-object-in-nestjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!