Created
April 1, 2018 19:49
-
-
Save annibuliful/bfb8a63f861a05fdff35ce5abc890d14 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const fastify = require('fastify')() | |
const { | |
makeExecutableSchema | |
} = require('graphql-tools') | |
const { | |
graphqlFastify, | |
graphiqlFastify | |
} = require('./') | |
const { | |
PubSub | |
} = require('graphql-subscriptions') | |
const pubsub = new PubSub(); | |
const { | |
SubscriptionServer | |
} = require('subscriptions-transport-ws') | |
const { | |
execute, | |
subscribe | |
} = require('graphql') | |
const typeDefs = ` | |
type Query { | |
hello: String, | |
hellos: [String] | |
} | |
type Subscription { | |
itemAdded: String | |
} | |
type Mutation { | |
addItem(id: ID!, title: String!, status: String): String | |
} | |
schema { | |
query: Query | |
mutation: Mutation | |
subscription: Subscription | |
} | |
` | |
const ITEM_ADDED = 'ITEM_ADDED'; | |
const resolvers = { | |
Query: { | |
hello: () => 'world', | |
hellos: () => ['hola', 'hello', 'aloha'] | |
}, | |
Mutation: { | |
addItem(root, { id, title, status }, context) { | |
const item = { | |
id, | |
title, | |
status, | |
created_at: new Date() | |
}; | |
pubsub.publish(ITEM_ADDED, { itemAdded: item }); | |
return item; | |
}, | |
}, | |
Subscription: { | |
itemAdded: { | |
subscribe: () => pubsub.asyncIterator(ITEM_ADDED), | |
} | |
} | |
} | |
const schema = makeExecutableSchema({ | |
typeDefs, | |
resolvers | |
}) | |
fastify | |
.register(graphqlFastify, { | |
schema, | |
printSchema: true | |
}) | |
.register(graphiqlFastify, { | |
endpointURL: '/', | |
prefix: '/graphiql' | |
}) | |
fastify.register(require('./'), { | |
graphql: { | |
schema | |
}, | |
graphiql: { | |
endpointURL: '/', | |
prefix: '/graphiql', | |
subscriptionsEndpoint: `ws://localhost:8000/subscriptions` | |
}, | |
prefix: '/v2' | |
}, err => { | |
if (err) { | |
throw err | |
} | |
}) | |
fastify.listen(8000, function (err) { | |
if (err) { | |
throw err | |
} | |
console.log(`listening on ${fastify.server.address().port}`) | |
}) | |
const subscriptionServer = SubscriptionServer.create({ | |
schema, | |
execute, | |
subscribe, | |
}, { | |
server: fastify.server, | |
path: '/graphql', | |
}, ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment