Part 8 from series: How to build a real-time chat app

GraphQL Subscriptions

Create a GraphQL Subscription to send real-time message notifications

We can retrieve a list of messages and create messages with our GraphQL API from our Angular app. Now we need a way of subscribing and instantly notifying all apps of when a message gets sent using a subscription.

We will use GraphQL Subscriptions to achieve this, which use websockets under the hood.

Add the subscription to our schema

We're going to add a Subscription to our schema to describe events we're interested in such as when a new message has been added.

Within your project folder, open the file web-api/index.js and add these new lines within middle of the document to the typeDefs constant:

File path icon web-api/index.js
// Existing code...

const typeDefs = gql`
  # Existing code...

  type Mutation {
    # Existing code...
  }

  type Subscription { # <-- Add new subscription here
    messageAdded: Message
  }

  ${messageGQL}
  ${userGQL}
`;

// Existing code...

Review the websocket server

Apollo Server doesn't handle subscriptions itself. Instead we run a separate websocket server alongside our HTTP server, which uses the graphql-ws protocol and the same schema as our Apollo Server. The boilerplate project we cloned already sets this up in web-api/index.js, so you shouldn't need to add anything, but it's worth taking a look at how it works.

Near the top of the file, a WebSocketServer (from the ws package) is created and attached to the same HTTP server on the /graphql path:

File path icon web-api/index.js
// Existing code...

const wsServer = new WebSocketServer({
  server: httpServer,
  path: '/graphql'
});

// Existing code...

Then, inside our async setup function, the useServer function from graphql-ws connects this websocket server to our schema:

File path icon web-api/index.js
// Existing code...

  const serverCleanup = useServer({
    schema,
    context: (ctx) => {
      return {
        ...ctx,
        dataSources
      };
    }
  }, wsServer);

// Existing code...

The context function does the same job for websocket connections that our context function did for HTTP requests in the previous parts. It returns the data sources so that our resolvers can use our existing data source instances. The serverCleanup value is used by a plugin we pass to ApolloServer to shut the websocket server down cleanly when the HTTP server is drained.

Connect to Slack's Socket Mode

Before we can create our subscription, we first need to make a connection to Slack to be notified when messages are sent. Slack's Socket Mode lets our API open a websocket connection to Slack and receive events through it. We will use the Node Slack SDK again for this, along with the app-level token that we created in the setup guide.

Open the file web-api/slack/connection.js, then add the new SocketModeClient from the @slack/socket-mode module and the PubSub dependency from graphql-subscriptions to create a new instance.

File path icon web-api/slack/connection.js
const { WebClient } = require('@slack/web-api');
const { SocketModeClient } = require('@slack/socket-mode'); // <-- Add new import
const { PubSub } = require('graphql-subscriptions'); // <-- Add new import

let webAPI, socketModeClient; // <-- Define new variable

const pubsub = new PubSub(); // <-- Create new instance

// Existing code...

The PubSub module will give us a shared instance of an event generator. This will allow us to publish events to any subscribed clients any time an event of interest happens.

When Slack receives a message it will notify our GraphQL API through the use of the SocketModeClient instance, we will then need to notify all Angular apps connected to our API. This is done by publishing an event through the PubSub instance. GraphQL will use the PubSub instance to publish the schema event messageAdded with the new message data.

Next we need to redefine the connect function to create a memoized connection to Slack's Socket Mode that we can reuse in our new subscriptions.

File path icon web-api/slack/connection.js
// Existing code...

async function connect({ appToken, botToken }) {
  webAPI = new WebClient(botToken);
  socketModeClient = new SocketModeClient({ // <-- Create new SocketModeClient instance with the app token
    appToken
  });

  await socketModeClient.start(); // <-- Boot SocketModeClient
}

function getConnection() {
  // Existing code...
}

// Existing code...

The function is async because starting the Socket Mode client opens a network connection, which we want to wait for before our server starts handling requests.

In order to retrieve a reference to our new connection with Slack from our subscriptions, we need to redefine the getConnection function to return the new SocketModeClient instance and also export the new shared PubSub instance.

File path icon web-api/slack/connection.js
// Existing code...

async function connect({ appToken, botToken }) {
  // Existing code...
}

function getConnection() {
  if(!webAPI || !socketModeClient /* <-- Check connection exists */) {
    throw Error('Slack connections not found');
  }

  return { webAPI, socketModeClient /* <-- Return new reference */ };
}

module.exports = { connect, getConnection, pubsub };

Now we need to make sure our server connects to Slack with both tokens. Back in web-api/index.js, our async setup function should connect to Slack first, before the schema is created with an appToken:

File path icon web-api/index.js
// Existing code...

(async () => {
  await slackConnection.connect({
    botToken: process.env.SLACK_RTM_ACCESS_TOKEN,
    appToken: process.env.SLACK_APP_TOKEN // <-- Add app token
  });

  const dataSources = {
    // Existing code...
  };

  // Existing code...
})();

We can now listen to new Slack notifications and publish new events of interest such as new sent messages within our subscriptions.

Create the Subscription resolver for Slack real-time messaging

Create and open the file web-api/api/slack-integration/resolvers/messages.messageAdded.subscription.js.

touch web-api/api/slack-integration/resolvers/messages.messageAdded.subscription.js

First we will need to import a few modules at the top of the file and define a couple of constants that will describe the connection.

File path icon web-api/api/slack-integration/resolvers/messages.messageAdded.subscription.js
const { pubsub, getConnection } = require('../../../slack/connection');
const slackMessageMap = require('../data-mappings/message');

const { socketModeClient } = getConnection();

const TOPIC = 'messageAdded';

Most of the imports should be familiar. The slackMessageMap we've used a couple of times previously. This will again be needed to transform Slack message data into a compatible model for when our schema publishes the data for a messageAdded event.

We get the Socket Mode client that we started with Slack (socketModeClient) and define the TOPIC of messageAdded, which we declared in our schema to describe new events we're interested in.

We need to define an event handler that will handle the Slack response for when a new message is created. Then control when this method gets called by setting up a listener with the client's on method.

File path icon web-api/api/slack-integration/resolvers/messages.messageAdded.subscription.js
// Existing code...

async function onMessageHandler(response) { // <-- Add new handler function
  await response.ack();

  const slackEvent = response.body.event;

  if (slackEvent && slackEvent.type === 'message') {
    if (slackEvent.subtype) {
      return;
    }

    await pubsub.publish(TOPIC, {
      [TOPIC]: slackMessageMap(response.event),
      channelId: response.event.channel
    });
  }
}

socketModeClient.on('message', onMessageHandler); // <-- Listen to Slack message events

The onMessageHandler function will get called when the Slack client emits a new message from the API. Slack expects every event it sends over Socket Mode to be acknowledged, so the first thing we do is await response.ack(). If we don't, Slack assumes the event wasn't delivered and may send it again.

Slack also sends events for things we're not interested in, such as message edits or deletions and "user joined the channel" notices. These events have a subtype, so we ignore them and only handle ordinary messages.

For ordinary messages, we call publish on the pubsub instance to publish a new messageAdded event. For the second parameter to pubsub.publish, we define a payload object to hold message data with each new publication. This will map the message data sent from Slack to our schema compatible message model [TOPIC]: slackMessageMap(response.event). We also include the channelId the message was sent to, which will be useful if you later want to support more than one conversation.

After the handler, add the pubsub async iterator function to our module exports.

File path icon web-api/api/slack-integration/resolvers/messages.messageAdded.subscription.js
// Existing code...

module.exports = {
  subscribe: () => pubsub.asyncIterator(TOPIC)
};

The properties on the export function will plug in to our schema and allow our Angular app to connect to the asyncIterator over a websocket connection for real-time notifications. We just need to add our subscription resolver to our resolver export bundle.

Open the file web-api/index.jsand add the following lines:

File path icon web-api/index.js
// Existing code...

const schema = makeExecutableSchema({
  // Existing code...
  resolvers: {
    Query: {
      // Existing code...
    },

    Mutation: { // <-- New property to add
      // Existing code...
    },

    Subscription: { // <-- Add the new subscription resolver
      messageAdded: require('./api/slack-integration/resolvers/messages.messageAdded.subscription')
    },
  }
});

Note: An inline require is used here to ensure that the Slack connection is created before attempting to get and use the connection. This is just for convenience purposes in our example application so that we can attach the default export subscription directly to the resolver tree but better practice would be to separate initialising the connection from exporting the module.

Restart your API (with the SLACK_APP_TOKEN and SLACK_RTM_ACCESS_TOKEN environment variables from the setup guide set).

We now have everything we need for our Angular app to connect to our GraphQL subscription, we'll add this in the next part.