GraphQL Subscriptions with JavaScript and Apollo Server

Let’s Start

Step 1: Set up a new Node project and Install Dependencies

npm init -y
npm i graphql
npm i apollo-server-express
npm i graphql-subscriptions
npm i subscriptions-transport-ws
npm i @graphql-tools/schema
“scripts”: {“test”: “echo \”Error: no test specified\” && exit 1",“start”: “node index.js”},

Step 2: Set up the server

const { createServer } = require(“http”);
const express = require(“express”);
const { execute, subscribe } = require(“graphql”);
(async () => {     const app = express();     const httpServer = createServer(app);})();

Step 3: Set up a Pub Sub Instance

const { PubSub } = require(“graphql-subscriptions”);
const pubsub = new PubSub();

Step 4: Define the GraphQL Schema

const typeDefs = gql`    type Query {
viewMessages: [Message!]
}
type Mutation {
sendMessage(name: String, content: String): Message!
}
type Subscription {
receiveMessage: Message!
}
type Message {
id: ID!
name: String!
content: String
}`;

Step 5: Add Resolvers

let messages = []const resolvers = {
Query: {
viewMessages() {
return messages;
},
},
Mutation: {
sendMessage: (parent, { name, content }) => {
const id = messages.length;
var new_message = {
id,
name,
content
}
messages.push(new_message);
pubsub.publish(“MessageService”, {receiveMessage: new_message});
return new_message;
},
},
Subscription: {
receiveMessage: {
subscribe:()=> pubsub.asyncIterator([“MessageService”]),
},
},
};

Step 6: Enable the Subscriptions

const { ApolloServer, gql } = require(“apollo-server-express”);
const { SubscriptionServer } =require(“subscriptions-transport-ws”);
const { makeExecutableSchema } = require(“@graphql-tools/schema”);
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = new ApolloServer({schema,});
await server.start();
server.applyMiddleware({ app });
SubscriptionServer.create({ schema, execute, subscribe },{ server: httpServer, path: '/graphql'});

Step 7: Listen for the Requests

const PORT = 4000;httpServer.listen(PORT, () => {console.log(`Query endpoint ready at http://localhost:${PORT}${server.graphqlPath}`);console.log(`Subscription endpoint ready at ws://localhost:${PORT}${server.graphqlPath}`);});

Step 8: Testing the Subscriptions

npm start
subscription receive {
receiveMessage{
id
name
content
}
}
mutation send {
sendMessage(name: “User”, content: “Hello”){
id
name
content
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store