사진찍는 개발자📸👩‍💻

[Nest.js] swagger 데코레이터 - 5 (타입 헬퍼) 본문

develop/Nest.js

[Nest.js] swagger 데코레이터 - 5 (타입 헬퍼)

hsleeee 2024. 12. 29. 18:30
반응형
SMALL

타입 헬퍼란? 

  • 기존에 정의된 타입을 기반으로 새로운 타입을 쉽게 만들 수 있도록 도와주는 도구
  • 코드 중복을 줄이고 타입간의 일관성을 유지하는 데에 유용
  • 장점
    • 코드 중복 감소
    • 타입 안정성 보장
    • API 문서 자동 생성
    • 유지보수 용이성
    • 일관된 DTO 구조 유지

 

 

1. PartialType()

- 용도: 모든 속성을 선택적(optional)으로 만듦

// 원본 DTO
class CreatePostDto {
  @ApiProperty()
  title: string;

  @ApiProperty()
  content: string;

  @ApiProperty()
  authorId: number;
}

// 모든 필드가 선택적으로 변환
@ApiTags('posts')
class UpdatePostDto extends PartialType(CreatePostDto) {}
// 결과:
// {
//   title?: string;
//   content?: string;
//   authorId?: number;
// }

 

2. PickType()

- 용도: 특정 속성들만 선택해서 새로운 타입 생성

class CreateUserDto {
  @ApiProperty()
  email: string;

  @ApiProperty()
  password: string;

  @ApiProperty()
  name: string;

  @ApiProperty()
  age: number;
}

// email과 password만 선택
class LoginDto extends PickType(CreateUserDto, ['email', 'password']) {}
// 결과:
// {
//   email: string;
//   password: string;
// }

 

3. OmitType()

- 용도: 특정 속성들을 제외한 새로운 타입 생성

class UserDto {
  @ApiProperty()
  id: number;

  @ApiProperty()
  email: string;

  @ApiProperty()
  password: string;
}

// password 필드 제외
class UserResponseDto extends OmitType(UserDto, ['password']) {}
// 결과:
// {
//   id: number;
//   email: string;
// }

 

4. IntersectionType()

- 용도: 두 타입을 결합하여 새로운 타입 생성

class PostDto {
  @ApiProperty()
  title: string;

  @ApiProperty()
  content: string;
}

class AuditDto {
  @ApiProperty()
  createdAt: Date;

  @ApiProperty()
  updatedAt: Date;
}

// PostDto와 AuditDto 결합
class PostDetailDto extends IntersectionType(PostDto, AuditDto) {}
// 결과:
// {
//   title: string;
//   content: string;
//   createdAt: Date;
//   updatedAt: Date;
// }
반응형
LIST