Suscriptions with GraphQL and Node JS
2 min readSep 26, 2020
Learn how to use subscriptions with Node JS in GraphQL
Backend
1) Installation of dependencies
npm i nodemon apollo-server
2) Apollo server creation
import { ApolloServer } from "apollo-server";const server = new ApolloServer({
typeDefs,
resolvers,
});// The `listen` method launches a web server.
server.listen().then(({ url, subscriptionsUrl }) => {
console.log(`🚀 Server ready at ${url}`);
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
});
3) Typedefs
const typeDefs = gql` type Subscription {
postAdded: Post
} type Query {
posts: [Post]
} type Mutation {
addPost(author: String, comment: String): Post
} type Post {
author: String
comment: String
}
`;
Resolvers and Queries
const typeDefs = gql`type Subscription {
postAdded: Post
}type Query {
posts: [Post]
}type Mutation {
addPost(author: String, comment: String): Post
}type Post {
author: String
comment: String
}
`;const posts = [
{
author: "Nelson",
comment: "Hello",
},
{
author: "Steve",
comment: "Hello GraphQL",
},
];const POST_ADDED = "POST_ADDED";const resolvers = {
Subscription: {
postAdded: {
// Additional event labels can be passed to asyncIterator creation
subscribe: () => pubsub.asyncIterator([POST_ADDED]),
},
}, Query: {
posts() {
return posts
},
}, Mutation: {
addPost(_, args) {
//Execute event
pubsub.publish(POST_ADDED, { postAdded: args });
posts.push(args)
return args
},
},
};const server = new ApolloServer({
typeDefs,
resolvers,
});
Finally
const POST_ADDED = "POST_ADDED";const resolvers = {
Subscription: {
postAdded: {
// Additional event labels can be passed to asyncIterator creation
subscribe: () => pubsub.asyncIterator([POST_ADDED]),
},
},Query: {
posts() {
return posts
},
},Mutation: {
addPost(_, args) {
//Execute event
pubsub.publish(POST_ADDED, { postAdded: args });
posts.push(args)
return args
},
},
};const server = new ApolloServer({
typeDefs,
resolvers,
});// The `listen` method launches a web server.
server.listen().then(({ url, subscriptionsUrl }) => {
console.log(`🚀 Server ready at ${url}`);
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
});
Repository in Github https://github.com/nelson-Web/nodejs-graphql-suscriptions