All files redis-pubsub.ts

88.71% Statements 55/62
80.77% Branches 21/26
100% Functions 10/10
87.72% Lines 50/57
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118  1x 1x               1x   2x 11x 1x 1x   1x   1x             1x 1x 1x     1x   4x     7x 7x 7x 7x   7x 7x 2x 2x 2x     5x   5x 5x     5x 5x             1x 16x 8x   8x 1x     7x 5x 5x     2x 2x 2x       7x     4x 4x     4x       4x 4x         4x   5x 5x 5x                     1x        
import {PubSubEngine} from 'graphql-subscriptions/dist/pubsub';
import {RedisClient, ClientOptions as RedisOptions} from 'redis';
import {each} from 'async';
 
export interface PubSubRedisOptions {
  connection?: RedisOptions;
  triggerTransform?: (trigger: string) => string;
  connectionListener?: (err: Error) => void;
}
 
export class RedisPubSub implements PubSubEngine {
 
  constructor(Eoptions: PubSubRedisOptions = {}) {
    this.triggerTransform = options.triggerTransform || (trigger => trigger as string);
    this.redisPublisher = new RedisClient(options.connection);
    this.redisSubscriber = new RedisClient(options.connection);
    // TODO support for pattern based message
    this.redisSubscriber.on('message', this.onMessage.bind(this));
 
    Iif (options.connectionListener) {
      this.redisPublisher.on('connect', options.connectionListener);
      this.redisPublisher.on('error', options.connectionListener);
      this.redisSubscriber.on('connect', options.connectionListener);
      this.redisSubscriber.on('error', options.connectionListener);
    }
 
    this.subscriptionMap = {};
    this.subsRefsMap = {};
    this.currentSubscriptionId = 0;
  }
 
  public publish(trigger: string, payload: any): boolean {
    // TODO PR graphql-subscriptions to use promises as return value
    return this.redisPublisher.publish(this.triggerTransform(trigger), JSON.stringify(payload));
  }
 
  public subscribe(trigger: string, onMessage: Function): Promise<number> {
    const triggerName: string = this.triggerTransform(trigger);
    const id = this.currentSubscriptionId++;
    this.subscriptionMap[id] = [triggerName, onMessage];
 
    let refs = this.subsRefsMap[triggerName];
    if (refs && refs.length > 0) {
      const newRefs = [...refs, id];
      this.subsRefsMap[triggerName] = newRefs;
      return Promise.resolve(id);
 
    } else {
      return new Promise<number>((resolve, reject) => {
        // TODO Support for pattern subs
        this.redisSubscriber.subscribe(triggerName, (err, result) => {
          Iif (err) {
            reject(err);
          } else {
            this.subsRefsMap[triggerName] = [id];
            resolve(id);
          }
        });
      });
    }
  }
 
  public unsubscribe(subId: number) {
    const [triggerName = null] = this.subscriptionMap[subId] || [];
    const refs = this.subsRefsMap[triggerName];
 
    if (!refs)
      throw new Error(`There is no subscription of id "${subId}"`);
 
    let newRefs;
    if (refs.length === 1) {
      this.redisSubscriber.unsubscribe(triggerName);
      newRefs = [];
 
    } else {
      const index = refs.indexOf(subId);
      Eif (index != -1) {
        newRefs = [...refs.slice(0, index), ...refs.slice(index + 1)];
      }
    }
 
    this.subsRefsMap[triggerName] = newRefs;
  }
 
  private onMessage(channel: string, message: string) {
    const subscribers = this.subsRefsMap[channel];
 
    // Don't work for nothing..
    Iif (!subscribers || !subscribers.length)
      return;
 
    let parsedMessage;
    try {
      parsedMessage = JSON.parse(message);
    } catch (e) {
      parsedMessage = message;
    }
 
    each(subscribers, (subId, cb) => {
      // TODO Support pattern based subscriptions
      const [triggerName, listener] = this.subscriptionMap[subId];
      listener(parsedMessage);
      cb();
    })
  }
 
  private triggerTransform: (trigger: Trigger) => string;
  private redisSubscriber: RedisClient;
  private redisPublisher: RedisClient;
 
  private subscriptionMap: {[subId: number]: [string , Function]};
  private subsRefsMap: {[trigger: string]: Array<number>};
  private currentSubscriptionId: number;
}
 
type Path = Array<string | number>;
type Trigger = string | Path;