Data Transfer Object
NoteIMPORTANT!
The DTO file should be placed in directoryapp/dto
A data transfer object (DTO) is an object that carries data between processes. You can use this technique to facilitate communication between two systems (like an API and your server) without potentially exposing sensitive information
A DTO should just contain data, not business logic. It’s a simple, small thing that should do one task only.
A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.
Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than four or five parameters.
DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer. The main benefit here is that it reduces the amount of data that needs to be sent across the wire in distributed applications. They also make great models in the MVC pattern
When using the DTO pattern, you would also make use of DTO assemblers. The assemblers are used to create DTOs from Domain Objects, and vice versa.
package dto
import "gfly/app/domain/models/types"
// CreateUser struct to describe the request body to create a new user.
// CreateUser struct to describe the request body to create a new user.
// @Description Request payload for creating a new user.
// @Tags Users
type CreateUser struct {
Email string `json:"email" example:"john@jivecode.com" validate:"required,email,max=255" doc:"User's email address (required, max length 255)"`
Password string `json:"password" example:"M1PassW@s" validate:"required,max=255" doc:"User's password (required, max length 255)"`
Fullname string `json:"fullname" example:"John Doe" validate:"required,max=255" doc:"User's full name (required, max length 255)"`
Phone string `json:"phone" example:"0989831911" validate:"required,max=20" doc:"User's phone number (required, max length 20)"`
Avatar string `json:"avatar" example:"https://i.pravatar.cc/32" validate:"omitempty,max=255" doc:"URL of the user's avatar (optional, max length 255)"`
Status string `json:"status" example:"pending" validate:"omitempty" doc:"User's status (optional)"`
Roles []types.Role `json:"roles" example:"admin,user" validate:"omitempty" doc:"List of user's roles (optional)"`
}
A good DTO will:
- Minimize boilerplate. You’ll write each one fresh.
- Be easy to create. DTOs shouldn’t be so complicated that you struggle to write them.
- Be readable. Anyone should be able to parse your code.
In gFly, we will always mention and use DTO in many cases:
- Controller —> Service
- Service <—> Service
- Console —> Service