DTO? Yes! DTO!
My objective in this writing is to explain the underlying concept behind DTO in the simplest way possible.
I’ll start by saying that I will use the NestJS framework In this article.
Daniel, come on, stop wasting my time!! ok ok, let’s get right into it.
What is a DTO? let’s define what a DTO is.
A DTO is just an object, Data Transfer Object, this object can be either a class or a TypeScript interface capeesh?
This is a code example straight from NestJS docs:
(File name: create-cat.dto.ts)
export class CreateCatDto {
name: string;
age: number;
breed: string;
}
as you can see a DTO is a class (object).
Now that we see that there is nothing to be afraid of I will continue explaining the purpose of a DTO and why you must use them.
The code below is related to the DTO that I’ve just shown you, Let me explain how.
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
The sole purpose of a DTO is to validate the data transferred in communication between the client and the server.
In our case, we will send an HTTP-POST request, within the body of the request we will add an object with the same key-value pairs as in the DTO.
One caveat:
In most cases, if not all, you will have to use the Body decorator before using the DTO as such: @Body() createCatDto: CreateCatDto