webpubsub-apollo-subscription
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-beta-2 • Public • Published

webpubsub-apollo-experimental

Introduction

Microsoft Azure Web PubSub is a real-time messaging cloud service.

In GraphQL, subscriptions are long-lasting GraphQL read operations that can update their result whenever a particular server-side event occurs. And it is usually implemented with WebSocket protocol.

This package helps developers use Microsoft Azure WebPub service to avoid server-side maintenance of WebSocket connections between users clients and GraphQL server caused by subscriptions query from clients.

Let's show how to apply the package into the subscription sample provided by Apollo GraphQL.

Get the subscription sample

[!NOTE]

Please Note that this document is based on sample commit 50808f11c5, the latest version as of the time of writing the document.

git clone https://github.com/apollographql/docs-examples
cd docs-examples
git checkout 50808f11c5cfeaf02
cd apollo-server/v3/subscriptions
yarn install

Add the webpubsub-apollo-subscription package

Since the original sample uses yarn, to keep consistency, we use yarn to add the package.

yarn add webpubsub-apollo-subscription

Update index.js to use the package

  1. import WebPubSubServerAdapter:
const { WebPubSubServerAdapter } = require("webpubsub-apollo-subscription");
  1. Update SubscriptionServer.create to use a WebPubSubServerAdapter instance Note that we read the connection string from environment. Connection string is used to connect to Azure Web PubSub and we will get the value in later steps.

    const serverAdapter = new WebPubSubServerAdapter(
      {
        connectionString: process.env.WebPubSubConnectionString,
        hub: "graphql_subscription",
        path: "/graphql_subscription",
      },
      app
    );
    SubscriptionServer.create({ schema, execute, subscribe }, serverAdapter);
  2. Also print out subscription endpoint and event handler endpoint Add the logs after httpServer starts. These endpoints will be used in later setup.

    serverAdapter.getSubscriptionPath().then((v) => {
      console.log(`🚀 Subscription endpoint ready at ${v}`);
      console.log(
        `🚀 Event handler listens at http://localhost:${PORT}${serverAdapter.path}`
      );
    });

The complete code change can be found here.

Setup the Azure Web PubSub resource and configurations

1. Create a Azure Web PubSub service

Follow the instruction to create an Azure Web PubSub service.

Get the ConnectionString of the service for later use:

az webpubsub key show --name "<your-unique-resource-name>" --resource-group "myResourceGroup" --query primaryConnectionString

Copy the fetched ConnectionString and it will be used later in this article as the value of <connection_string>.

2. Run the local demo

Run the below command with <connection_string> replaced by the value fetched in the above step:

SET WebPubSubConnectionString=<connection_string>
yarn start

The console log shows the exposed endpoints:

🚀 Query endpoint ready at http://localhost:4000/graphql
🚀 Subscription endpoint ready at wss://<your-unique-resource-name>.webpubsub.azure.com/client/hubs/graphql_subscription
🚀 Event handler listens at http://localhost:4000/graphql_subscription/

The console log shows that the exposed endpoint for Azure Web PubSub event handlers is http://localhost:4000/graphql_subscription/. Let's expose this local endpoint to public so that the Azure Web PubSub can redirect traffic to your localhost.

Use ngrok to expose your local endpoint

ngrok http 4000 

Then you'll get a forwarding endpoint http://<your-ngrok-id>.ngrok.io like http://e27c-167-220-255-102.ngrok.io

Configure event handlers

Since GraphQL has its own Authentication logic, graphql_subscription hub can allow anonymous connect and delegate all the event handling to the upstream. Setting the event handler through Azure CLI with below command:

az webpubsub hub create --hub-name graphql_subscription --name "<your-unique-resource-name>" --resource-group "myResourceGroup" --allow-anonymous --event-handler url-template=http://<your-ngrok-id>.ngrok.io/{hub}/{event} user-event-pattern=* system-event=connect system-event=disconnected system-event=connected

Open GraphQL Explorer and update the subscription URL

  1. Open http://localhost:4000/graphql and click Query your server, click the top settings gear, and update the subscription URL to the Web PubSub endpoint wss://<your-unique-resource-name>.webpubsub.azure.com/client/hubs/graphql_subscription.

Set the subscription URL to use the Web PubSub endpoint.

  1. Update the operations to query the incremental number and run:
subscription IncrementingNumber {
  numberIncremented
}

You can see that the subscription updates are consistently pushed to the GraphQL clients through the WebSocket connection.

Run the subscription operation to use the Web PubSub endpoint.

Check the internals of the package here:

Package Sidebar

Install

npm i webpubsub-apollo-subscription

Weekly Downloads

0

Version

1.0.0-beta-2

License

MIT

Unpacked Size

866 kB

Total Files

36

Last publish

Collaborators

  • vicancy