Data Transfer Object (DTO)
Manipulate data between the client and the server.
This guide is based of NestJS controllers documentation, NestJS DTO documentation & Class-validator GitHub.
Data Transfer Objects (DTOs) are used to define the shape of data that is sent between the client and the server. They are used to validate and transform data before it is passed to the service layer.
Structure DTO in shared folder
VitNode uses a shared folder to store DTOs. This folder is located at apps/shared/plugins/{your_plugin_code}
.
Thanks to monorepo structure, you can use this folder in both the frontend
and backend
. This is useful when you need type-safe data transfer between the client and the server.
Here is an example of how to structure DTOs in the shared folder:
Request payloads
As an example, let's create a simple POST
endpoint.
But we don't have any methods to provide data to the controller. We have few options to do this:
Body
The @Body()
decorator is used to extract the entire body of the request.
Create DTO
Inside the shared folder, create a new file for your DTO.
Query
The @Query()
decorator is used to extract the query parameters from the request.
Example query: http://localhost:8080/welcome/example?name=John&description=Hello
Create DTO
Inside the shared folder, create a new file for your DTO.
As you can see, the structure is the same as the body DTO. The only difference is that we use the @Query()
decorator in the controller.
Param
The @Param()
decorator is used to extract the route parameters from the request.
Example route: http://localhost:8080/welcome/example/John
Create DTO
Inside the shared folder, create a new file for your DTO.
The @IsNumberString()
decorator is used to validate that the parameter is a
number from the client. If the client sends a string, the validation will
fail.
Types and Paremeters
This section is based of NestJS OpenAPI types documentation.
Api Property
The @ApiProperty()
and @ApiPropertyOptional()
decorators are used to define the metadata for the DTO properties. This metadata is used by the Swagger UI to generate the API documentation. You can provide a description, example, and other parameters.
Arrays
To define an array in a DTO, you can use the Array
type or the []
syntax.
Enums
You cannot store an enum in the same file as the DTO. It will cause a issue
with the NestJS
packages inside shared
folder and may not work properly on
frontend
side.
To use an enum, you need to create a new file in the shared
folder.
Then you can use it in your DTO.
oneOf, anyOf, allOf
To use oneOf
, anyOf
, or allOf
in your DTO, you can use the @ApiProperty()
decorator.
Arrays
Objects
Schema Name
If you want to chnge the schema name, you can use the @ApiSchema()
decorator.
Usage in frontend
You can also use DTOs in the frontend.