Skip to content

Instantly share code, notes, and snippets.

@stubailo
Last active October 12, 2020 22:40
Show Gist options
  • Save stubailo/3c33afb38dc1322d58129cc6db35bdc3 to your computer and use it in GitHub Desktop.
Save stubailo/3c33afb38dc1322d58129cc6db35bdc3 to your computer and use it in GitHub Desktop.
A very basic demo of GraphQL subscriptions with the graphql-subscriptions package
// 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!
@stubailo
Copy link
Author

stubailo commented Oct 2, 2016

@stubailo
Copy link
Author

stubailo commented Oct 7, 2016

@drFabio
Copy link

drFabio commented Oct 27, 2016

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