DTO란? (Data Transfer Object)

DTO(Data Transfer Object)는 계층 간 데이터 전송을 위해 사용하는 객체입니다. 주로 컨트롤러 ↔ 서비스 ↔ 데이터베이스 간에 데이터를 주고받을 때 사용됩니다.

DTO의 특징

  • 불필요한 데이터를 제외하고, 필요한 데이터만 포함
  • 데이터를 변환하거나 가공할 수 있음
  • 보안 및 성능 최적화를 위해 사용
  • class 또는 interface로 선언 가능

예시 (TypeScript)

class UserDto {
  id: number;
  name: string;
  email: string;

  constructor(id: number, name: string, email: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
}

UserDto 클래스는 데이터베이스에서 가져온 유저 정보를 가공하여 클라이언트에 전달하는 데 사용할 수 있습니다.


type과 DTO의 차이점

| 비교 항목 | type | DTO | |—————|——–|—–| | 선언 방식 | type 키워드 사용 | class 또는 interface 사용 | | 기능 | 단순 타입 정의 | 데이터 가공 및 메서드 포함 가능 | | 인스턴스화 가능 여부 | ❌ (객체 생성 불가) | ✅ (객체 생성 가능) | | 계층 간 데이터 전송 | ❌ (주로 타입 검증 용도) | ✅ (데이터 변환, 유효성 검사 가능) |

type 예시 (TypeScript)

type User = {
  id: number;
  name: string;
  email: string;
};

DTO와 type 비교 예시

// type: 단순 데이터 구조
type UserType = {
  id: number;
  name: string;
  email: string;
};

// DTO: 데이터 변환 및 가공 가능
class UserDto {
  id: number;
  name: string;
  email: string;

  constructor(user: UserType) {
    this.id = user.id;
    this.name = user.name.toUpperCase(); // 예제: 이름을 대문자로 변환
    this.email = user.email;
  }
}

정리

✅ type은 단순한 데이터 구조를 정의하는 데 사용
✅ DTO는 데이터를 가공하거나 변환할 때 사용