처음부터 차근차근

[NestJS] NestJS에서 GraphQL 초기 설정 본문

FrameWork/NestJS

[NestJS] NestJS에서 GraphQL 초기 설정

HangJu_95 2023. 11. 29. 13:49
728x90

GraphQL이란?

GraphQL에 대한 상세한 설명이 적혀 있습니다.

 

[GraphQL] GraphQL이란?

GraphQL이란? GraphQL은 API를 위한 쿼리 언어이며 이미 존재하는 데이터로 쿼리를 수행하기 위한 런타임 입니다. GraphQL은 API에 있는 데이터에 대한 완벽하고 이해하기 쉬운 설명을 제공하고 클라이

hangju95.tistory.com

GraphQL installation

GraphQL을 사용하기 위해선 아래에 있는 패키지가 필요합니다.

# For Express and Apollo (default)
$ npm i @nestjs/graphql @nestjs/apollo @apollo/server graphql

NestJS에서는 두 가지 방법으로 GraphQL을 build할 수 있도록 제공하고 있습니다.

  1. Code first : 데코레이터와 TS의 Class를 퉁해 GraphQL schema를 생성합니다.
  2. schema first : GraphQL SDL이 능숙한 사람은 이것을 통해 작성합니다. 이를 통해 TypeScript definition을 자동으로 생성합니다.

저는 Code를 통해 Class를 작성하고, 데코레이터를 통해 Schema를 생성하는 방법을 채택했습니다.

 

import GraphQL

GraphQL을 사용하기 위해서는 루트 모듈에 GraphModule을 Import해야 합니다.

해당 방법은 Class와 데코레이터를 통해 Schema를 작성하기 때문에 autoSchemaFile을 속성에 추가해줘야 합니다.

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';

@Module({
  imports: [
    // GraphQL을 사용하기 위한 초기 설정
    GraphQLModule.forRoot<ApolloDriverConfig>({
      // 서버는 apollo 서버를 사용
      driver: ApolloDriver,
      // playground: RestAPI에서 postman, swagger와 같은 존재.
      // local, dev 환경에서는 true로 해두자.
      playground: true,
      // 스키마자동 생성 진행
      // schema를 Entity나 DTO를 통해 자동으로 읽어, gql 파일 생성
      autoSchemaFile: join(process.cwd(), 'schema.gql'),
    }),
  ],
})
export class AppModule {}

 

'FrameWork > NestJS' 카테고리의 다른 글

[NestJS] GraphQL Mutation  (1) 2023.11.30
[NestJS] GraphQL Resolvers  (0) 2023.11.29
[NestJS] 제어 역전과 의존성 주입  (1) 2023.11.29
[NestJS] Custom decorator  (0) 2023.11.28
[NestJS] Exception filter  (0) 2023.11.28