All files pubsub.ts

100% Statements 24/24
100% Branches 0/0
100% Functions 6/6
100% Lines 21/21
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 401x   1x   1x           7x 7x 7x     1x 7x   7x     1x 2x 2x 2x   2x     1x 1x 1x 1x     1x 5x   1x  
import { EventEmitter } from 'events';
import { PubSubEngine } from './pubsub-engine';
import { eventEmitterAsyncIterator } from './event-emitter-to-async-iterator';
 
export class PubSub implements PubSubEngine {
  protected ee: EventEmitter;
  private subscriptions: { [key: string]: [string, (...args: any[]) => void] };
  private subIdCounter: number;
 
  constructor() {
    this.ee = new EventEmitter();
    this.subscriptions = {};
    this.subIdCounter = 0;
  }
 
  public publish(triggerName: string, payload: any): boolean {
    this.ee.emit(triggerName, payload);
 
    return true;
  }
 
  public subscribe(triggerName: string, onMessage: (...args: any[]) => void): Promise<number> {
    this.ee.addListener(triggerName, onMessage);
    this.subIdCounter = this.subIdCounter + 1;
    this.subscriptions[this.subIdCounter] = [triggerName, onMessage];
 
    return Promise.resolve(this.subIdCounter);
  }
 
  public unsubscribe(subId: number) {
    const [triggerName, onMessage] = this.subscriptions[subId];
    delete this.subscriptions[subId];
    this.ee.removeListener(triggerName, onMessage);
  }
 
  public asyncIterator<T>(triggers: string | string[]): AsyncIterator<T> {
    return eventEmitterAsyncIterator<T>(this.ee, triggers);
  }
}