...

/

Create a DTO and Introduce Entities

Create a DTO and Introduce Entities

Learn how to use DTOs and entities in NestJS and understand their differences.

DTOs and entities

This lesson will explore the fundamental concepts of DTOs and entities. A DTO enables us to format and structure data for various use cases, while entities represent the data models that interact with the database. Understanding these concepts is essential for building a data-driven application.

DTO

A DTO is a data object that transfers data between different layers. DTOs are objects that shape and format data for efficient and structured exchange between different layers or components within an application. While they’re often employed in client-server communication, their primary purpose is to facilitate data transfer and maintain a standardized format between various application layers, such as between controllers and services. DTOs help ensure that data is appropriately structured and presented, enhancing the application’s maintainability.

For example, the UserDto class represents the data structure of a user.

Press + to interact
export class UserDto {
userId: number;
name: string;
email: string;
}

Then, in the controller endpoint below, we specify the return data type using the UserDto class.

Press + to interact
@Get()
findAll() : UserDto[]{
return this.usersService.findAll();
}

In TypeScript, we can use an interface or class to define data shape. In the context of NestJS, using DTO classes rather than interfaces is recommended. The reason is that, in TypeScript, interfaces exist only at compile-time and don’t have a runtime representation, while classes are preserved in the compiled JavaScript code at runtime. NestJS might require access to an object’s metadata during runtime, making DTO classes the preferred choice.

DTOs for creating and updating

In the example above, UserDto represents the data structure when retrieving user data. When creating a user, we need to add a password field. Another CreateUserDto class is then created.

Press + to interact
export class CreateUserDto extends UserDto {
password: string;
}

With the CreateUserDto class, the server API will ...