All files mqtt-pubsub.ts

88.89% Statements 56/63
85.71% Branches 24/28
100% Functions 10/10
87.93% Lines 51/58
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 119  1x 1x               1x   3x 11x 2x 2x   2x   2x             2x 2x 2x     1x   5x     12x 12x 12x 12x   12x 12x 4x 4x 4x     8x   8x 8x     8x 8x             1x 28x 14x   14x 2x     12x 8x 8x     4x 4x 4x       12x 12x     5x 5x     5x       5x 5x         5x   6x 6x 6x                     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?: TriggerTransform;
  connectionListener?: (err: Error) => void;
}
 
export class RedisPubSub implements PubSubEngine {
 
  constructor(options: 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(trigger, JSON.stringify(payload));
  }
 
  public subscribe(trigger: string, onMessage: Function, options?: Object): Promise<number> {
    const triggerName: string = this.triggerTransform(trigger, options);
    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 => {
          Iif (err) {
            reject(err);
          } else {
            this.subsRefsMap[triggerName] = [...(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..
    if (!subscribers || !subscribers.length)
    I  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: TriggerTransform;
  private redisSubscriber: RedisClient;
  private redisPublisher: RedisClient;
 
  private subscriptionMap: {[subId: number]: [string , Function]};
  private subsRefsMap: {[trigger: string]: Array<number>};
  private currentSubscriptionId: number;
}
 
export type Path = Array<string | number>;
export type Trigger = string | Path;
export type TriggerTransform = (trigger: Trigger, channelOptions?: Object) => string;