티스토리 뷰
프로젝트에서 @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),
) {}
참고 블로그
'라이브러리, 프레임워크 > Nest.js' 카테고리의 다른 글
[NejstJS] class-validator 정규식 활용 (Matches) (0) | 2022.07.07 |
---|---|
[NestJS] @Get 사용 시 라우터의 순서 (0) | 2022.07.06 |
[NestJS] Authorization - 사용자 등급별 권한 (0) | 2022.06.28 |
[NestJS] Authentication 구현 참고할 블로그 포스팅 (0) | 2022.06.10 |
[Nest.js 에러] No metadata for "" was found (0) | 2022.06.09 |
댓글