백엔드/NestJs

[nestjs] PickType,OmitType, PartialType

STUFIT 2023. 9. 25. 10:22
반응형

nestjs에서 graphql을 사용할 때, ObjectType과 InputType을 통해 input과 output 스키마를 설정하게 된다.

이 때, ObjectType 및 InputType을 작성할 때, 엄청나게 많은 필드들을 중복적으로 다른 스키마에서 사용할 때가 있는데, 이 때마다 똑같은 필드들을 중복해서 작성하는 것은 비효율적이다. 

이럴때 사용하는 것이 PickType, OmitType, PartialType 인데 아레에서는 각각 언제 사용하는지 설명하도록 하겠다.

1. PickType

PickType은 특정 필드만을 선택하여 새로운 타입을 만들 때 사용된다.

만약 예를들어, 아래와 같은 ObjectType이 존재한다고 가정하겠다.

@ObjectType('UserList')
export class UserList {
	  @Field(() => Int, { nullable: true, description: '아이디' })
      id: number;
      @Field(() => String, { nullable: true, description: '이름' })
      name: string;
      @Field(() => String, { nullable: true, description: '핸드폰번호' })
      phoneNumber: string;
      @Field(() => String, { nullable: true, description: '주소' })
      address: string;
      @Field(() => String, { nullable: true, description: '성별' })
      sex: string;
}

해당 ObjectType에서 필드는 총5가지이다.(id,name,phoneNumber,address,sex)

이 때, 나는 새로운 ObjectType을 만드는데 name과,phoneNumber만이 필요하다고 하면 보통은 저 필드를 복사 & 붙여넣기를 할텐데 그렇게 하는 것이 아닌 PickType을 이용하면 훨씬 간결하게 표현할 수 있다.

import { ObjectType, PickType } from '@nestjs/graphql';
import { UserList } from './userList.model';

@ObjectType()
export class PickUserList extends PickType(UserList, ['id', 'name'] as const) {}

위에서는 PickType을 상속받아서 name과 phoneNumber만을 사용한 것이다. 그리고 뒤에 as const를 붙이는 이유는 상수 단언으로서, 배열이 불변하도록 명시적으로 나타낸 것이다.

2. PartialType

PartialType은 모든 필드에 대해 선택적으로 변경하는 것으로서 보통 InputType의 경우 자주 사용된다.

만약 아래의 코드가 있다고 가정하자.

import { InputType, Field } from '@nestjs/graphql';

@InputType()
export class CreateUserInput {
  @Field()
  name: string;

  @Field()
  phoneNumber: string;

  @Field()
  address: string;

  @Field()
  sex: string;
}

이 떄, 나는 모든 필드에 대해 선택적 필드로 변경하고 싶다면 PartialType으로 변경해준다.

import { InputType } from '@nestjs/graphql';
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserInput } from './create-user.input';

@InputType()
export class UpdateUserInput extends PartialType(CreateUserInput) {}

이렇게 하면 InputType에 UpdateUserInput을 사용하게 되면 모든 필드가 선택적 필드가 되어서 사용자가 원하는 필드에 대해 업데이트 하는 mutation을 만들 수 있다.

3. OmitType

OmitType은 1번의 PickType과 반대로, 원치않는 필드를 제외한 나머지 필드를 가져오는 것을 뜻한다.

만약 아래의 코드가 있다고 가정해보자.

@ObjectType('UserList')
export class UserList {
	  @Field(() => Int, { nullable: true, description: '아이디' })
      id: number;
      @Field(() => String, { nullable: true, description: '이름' })
      name: string;
      @Field(() => String, { nullable: true, description: '핸드폰번호' })
      phoneNumber: string;
      @Field(() => String, { nullable: true, description: '주소' })
      address: string;
      @Field(() => String, { nullable: true, description: '성별' })
      sex: string;
}

이 떄, 나는 address 필드만 제외하고 나머지는 새로운 ObjectType의 스키마로 만들고 싶다면 아래의 코드로 표현할 수 있다.

import { ObjectType, OmitType } from '@nestjs/graphql';
import { UserList } from './userList.model';

@ObjectType()
export class OmitUserList extends OmitType(UserList, ['address'] as const) {}

이 3가지를 사용한다면 불필요한 노가다를 줄일 수 있다.

 

반응형

'백엔드 > NestJs' 카테고리의 다른 글

nestjs) 미들웨어,가드,필터  (0) 2025.03.13
[typeorm] getRawMany(), getMany()  (1) 2023.12.12
리졸브필드(resolveField)  (0) 2023.07.31
권한설정  (0) 2023.07.18
[nestjs] new DataLoader  (0) 2023.07.02