ABOUT ME

Today
Yesterday
Total
  • nestJS에서 DTO에서 쓰는 PartialType and PickType을 같이 쓸 때 주의할 점
    Project using Nest.js/E-commerce App 2021. 9. 3. 16:39

    product.entity.ts

    import { Field, InputType, Int, ObjectType } from '@nestjs/graphql';
    import { IsNumber, IsString } from 'class-validator';
    import { Column, Entity, ManyToOne } from 'typeorm';
    
    import { CoreEntity } from 'src/common/entities/common.entity';
    import { User } from 'src/users/entities/user.entity';
    import { Category } from 'src/categories/entities/category.entity';
    
    @InputType('InfoItemInputType', { isAbstract: true })
    @ObjectType()
    export class InfoItem {
      @Field((type) => String)
      @IsString()
      key: string;
    
      @Field((type) => String)
      @IsString()
      value: string;
    }
    
    @InputType('ProductInputType', { isAbstract: true })
    @ObjectType()
    @Entity()
    export class Product extends CoreEntity {
      @Column()
      @Field((type) => String)
      @IsString()
      name: string;
    
      @ManyToOne((type) => User, (user) => user.products, {
        onDelete: 'CASCADE',
      })
      @Field((type) => User)
      provider: User;
    
      @Column()
      @Field((type) => Int)
      @IsNumber()
      price: number;
    
      @Column('text', { array: true })
      @Field((type) => [String])
      images: string[];
    
      @ManyToOne((type) => Category, (category) => category.products, {
        onDelete: 'SET NULL',
      })
      @Field((type) => Category)
      category: Category;
    
      @Field((type) => [InfoItem], { nullable: true })
      @Column({ nullable: true, type: 'json' })
      info?: InfoItem[];
    }

    edit-product.dto.ts

    import {
      Field,
      InputType,
      ObjectType,
      PartialType,
      PickType,
    } from '@nestjs/graphql';
    
    import { CoreOutput } from 'src/common/dtos/output.dto';
    import { Product } from '../entities/product';
    
    @InputType()
    export class EditProductInput extends PickType(PartialType(Product), [
      'name',
      'price',
      'images',
      'info',
    ]) {
      @Field((type) => String)
      productId: string;
    }
    
    @ObjectType()
    export class EditProductOutput extends CoreOutput {}

       edit api를 만들 대 PartialType과 PickType을 종종 같이 쓴다. 이 때 순서가 중요한데 PartialType이 PickType을 감싸면 안 되고 PickType의 인자로 PartialType을 줘야 한다. 그렇지 않으면 name, price, images, info 이외에도 id, createdAt, updatedAt, provider, category 등도 수정할 수 있는 권한을 주게된다.

    Github link

    Amend edit-dtos : https://github.com/zpskek/houpang-backend-v1/commit/8a932b1b010a957762f3ba570a8711a7904da41b

    'Project using Nest.js > E-commerce App' 카테고리의 다른 글

    댓글

Designed by Tistory.