A graphql subscriptions implementation using redis and apollo's graphql-subscriptions
Switch branches/tags
greenkeeper/ioredis-4.0.0 greenkeeper/ioredis-4.0.1 greenkeeper/ioredis-4.0.2 greenkeeper/ioredis-4.1.0 greenkeeper/ioredis-4.2.0 greenkeeper/ioredis-4.3.0 greenkeeper/@types/ioredis-4.0.4 greenkeeper/@types/node-7.0.20 greenkeeper/@types/node-7.0.21 greenkeeper/@types/node-7.0.22 greenkeeper/@types/node-7.0.23 greenkeeper/@types/node-7.0.24 greenkeeper/@types/node-7.0.25 greenkeeper/@types/node-7.0.26 greenkeeper/@types/node-7.0.27 greenkeeper/@types/node-7.0.28 greenkeeper/@types/node-7.0.29 greenkeeper/@types/node-7.0.32 greenkeeper/@types/node-8.0.0 greenkeeper/@types/node-8.0.1 greenkeeper/@types/node-8.0.2 greenkeeper/@types/node-8.0.3 greenkeeper/@types/node-8.0.4 greenkeeper/@types/node-8.0.5 greenkeeper/@types/node-8.0.6 greenkeeper/@types/node-8.0.7 greenkeeper/@types/node-8.0.8 greenkeeper/@types/node-8.0.9 greenkeeper/@types/node-8.0.10 greenkeeper/@types/node-8.0.11 greenkeeper/@types/node-8.0.12 greenkeeper/@types/node-8.0.13 greenkeeper/@types/node-8.0.14 greenkeeper/@types/node-8.0.15 greenkeeper/@types/node-8.0.16 greenkeeper/@types/node-8.0.17 greenkeeper/@types/node-8.0.18 greenkeeper/@types/node-8.0.19 greenkeeper/@types/node-8.0.20 greenkeeper/@types/node-8.0.21 greenkeeper/@types/node-8.0.22 greenkeeper/@types/node-8.0.23 greenkeeper/@types/node-8.0.24 greenkeeper/@types/node-8.0.25 greenkeeper/@types/node-8.0.26 greenkeeper/@types/node-8.0.27 greenkeeper/@types/node-8.0.28 greenkeeper/@types/node-8.0.29 greenkeeper/@types/node-8.0.30 greenkeeper/@types/node-8.0.31 greenkeeper/@types/node-8.0.32 greenkeeper/@types/node-8.0.33 greenkeeper/@types/node-8.0.34 greenkeeper/@types/node-8.0.35 greenkeeper/@types/node-8.0.36 greenkeeper/@types/node-8.0.37 greenkeeper/@types/node-8.0.38 greenkeeper/@types/node-8.0.39 greenkeeper/@types/node-8.0.40 greenkeeper/@types/node-8.0.41 greenkeeper/@types/node-8.0.42 greenkeeper/@types/node-8.0.43 greenkeeper/@types/node-8.0.44 greenkeeper/@types/node-8.0.45 greenkeeper/@types/node-8.0.46 greenkeeper/@types/node-8.0.47 greenkeeper/@types/node-8.0.48 greenkeeper/@types/node-8.0.49 greenkeeper/@types/node-8.0.50 greenkeeper/@types/node-8.0.51 greenkeeper/@types/node-8.0.52 greenkeeper/@types/node-8.0.53 greenkeeper/@types/node-8.0.54 greenkeeper/@types/node-8.0.55 greenkeeper/@types/node-8.0.56 greenkeeper/@types/node-8.0.57 greenkeeper/@types/node-8.0.58 greenkeeper/@types/node-8.5.0 greenkeeper/@types/node-8.5.1 greenkeeper/@types/node-8.5.2 greenkeeper/@types/node-8.5.3 greenkeeper/@types/node-8.5.4 greenkeeper/@types/node-8.5.5 greenkeeper/@types/node-8.5.6 greenkeeper/@types/node-8.5.7 greenkeeper/@types/node-8.5.8 greenkeeper/@types/node-9.3.0 greenkeeper/@types/node-9.4.0 greenkeeper/@types/node-9.4.1 greenkeeper/@types/node-9.4.2 greenkeeper/@types/node-9.4.3 greenkeeper/@types/node-9.4.4 greenkeeper/@types/node-9.4.5 greenkeeper/@types/node-9.4.6 greenkeeper/@types/node-9.4.7 greenkeeper/@types/node-9.6.0 greenkeeper/@types/node-9.6.1 greenkeeper/@types/node-9.6.2 greenkeeper/@types/node-9.6.3 greenkeeper/@types/node-9.6.4 greenkeeper/@types/node-9.6.5 greenkeeper/@types/node-9.6.6 greenkeeper/@types/node-10.0.3 greenkeeper/@types/node-10.0.7 greenkeeper/@types/node-10.0.9 greenkeeper/@types/node-10.0.10 greenkeeper/@types/node-10.1.0 greenkeeper/@types/node-10.1.1 greenkeeper/@types/node-10.1.2 greenkeeper/@types/node-10.1.3 greenkeeper/@types/node-10.1.4 greenkeeper/@types/node-10.3.0 greenkeeper/@types/node-10.3.1 greenkeeper/@types/node-10.3.2 greenkeeper/@types/node-10.3.3 greenkeeper/@types/node-10.3.4 greenkeeper/@types/node-10.3.5 greenkeeper/@types/node-10.3.6 greenkeeper/@types/node-10.5.0 greenkeeper/@types/node-10.5.1 greenkeeper/@types/node-10.5.2 greenkeeper/@types/node-10.5.3 greenkeeper/@types/node-10.5.4 greenkeeper/@types/node-10.5.5 greenkeeper/@types/node-10.5.6 greenkeeper/@types/node-10.5.7 greenkeeper/@types/node-10.5.8 greenkeeper/@types/node-10.7.0 greenkeeper/@types/node-10.7.1 greenkeeper/@types/node-10.7.2 greenkeeper/@types/node-10.9.0 greenkeeper/@types/node-10.9.1 greenkeeper/@types/node-10.9.2 greenkeeper/@types/node-10.9.3 greenkeeper/@types/node-10.9.4 greenkeeper/@types/node-10.10.0 greenkeeper/@types/node-10.10.1 greenkeeper/@types/node-10.10.2 greenkeeper/@types/node-10.10.3 greenkeeper/@types/node-10.11.0 greenkeeper/@types/node-10.11.1 greenkeeper/@types/node-10.11.2 greenkeeper/@types/node-10.11.3 greenkeeper/@types/node-10.11.4 greenkeeper/@types/node-10.11.5 greenkeeper/@types/node-10.11.6 greenkeeper/@types/node-10.11.7 greenkeeper/@types/node-10.12.0 greenkeeper/@types/node-10.12.1 greenkeeper/@types/node-10.12.2 greenkeeper/@types/node-10.12.3 greenkeeper/@types/node-10.12.4 greenkeeper/@types/node-10.12.5 greenkeeper/@types/node-10.12.6 greenkeeper/@types/node-10.12.7 greenkeeper/@types/node-10.12.8 greenkeeper/@types/node-10.12.9 greenkeeper/@types/node-10.12.10 greenkeeper/@types/node-10.12.11 greenkeeper/@types/node-10.12.12 greenkeeper/@types/node-10.12.13 greenkeeper/@types/node-10.12.14 greenkeeper/@types/node-10.12.15 greenkeeper/@types/node-10.12.16 greenkeeper/@types/node-10.12.17 greenkeeper/@types/simple-mock-0.8.1 master use-jest
Nothing to show
Clone or download
Latest commit c00e497 Oct 8, 2018

README.md

graphql-redis-subscriptions

Greenkeeper badge Build Status

This package implements the PubSubEngine Interface from the graphql-subscriptions package and also the new AsyncIterator interface. It allows you to connect your subscriptions manger to a redis Pub Sub mechanism to support multiple subscription manager instances.

Installation

At first, install the graphql-redis-subscriptions package:

npm install graphql-redis-subscriptions

As the graphql-subscriptions package is declared as a peer dependency, you might receive warning about unmet peer dependency if it's not installed already by one of your other packages. In that case you also need to install it too:

npm install graphql-subscriptions

Using as AsyncIterator

Define your GraphQL schema with a Subscription type:

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

type Subscription {
    somethingChanged: Result
}

type Result {
    id: String
}

Now, let's create a simple RedisPubSub instance:

import { RedisPubSub } from 'graphql-redis-subscriptions';
const pubsub = new RedisPubSub();

Now, implement your Subscriptions type resolver, using the pubsub.asyncIterator to map the event you need:

const SOMETHING_CHANGED_TOPIC = 'something_changed';

export const resolvers = {
  Subscription: {
    somethingChanged: {
      subscribe: () => pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC),
    },
  },
}

Subscriptions resolvers are not a function, but an object with subscribe method, that returns AsyncIterable.

Calling the method asyncIterator of the RedisPubSub instance will send redis a SUBSCRIBE message to the topic provided and will return an AsyncIterator binded to the RedisPubSub instance and listens to any event published on that topic. Now, the GraphQL engine knows that somethingChanged is a subscription, and every time we will use pubsub.publish over this topic, the RedisPubSub will PUBLISH the event over redis to all other subscribed instances and those in their turn will emit the event to GraphQL using the next callback given by the GraphQL engine.

pubsub.publish(SOMETHING_CHANGED_TOPIC, { somethingChanged: { id: "123" }});

Dynamically create a topic based on subscription args passed on the query:

export const resolvers = {
  Subscription: {
    somethingChanged: {
      subscribe: (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),
    },
  },
}

Using both arguments and payload to filter events

import { withFilter } from 'graphql-subscriptions';

export const resolvers = {
  Subscription: {
    somethingChanged: {
      subscribe: withFilter(
        (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),
        (payload, variables) => payload.somethingChanged.id === variables.relevantId,
      ),
    },
  },
}

Creating the Redis Client

For production usage, it is recommended to send a redis client from the using code.

import { RedisPubSub } from 'graphql-redis-subscriptions';
import * as Redis from 'ioredis';

const options = {
  host: REDIS_DOMAIN_NAME,
  port: PORT_NUMBER,
  retry_strategy: options => {
    // reconnect after
    return Math.max(options.attempt * 100, 3000);
  }
};

const pubsub = new RedisPubSub({
  ...,
  publisher: new Redis(options),
  subscriber: new Redis(options)
});

You can learn more on ioredis package here.

Passing redis options object

The basic usage is great for development and you will be able to connect to a redis server running on your system seamlessly. But for any production usage you should probably pass in a redis options object

import { RedisPubSub } from 'graphql-redis-subscriptions';

const pubsub = new RedisPubSub({
  connection: {
    host: REDIS_DOMAIN_NAME,
    port: PORT_NUMBER,
    retry_strategy: options => {
      // reconnect after
      return Math.max(options.attempt * 100, 3000);
    }
  }
});

You can learn more on the redis options object here.

Using a custom reviver

By default, Javascript objects are serialized using the JSON.stringify and JSON.parse methods. For handling custom objects, you may pass your own reviver function to JSON.parse.

import { RedisPubSub } from 'graphql-redis-subscriptions';

const dateReviver = (key, value) => {
  const isISO8601Z = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
  if (typeof value === 'string' && isISO8601Z.test(value)) {
    const tempDateNumber = Date.parse(value);
    if (!isNaN(tempDateNumber)) {
      return new Date(tempDateNumber);
    }
  }
  return value;
};

const pubSub = new RedisPubSub({ ..., reviver: dateReviver });

pubSub.publish('Test', {
  validTime: new Date(),
  invalidTime: '2018-13-01T12:00:00Z'
});
pubSub.subscribe('Test', message => {
  message.validTime; // Javascript Date
  message.invalidTime; // string
});

Old Usage (Deprecated)

import { RedisPubSub } from 'graphql-redis-subscriptions';
const pubsub = new RedisPubSub();
const subscriptionManager = new SubscriptionManager({
  schema,
  pubsub,
  setupFunctions: {},
});

Using Trigger Transform (Deprecated)

Recently, graphql-subscriptions package added a way to pass in options to each call of subscribe. Those options are constructed via the setupFunctions object you provide the Subscription Manager constructor. The reason for graphql-subscriptions to add that feature is to allow pub sub engines a way to reduce their subscription set using the best method of said engine. For example, meteor's live query could use mongo selector with arguments passed from the subscription like the subscribed entity id. For redis, this could be a bit more simplified, but much more generic. The standard for redis subscriptions is to use dot notations to make the subscription more specific. This is only the standard but I would like to present an example of creating a specific subscription using the channel options feature.

First I create a simple and generic trigger transform

const triggerTransform = (trigger, {path}) => [trigger, ...path].join('.');

Then I pass it to the RedisPubSub constructor.

const pubsub = new RedisPubSub({
  triggerTransform,
});

Lastly, I provide a setupFunction for commentsAdded subscription field. It specifies one trigger called comments.added and it is called with the channelOptions object that holds repoName path fragment.

const subscriptionManager = new SubscriptionManager({
  schema,
  setupFunctions: {
    commentsAdded: (options, {repoName}) => ({
      'comments.added': {
        channelOptions: {path: [repoName]},
      },
    }),
  },
  pubsub,
});

When I call subscribe like this:

const query = `
  subscription X($repoName: String!) {
    commentsAdded(repoName: $repoName)
  }
`;
const variables = {repoName: 'graphql-redis-subscriptions'};
subscriptionManager.subscribe({query, operationName: 'X', variables, callback});

The subscription string that Redis will receive will be comments.added.graphql-redis-subscriptions. This subscription string is much more specific and means the the filtering required for this type of subscription is not needed anymore. This is one step towards lifting the load off of the graphql api server regarding subscriptions.