티스토리 뷰

관계설정

레시피와 재료는 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[]
}

 


참고 사이트

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
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
글 보관함