티스토리 뷰

프로젝트에서 @ApiProperty()와 유효성을 체크하는 데코레이터를 모두 기본적으로 entity에 작성하고 있다.

그런데 Dto를 만드려고 보니 entity와 중복되는 코드들이 많았다.
이 경우 유효성 체크라던가 swagger 에서 수정되어야하는 부분이 있을 때 Dto, Entity 모두를 체크해야하는 문제가 있다.

필요한 것만 뽑아 쓰는 PickType 혹은 옵션으로 만들어주는 PartialType을 사용하려고 했는데,
Entity에 없는 값을 쓰려면 어떻게 해야할지 방법을 알 수 없어서 서치해봤다.

 

Entity

@Entity()
export class Alarm {
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  id: number;

  @ApiProperty({ description: '알람 구분', enum: AlarmType })
  @IsEnum(AlarmType)
  @Column('varchar', { name: 'type', nullable: false })
  type: AlarmType;

  @ApiProperty({ description: '알람 아이콘' })
  @IsString()
  @Column('varchar', { name: 'image' })
  image: string;

  @ApiProperty({ description: '알람 내용' })
  @IsString()
  @Column('varchar', { name: 'text' })
  text: string;

  /*
  ManyToOne
  */
  @ApiProperty({ description: '유저' })
  @IsNumber()
  @ManyToOne((type) => User, (user) => user.alarm, {
    onDelete: 'CASCADE'
  })
  user: number;
  
  /*
  Date
  */
  @CreateDateColumn()
  createdAt: Date;
}

 


기존 Dto

export class CreateAlarmDto {
    @ApiProperty({ description: '유저 ID' })
    @IsNumber({}, { each: true })
    userIds: number[];

    @ApiProperty({ description: '알람 구분', enum: AlarmType })
    @IsEnum(AlarmType)
    type: AlarmType;

    @ApiProperty({ description: '알람 아이콘' })
    @IsOptional()
    @IsString()
    image?: string;

    @ApiProperty({ description: '알람 내용' })
    @IsString()
    text: string;

    @ApiProperty({ description: '알람 터치시 이동 link', required: false })
    @IsOptional()
    @IsString()
    link?: string;
}

type, image, text, link 가 모두 중복이다

 

변경 Dto

export class CreateAlarmDto extends PickType(Alarm, [
    'type',
    'image',
    'text',
    'link'
] as const) {
    @ApiProperty({ description: '유저 ID' })
    @IsNumber({}, { each: true })
    userIds: number[];
}

중복되는 것들은 PickType을 이용했고, Entity에 없이 새로 추가 돼야 하는 것은 중괄호 안에 새로 작성하였다.

 

 

그 외 Mapped types

PartialType() : 동일 필드를 사용하되 각 필드가 선택 사항

export class UpdateAlarmDto extends PartialType(CreateAlarmDto) {}


OmitType() : 특정 필드 제거

export class UpdateAlarmDto extends OmitType(CreateAlarmDto, ['type'] as const) {}


IntersectionType() : 여러 집합을 결합

export class UpdateAlarmDto extends IntersectionType(
  CreateAlarmDto,
  AdditionalAlarmInfo,
) {}


CompositionType() : 타입들 조합하여 사용

export class UpdateAlarmDto extends PartialType(
  OmitType(CreateAlarmDto, ['type'] as const),
) {}

 


참고 블로그

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함