Implementing GraphQL Subscriptions for Real-Time Data Updates in JavaScript


In today's fast-paced world, real-time data updates are becoming increasingly crucial for modern web applications. One popular solution for achieving real-time functionality is GraphQL subscriptions. In this article, we will explore how to implement GraphQL subscriptions in JavaScript, providing code examples, explanations, and a comprehensive understanding of the topic.

Understanding GraphQL Subscriptions

GraphQL is an open-source query language for APIs and a runtime for executing these queries with existing data. It allows clients to request specific data from the server, enabling efficient and flexible communication between the client and the server. While GraphQL queries and mutations are used for retrieving and manipulating data, GraphQL subscriptions enable real-time data updates by establishing a persistent connection between the client and server.

Setting Up the Environment

To get started, we need a JavaScript environment and a GraphQL server. For the purpose of this article, we'll use Node.js and the Apollo Server library, a popular choice for building GraphQL servers in JavaScript. Ensure you have Node.js installed before proceeding.

Installing Dependencies

Let's create a new project and install the necessary dependencies −

mkdir graphql-subscriptions
cd graphql-subscriptions
npm init -y
npm install apollo-server graphql

Explanation

In this step, we set up the project directory and use npm to initialize a new project. We then install the required dependencies, including Apollo Server and the GraphQL library.

Defining the Schema

Next, let's create a file named schema.js and define a simple GraphQL schema −

// schema.js

const { gql } = require('apollo-server');

const typeDefs = gql`
   type Post {
      id: ID!
      title: String!
      content: String!
   }

   type Query {
      posts: [Post!]!
   }

   type Mutation {
      createPost(title: String!, content: String!): Post!
   }

   type Subscription {
      newPost: Post!
   }
`;

module.exports = typeDefs;

Explanation

In this code snippet, we import the necessary dependencies from Apollo Server and define our GraphQL schema using the gql tag. We define a Post type with id, title, and content fields. Additionally, we define a Query type for retrieving posts, a Mutation type for creating posts, and a Subscription type for receiving real-time updates on new posts.

Implementing GraphQL Subscriptions

With the schema in place, let's now implement the resolver functions for the Query, Mutation, and Subscription types.

In this example, we'll use an in-memory array to store posts.

Creating the Resolvers

In a new file named resolvers.js, add the following code −

// resolvers.js

const posts = [];

const resolvers = {
   Query: {
      posts: () => posts,
   },
   Mutation: {
      createPost: (_, { title, content }) => {
         const newPost = { id: posts.length + 1, title, content };
         posts.push(newPost);
         return newPost;
      },
   },
   Subscription: {
      newPost: {
         subscribe: (_, __, { pubsub }) => pubsub.asyncIterator('NEW_POST'),
      },
   },
};

module.exports = resolvers;

Explanation

In this code snippet, we define the resolver functions for the different GraphQL types. The Query resolver for the posts field returns the posts array. The Mutation resolver for createPost adds a new post to the posts array and returns the newly created post. Finally, the Subscription resolver for newPost sets up a subscription and uses the pubsub object to asynchronously listen for new posts.

Configuring the Server

Now, let's configure the Apollo Server in a new file named server.js −

// server.js

const { ApolloServer, PubSub } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const pubsub = new PubSub();

const server = new ApolloServer({
   typeDefs,
   resolvers,
   context: () => ({ pubsub }),
});

server.listen().then(({ url }) => {
   console.log(`Server ready at ${url}`);
});

Explanation

In this code snippet, we import the necessary dependencies from Apollo Server and the schema and resolver files we created earlier. We instantiate a PubSub object from Apollo Server to handle the pub-sub functionality required for subscriptions. We then configure the Apollo Server with the schema, resolvers, and context containing the pubsub object. Finally, we start the server and log the URL where it's running.

Testing GraphQL Subscriptions

Subscribing to New Posts −

With the server running, open a new terminal and execute the following subscription query using a GraphQL client like GraphiQL or Apollo Client:

subscription {
   newPost {
      id
      title
      content
   }
}

Explanation

This subscription query sets up a subscription to listen for new posts. It requests the id, title, and content fields of new posts.

Publishing New Posts

Now, in another terminal, execute the following mutation to publish a new post −

Example

mutation {
   createPost(title: "Hello, World!", content: "This is my first post.")
   {
      id
      title
      content
   }
}

Explanation

This mutation creates a new post with a title of "Hello, World!" and the content of "This is my first post." The mutation returns the id, title, and content fields of the newly created post.

Output

After executing the mutation, you should see the newly created post being emitted to the subscription tab. The output in the subscription tab will look something like this −

{
   "data": {
      "newPost": {
         "id": "1",
         "title": "Hello, World!",
         "content": "This is my first post."
      }
   }
}

Conclusion

In this article, we explored how to implement GraphQL subscriptions in JavaScript. We discussed the importance of real-time data updates, set up a GraphQL server using Apollo Server, and demonstrated how to define the schema, resolvers, and subscriptions. By following the steps provided, you can integrate GraphQL subscriptions into your JavaScript applications and enable real-time functionality for improved user experiences.

Updated on: 25-Jul-2023

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements