@aaronpowell/graphql-cosmosdb-subscriptions

A GraphQL subscription library that uses the CosmosDB change feed as the event source

Usage no npm install needed!

<script type="module">
  import aaronpowellGraphqlCosmosdbSubscriptions from 'https://cdn.skypack.dev/@aaronpowell/graphql-cosmosdb-subscriptions';
</script>

README

CosmosDB GraphQL Subscriptions npm - CosmosDB package

This package contains support for Apollo GraphQL Subscriptions, using the Azure CosmosDB Change Feed.

Installation

Install via npm or GitHub Packages:

gt; npm install --save @aaronpowell/graphql-cosmosdb-subscriptions

Usage

You'll need a SignalR Service account (if you don't have an Azure account sign up for free). Copy the connection string and provide it when you create an instance of SignalRPubSub:

import { CosmosDBPubSub } from "@aaronpowell/graphql-cosmosdb-subscriptions";

const cosmosPubSub = new CosmosDBPubSub(
  new CosmosClient(process.env.COSMOS_CONNECTION_STRING || "")
    .database(process.env.COSMOS_DB || "")
    .container(process.env.COSMOS_CONTAINER || "")
);

Unlike most pubsub libraries, you don't need to publish directly, messages are received when the Change Feed receives messages. When creating the subscription, you subscribe to a CosmosDB partition key value (in the below example type is the partition key and we're subscription when type = 'message').

export const resolvers = {
  Query: {
    async hello(parent, args, { dataSources }) {
      const text = `Message! ${Date.now()}`;
      await dataSources.messages.createOne({
        id: Date.now() + "",
        text,
        type: "message",
      });
      return text;
    },
  },
  Subscription: {
    getMessage: {
      subscribe: () => cosmosPubSub.asyncIterator(["message"]),
    },
  },
};