Last active
October 12, 2020 22:40
-
-
Save stubailo/3c33afb38dc1322d58129cc6db35bdc3 to your computer and use it in GitHub Desktop.
A very basic demo of GraphQL subscriptions with the graphql-subscriptions package
This file contains 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
// npm install graphql graphql-tools graphql-subscriptions | |
const { PubSub, SubscriptionManager } = require('graphql-subscriptions'); | |
const { makeExecutableSchema } = require('graphql-tools'); | |
// Our "database" | |
const messages = []; | |
// Minimal schema | |
const typeDefs = ` | |
type Query { | |
messages: [String!]! | |
} | |
type Subscription { | |
newMessage: String! | |
} | |
`; | |
// Minimal resolvers | |
const resolvers = { | |
Query: { messages: () => messages }, | |
// This just passes through the pubsub message contents | |
Subscription: { newMessage: (rootValue) => rootValue }, | |
}; | |
// Use graphql-tools to make a GraphQL.js schema | |
const schema = makeExecutableSchema({ typeDefs, resolvers }); | |
// Initialize GraphQL subscriptions | |
const pubsub = new PubSub(); | |
const subscriptionManager = new SubscriptionManager({ schema, pubsub }); | |
// Run a subscription | |
subscriptionManager.subscribe({ | |
query: ` | |
subscription NewMessageSubscription { | |
newMessage | |
} | |
`, | |
callback: (err, result) => | |
console.log(`New message: ${result.data.newMessage}`), | |
}); | |
// Create a message | |
const helloWorldMessage = 'Hello, world!'; | |
// Add it to "database" | |
messages.push(helloWorldMessage); | |
// Push it over pubsub, this could be replaced with Redis easily | |
pubsub.publish('newMessage', helloWorldMessage); | |
// Prints "New message: Hello, world!" in the console via the subscription! |
Author
stubailo
commented
Oct 2, 2016
- Introduction to the subscriptions architecture: https://medium.com/apollo-stack/graphql-subscriptions-in-apollo-client-9a2457f015fb#.ay1o7ukim
- How to wire it up to Redis: https://medium.com/apollo-stack/graphql-subscriptions-with-redis-pub-sub-f636fc84a0c4#.6voou0vhf
- New post coming soon, about how the underlying pieces fit together!
Here's the new post about this generic subscription implementation: https://medium.com/apollo-stack/a-proposal-for-graphql-subscriptions-1d89b1934c18?source=linkShare-803918030a60-1475857435
Just used this post to realize I did not added a schema resolver, is there a way to have a subscriptio default resolver that just return root?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment