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?
A DTO is helpful whenever you need to group values in ad hoc structures for passing data around. From a pure design perspective, DTOs are a solution really close to perfection. DTOs help to further decouple presentation from the service layer and the domain model.
DTO is the short name of Data Transfer Object. DTO is used in order to validate incoming requests. The DTO on its 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!!!.
Data Transfer Object (DTO) The Data Transfer Objects are objects which bridge the domain, business and application layer. DTOs are basically “dumb” objects holding key-value pairs. To keep it simpler, domain is the database, business is our logic in handler function and application means our web service API.
DTO stands for Data Transfer Object. This is a pattern, widely used in the backend, in which you decouple types used for data transfer from the actual data model. In our example, the changes in the API will be reflected in the UserDTO type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With