Introduction:
In NestJS, Data Transfer Objects (DTOs) are used to define the shape of data for various operations, such as creating or updating entities. However, it's common to have similar properties between DTOs for creating and updating entities, which can lead to redundancy in your code. In this post, we'll explore a smart way to reduce redundancy in NestJS DTOs using class inheritance and the PartialType utility provided by the @nestjs/mapped-types package.
Step 1: Install the @nestjs/mapped-types package
First, you'll need to install the @nestjs/mapped-types package, which provides the PartialType utility:
npm install @nestjs/mapped-types
Step 2: Create a base DTO for creating a new entity
Let's create a base DTO for creating a new user. This will be our CreateUserDto:
// create-user.dto.ts
export class CreateUserDto {
firstName: string;
lastName: string;
email: string;
password: string;
}
Step 3: Create an update DTO for updating an entity using class inheritance and PartialType
Now, we'll create an UpdateUserDto by extending the CreateUserDto and using the PartialType utility. This will make all properties from CreateUserDto optional in UpdateUserDto:
// update-user.dto.ts
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './create-user.dto';
export class UpdateUserDto extends PartialType(CreateUserDto) {}
Conclusion:
By using class inheritance and the PartialType utility, we've successfully reduced redundancy in our NestJS DTOs. The UpdateUserDto inherits all properties from CreateUserDto, but they are optional due to the PartialType utility. This keeps your code DRY (Don't Repeat Yourself) and makes it easier to maintain.
When you need to update your DTOs, you only need to modify the base DTO (CreateUserDto), and the changes will automatically be reflected in the UpdateUserDto. This approach helps you write cleaner and more maintainable code in your NestJS applications.
Top comments (0)