graphql

설명
Tags
 

Quick Start

 

AppModule에 GraphQLModule 추가

graphql에서 AppModule이 루트 모듈이며, 모든 모듈이 AppModule로 모여야 한다.
따라서 GraphQLModule도 AppModule에 추가해줘야함.
import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { AppController } from './app.controller'; import { AppService } from './app.service'; @Module({ imports: [GraphQLModule.forRoot()], controllers: [AppController], providers: [AppService], }) export class AppModule {}
The GraphQLModule can be configured to use Apollo server (with the @nestjs/apollo driver) and Mercurius (with the @nestjs/mercurius)
GraphQL은 Apollo server를 통한다.
 

Code First

Schema first 방식과 Code First 방식을 택할 수 있는데, 타입스크립트로 작성하는 강점을 이용하고자 Code First를 채택함.
GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: join(process.cwd(), 'src/schema.gql'), }),
위와 같이 app.module.ts 파일에서 GraphQLModule.forRoot() 코드를 수정해줘야 함.
 
  1. nest g mo <모듈명> 로 모듈을 만들고
  1. 다음과 같이 작성함.
// restaurants.module.ts import { Module } from '@nestjs/common'; import { RestaurantResolver } from './restaurants.resolver'; @Module({ providers: [RestaurantResolver], }) export class RestaurantsModule {}
  1. resolver를 작성함
// restaurants.resolver.ts import { Query, Resolver } from '@nestjs/graphql'; @Resolver() export class RestaurantResolver { @Query(() => Boolean) // graphql generator를 위한 것 isPizzaGood(): boolean { // 여기의 : boolean 반환값 명시는 typescript를 위한 것 return true; } }
  1. 쿼리가 생성된 것을 볼 수 있다.
notion image

유의

  • @InputType() 데코레이터를 사용한다면, @Args(’여기에 이름을 반드시 명시’) 인자명을 반드시 지정해야 한다.
  • @ArgsType() 데코레이터를 사용한다면 @Args() 이렇게 이름을 비워둬야함.