티스토리 뷰
라이브러리, 프레임워크/Nest.js
[NejstJS] ValidationPipe 사용 시 OneToMany 관계까지 유효성 검사하기 (class-validator / class-transformer)
dv_jamie 2023. 1. 4. 17:40관계설정
레시피와 재료는 OneToMany 관계이다.
// recipe.entity.ts
@Entity()
export class Recipe extends BaseEntity {
@IsString()
@Column()
title: string
@OneToMany(() => Ingredient, (ingredient) => ingredient.recipe)
ingredients: Ingredient[]
}
// ingredient.entity.ts
@Entity()
export class Ingredient {
@PrimaryGeneratedColumn()
id: number;
@IsString()
@Column({ length: 10 })
name: string
@ManyToOne(() => Recipe, (recipe) => recipe.ingredients, {
onDelete: 'CASCADE'
})
recipe: Recipe
}
Dto 생성
레시피 생성 시 사용할 Dto를 아래와 같이 PickType을 이용해 만들고,
ingredients가 객체의 배열인지 검사하는 데코레이터를 추가했다 (이후 컨트롤러에 적용)
// create-recipe.dto.ts
export class CreateRecipeDto extends PickType(Recipe, [
'title',
'ingredients'
] as const) {}
// recipe.entity.ts
@Entity()
export class Recipe extends BaseEntity {
@IsString()
@Column()
title: string
@IsObject({ each: true)} // *** 여기에 추가
@OneToMany(() => Ingredient, (ingredient) => ingredient.recipe)
ingredients: Ingredient[]
}
테스트
body 객체를 다음과 같이 작성하여 테스트 해봤다
// 1번
{
"title": "나의 레시피",
"ingredients": [{
"name": "재료1",
}]
}
// 2번
{
"title": "나의 레시피",
"ingredients": [{}]
}
// 3번
{
"title": "나의 레시피",
"ingredients": [{
"name": 1,
}]
}
// 4번
{
"title": "나의 레시피",
"ingredients": [{
"name": "재료1",
"error": "에러나야함"
}]
}
1번 ~ 4번 중 1번만 통과해야하는데, ingredients 배열 내 객체이기 때문에 모두 에러가 나지 않았다.
하지만 난 객체 내의 값들까지 유효성 검사를 하고 싶었다
- 2번 테스트 : name이 입력되지 않았을 때 에러나야 함
- 3번 테스트 : value가 다르게 들어가도 에러나야 함
- 4번 테스트 : name 외에 다른 property가 들어가도 에러가 나지 않는다
해결
// recipe.entity.ts
@Entity()
export class Recipe extends BaseEntity {
@IsString()
@Column()
title: string
@ValidateNested({ each: true }) // *** 배열이기 때문에 { each: true } 옵션 부여
@Type(() => Ingredient) // *** Ingredient 엔티티로 변환
@OneToMany(() => Ingredient, (ingredient) => ingredient.recipe)
ingredients: Ingredient[]
}
참고 사이트
'라이브러리, 프레임워크 > Nest.js' 카테고리의 다른 글
[NejstJS] @Type(() => Boolean) 적용 시 항상 true 반환되는 문제 (class-validator) (0) | 2022.12.30 |
---|---|
[NejstJS] Query 배열로 받기 (class-validator 이용) (0) | 2022.12.30 |
[NestJS] @Res 객체를 쓸 때 return을 하지 않는 문제 (0) | 2022.09.06 |
[NestJS] circular dependency 에러 원인 (0) | 2022.07.07 |
[NejstJS] class-validator 정규식 활용 (Matches) (0) | 2022.07.07 |
댓글