[우버이츠 클론코딩] # 4. TypeORM

GisangLee·2022년 6월 14일
0

Giber-eats

목록 보기
5/5

1. Entity

  • TypeORM 공식문서에 따르면 아래와 같다.

    Entity is a class that to a database table( or collecttion when using MongoDB ).

  • Entity는 디비 테이블에 매핑되는 클래스라고 정의할 수 있다.

    Entity 하나로 graphql + 데이터 베이스 테이블을 만들 수 있다.

  • ex)

@ObjectType()
@Entity()
export class Restaurant {
  @PrimaryGernatedColumn()
  @Field(type => Number)
  id: number;
  
  @Column()
  @Field(type => String)
  name: string;
  
  @Column()
  @Field(type = Boolean)
  isVegan: boolean;
}

2. Mapped Types

  • PartialType()

    - returns a type (class) with all the properties of the input type set to optional
export class CreateCatDto {
  name: string;
  age: number;
  breed: string;
}

export class UpdateCatDto extends PartialType(CreateCatDto) {}
  • PickType()

    - constructs a new type (class) by picking a set of properties from an input type
export class CreateCatDto {
  name: string;
  age: number;
  breed: string;
}

export class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}
  • IntersectionType()

    - combines two types into one new type (class)
export class CreateCatDto {
  name: string;
  breed: string;
}

export class AdditionalCatInfo {
  color: string;
}

export class UpdateCatDto extends IntersectionType(
  CreateCatDto,
  AdditionalCatInfo,
) {}
  • OmitType()

    - constructs a type by picking all properties from an input type and then removing a particular set of keys
export class CreateCatDto {
  name: string;
  age: number;
  breed: string;
}

export class UpdateCatDto extends OmitType(CreateCatDto, ['name'] as const) {}

3. Synchronize DTO with Entity

Entity가 수정될 때마다 DTO를 수기로 수정하고 작성하는 일은
비효율적이라고 할 수 있다. 그래서 연결을 해야한다.

  • 방법 1. extends entity to DTO
@InputType()
export class CreateRestaurant extends OmitType(Restaurant, ["id"], InputType) {
  
}
  • 방법 2. Add InputType to Entity and set isAbtract: true
@InputType({ isAbract: true })
@ObjectType()
@Entity()
export class Restaurant {
  @PrimaryGernatedColumn()
  @Field(type => Number)
  id: number;
  
  @Column()
  @Field(type => String)
  name: string;
  
  @Column()
  @Field(type = Boolean)
  isVegan: boolean;
}
profile
포폴 및 이력서 : https://gisanglee.github.io/web-porfolio/

0개의 댓글