Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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!
Owner

stubailo commented Oct 2, 2016

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