1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nest.jsをやっててDTOの理解度を上げたくなった僕の備忘録

Posted at

DTOとは

デザインパターンの一つであるDTOはData Transfer Objectの略で、名前通りデータを転送するためのオブジェクトのこと。
ビジネスロジックではなく、データのみを記述します。
シンプルで1つのことを表現するべきです。

注意点

データクラスというフィールドのみを持つクラスはアンチパターンとして知られています。
DTOは一見データクラスっぽい見た目をしているが、単に転送されるデータを表現するためだけのクラスとして使用されるため、データクラスではないです。

Nest.jsで使うDTOの例

※ Userを作成するAPIを実装しているケースを想定しています。

  1. DTOを作成する。

    import { IsBoolean, IsString } from 'class-validator';
    
    export class CreateUserDTO {
        @IsString()
        firstName: string;
    
        @IsString()
        lastName: string;
    
        @IsBoolean()
        isActive: boolean;
    }
    
  2. Userを作成するサービスを追加する。

    ...
    
    async createUser(createUserDTO: CreateUserDTO): Promise<User> {
        return await this.userRepository.save({
          firstName: createUserDTO.firstName,
          lastName: createUserDTO.lastName,
          isActive: createUserDTO.isActive,
        });
    }
    
    ...
    
  3. コントローラーに適用する。

    ...
    
    // リクエストボディがCreateUserDTOの形式であることを明示している
    create(@Body() createUserDTO: CreateUserDTO): Promise<User> {
        return this.userService.createUser(createUserDTO);
    }
    
    ...
    

参考

DTO(Data Transfer Object)の定義と使用
NestJS の DTO と Validation の基本 - 型定義とデコレータで安全にデータを受け付ける
[NestJS] ValidationPipeとDTOを使った数字のリクエストパラメータの型変換とバリデーション
NestJSでDTO(データ転送用オブジェクト)を使用しCRUD操作を行ってみる
DTO (Data Transfer Object)を学び直す
オブジェクト指向のDTOを理解する

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?