Apollo server에 원하는 세팅을 보낼 수 있다.
typeDefs
DocumentNode or Array<DocumentNode> |
Required. Document or documents that represent your server's GraphQL schema, generated by applying the gql tag to valid Schema Definition Language (SDL) strings. |
resolvers
Object or Array |
Required. A map of functions that populate data for individual schema fields. Can also be an array of multiple maps that are merged. |
세팅을 하는 방법에는 Code first와 Schema first가 있는데 Schema first로 하면 typescript파일을 만들고 graphql를 작성해야 한다. 하지만 Code first의 경우에는 typescript 힘을 빌려서 schema를 자동으로 생성하게 해준다.
Code first 코드를 복사해서 forRoot 함수 안에 복사 붙여넣기를 한다.
추가 후 실행 시 아래와 같은 에러가 발생한다.
GraphQLError [Object]: Query root type must be provided.
GraphQLModule이 스키마를 생성하기 위해서 query와 mutation을 찾았지만 없어서 에러를 발생 시켰다.
nest g mo restaurants 명령어를 통해 restaurants directory와 module을 설치한다.
restaurants.resolver.ts 파일을 만들고 아래 코드를 입력한다.
import { Resolver } from "@nestjs/graphql";
@Resolver()
export class RestaurantsResolver {}
restaurants.module.ts는 아래 코드를 추가한다.
import { Module } from '@nestjs/common';
import { RestaurantsResolver } from './restaurants.resolver';
@Module({
providers: [RestaurantsResolver]
})
export class RestaurantsModule {}
여기까지 왔어도 에러가 안 없어진다. 쿼리를 생성하지 않았기 때문이다.
쿼리를 생성하기 위해 restaurants.resolver.ts의 클래스 안에 @Query decorator를 사용한다.
설명을 보면 (alias)Query(typeFucc: ReturnTypeFunc, options?: QueryOptions): MethodDecorator(+2 overloads)라고 쓰여져 있다.
즉, Query가 return하는 타입은 Return function이여야 한다.
import { Query, Resolver } from "@nestjs/graphql";
@Resolver()
export class RestaurantsResolver {
@Query(returns => Boolean) // GraphQL을 위함 Boolean은 필수
isPizzaGood(): Boolean { // 타입스크립트를 위함 : Boolean은 옵션
return true;
}
}
npm run start:dev를 실행하고 있다면 main.ts 아래 schema.gql이 만들어진다. 이 파일을 지운다.
지우는 이유는 가끔 필요 없을 때가 생기기 때문이다. 메모리로부터 파일을 생성하도록 한다.
app.module.ts에서 autoSchemaFile: true로 변경하면 직접 파일을 가지고 있지 않아도 된다.
localhost:3000에 접속하면 404 에러가 난다. controller를 포함한 모두를 지웠기 때문이다.
localhost:3000/graphql로 접속하면 isPizzaGood schema를 볼 수 있다.
'Uber Eats' 카테고리의 다른 글
Uber Eats # 5 Arguments, Mutation (0) | 2021.03.06 |
---|---|
Uber Eats # 4 entity ObjectType (0) | 2021.03.06 |
Uber Eats # 2 graphql (0) | 2021.03.06 |
Uber Eats # 1 nest, gitignore, github (0) | 2021.03.06 |
# 3-1 NestJS - 구조 파악하기 (0) | 2021.02.11 |