[NestJS] Object Type과 Input Type

유제·2021년 3월 1일
1

NestJS 공부하기

목록 보기
4/6

Object Types

GraphQL Schema에서 대부분의 definition들은 Object Type이다. 각각의 Object Type은 애플리케이션 클라이언트가 상호 작용할 수 있는 Domain Object를 나타내야 한다. 만약 Author와 Post List를 가져오는 API가 있다고 가정해보자. 우리는 이 기능을 지원하기 위해 Author Type과 Post Type을 정의해야 한다. code first 방식을 사용한다면, 데코레이터와 Typescript Class를 이용해서 다음과 같이 정의할 수 있다.

import { Field, Int, ObjectType } from '@nestjs/graphql';
import { Post } from './post';

@ObjectType()
export class Author {
  @Field(type => Int)
  id: number;

  @Field({nullable: true})
  firstName?: string;

  @Field({nullable: true})
  lastName?: string;

  @Field(type => [Post])
  posts: Post[];
}

위와 같이 만든 Author 클래스를 아래처럼 Resolver에서 사용할 수도 있다.

import { Resolver, Query } from '@nestjs/graphql';
import { Author } from './entities/author.entity';

@Resolver()
export class Resolver {
  @Query(returns => [Author])
  getAllAuthor() {
    return [{ name: "example1" }, { name: "example2" }];
  }
}

InputType과 ArgsType

InputTypeArgsType 모두 Query혹은 Mutation에서 Argument들을 받고자할 때 사용할 수 있다. 두 개의 차이점은 코드를 작성할 때와 GraphQL 요청을 보낼 때 나타난다.

코드를 작성할 때 차이점

둘다 @Args() 데코레이터를 사용한다. 그런데 @Args()의 인자로 이름을 넣어주냐 안넣어주냐에서 차이가 있다. InputType을 사용할 경우, @Args()의 인자로 args의 이름(string)을 넣어주어야한다. ArgsType을 사용할 경우, @Args()의 인자로 args의 이름을 넣지 않아도 된다.

InputType을 사용할 때

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

@InputType()
export class AuthorArgs {
  @Field()
  firstName: string;

  @Field()
  lastName: string;
}
import { Resolver, Query } from '@nestjs/graphql';
import { AuthorArgs } from "./dtos/author.dto";

@Resolver()
export class Resolver {
  @Query(returns => Boolean)
  createAuthor(@Args('example') args: AuthorArgs) {
    return true;
  }
}

ArgsType을 사용할 때

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

@ArgsType()
export class AuthorArgs {
  @Field()
  firstName: string;

  @Field()
  lastName: string;
}
import { Resolver, Query } from '@nestjs/graphql';
import { AuthorArgs } from "./dtos/author.dto";

@Resolver()
export class Resolver {
  @Query(returns => Boolean)
  createAuthor(@Args() args: AuthorArgs) {
    return true;
  }
}

GraphQL 요청을 보낼 때 차이점

InputType@Args()에 넘겨준 args의 이름으로 하나의 객체를 보내고, ArgsType은 각각의 Field를 따로따로 보낸다.

InputType을 사용할 때

{
  createAuthor(example: { firstName: "Brendan", lastName: "Eich" })
}

ArgsType을 사용할 때

{
  createAuthor(firstName: "Brendan", lastName: "Eich")
}

0개의 댓글