이번 프로젝트에서 GraphQL을 사용하려고 했는데, prisma tutorial을 참고하다가 graphql-yoga라는 것을 사용해서 서버를 돌렸다. 일단 서버를 만들어 배포를 했는데, 무슨 도구인지 몰라서 이번에 정리 좀 하려한다.
즉 graphql-yoga는 graphql 서버를 쉽게 실행 시켜주는 도구라고 할 수 있다.
Grpahql-yoga는 아래의 도구를 설정되있어서 따로 설정할 필요가 없다.
예제코드를 보면 매우 간단하다
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 파일