Graphql-yoga

👊0👊·2020년 1월 5일
4

graphql 정리

목록 보기
2/2

들어가기 전에

이번 프로젝트에서 GraphQL을 사용하려고 했는데, prisma tutorial을 참고하다가 graphql-yoga라는 것을 사용해서 서버를 돌렸다. 일단 서버를 만들어 배포를 했는데, 무슨 도구인지 몰라서 이번에 정리 좀 하려한다.

개요

  • Graphql 서버를 실행하게 도와준다. : 합리적인 기본값과 최소 설정을 포함한다.
  • Subscriptions을 포함한다 : 웹 소켓으로 기본적으로 구현해서 따로 구현할 필요없게 해줌
  • 호환 가능 : Graphql client(Apollo, Relay...)에 상관없이 동작한다.

본문

즉 graphql-yoga는 graphql 서버를 쉽게 실행 시켜주는 도구라고 할 수 있다.
Grpahql-yoga는 아래의 도구를 설정되있어서 따로 설정할 필요가 없다.

  • express/ apollo-server
  • graphql-subscriptions/ subscriptions-transport-ws
  • graphql.js/ graphql-tools
  • graphql-playground

예제코드를 보면 매우 간단하다

import { GraphQLServer } from 'graphql-yoga'
// ... or using `require()`
// const { GraphQLServer } = require('graphql-yoga')

const typeDefs = `
  type Query {
    hello(name: String): String!
  }
`

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || 'World'}`,
  },
}

const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000')

subscription 구현또한 간단하다. typedefs, resolvers에 subscription을 만들고 PubSub을 생성하여 server에 등록해주면 끝이다.

...
const resolvers = {
  Query: {
    hello: () => `Hello`,
  },
  Counter: {
    countStr: counter => `Current count: ${counter.count}`,
  },
  Subscription: {
    counter: {
      subscribe: (parent, args, { pubsub }) => {
        const channel = Math.random().toString(36).substring(2, 15) // random channel name
        let count = 0
        setInterval(() => pubsub.publish(channel, { counter: { count: count++ } }), 2000)
        return pubsub.asyncIterator(channel)
      },
    }
  },
}

const pubsub = new PubSub()
const server = new GraphQLServer({ typeDefs, resolvers, context: { pubsub } })
...

정리

위에서 말한 것 처럼 graphql-yoga는 graphql 서버를 쉽게 실행 시켜주는 도구라고 할 수 있다.

듀토리얼을 구현한 저장소(zeit now + prisma + graphql-yoga)
https://github.com/mindshareteam/backend

.
├── README.md
├── now.json # now zeit 배포 설정파일
├── package-lock.json 
├── package.json
├── prisma # prisma datamodel 관련 폴더
│   ├── datamodel.prisma # prisma datamoel
│   ├── prisma.yml # prisma server setting
│   ├── seed.js # 기본 데이타
│   └── test.prisma # test 용임
└── src
    ├── generated # 자동 생성된 prisma-client
    │   └── prisma-client
    │       ├── index.d.ts
    │       ├── index.js
    │       └── prisma-schema.js
    ├── index.js # 서버가 코딩되어 있음
    ├── resolvers # resolver 관련 폴더
    │   ├── index.js
    │   ├── mutations # mutions 관련 폴더 
    │   │   └── index.js
    │   └── queries # queries 관련 폴더
    │       └── index.js
    └── schema.graphql # typedefs 파일
profile
ㅎㅎ

0개의 댓글