All files / controllers/realtime room.js

3.13% Statements 1/32
0% Branches 0/15
0% Functions 0/6
3.13% Lines 1/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                            1x  
class Room {
 
  /**
   * @param {Kuzzle} kuzzle
   * @param {string} index
   * @param {string} collection
   * @param {object} body
   * @param {function} callback
   * @param {object} options
   */
  constructor (kuzzle, index, collection, body, callback, options = {}) {
    this.kuzzle = kuzzle;
    this.index = index;
    this.collection = collection;
    this.callback = callback;
    this.options = options;
 
    this.id = null;
    this.channel = null;
 
    // format complete request from body & options
    this.request = {
      index,
      collection,
      body,
      controller: 'realtime',
      action: 'subscribe'
    };
    for (const opt of ['state', 'scope', 'users', 'volatile']) {
      this.request[opt] = this.options[opt];
      delete this.options[opt];
    }
 
    this.autoResubscribe = typeof options.autoResubscribe === 'boolean'
      ? options.autoResubscribe
      : kuzzle.autoResubscribe;
    this.subscribeToSelf = typeof options.subscribeToSelf === 'boolean'
      ? options.subscribeToSelf
      : true;
 
    for (const opt of ['autoResubscribe', 'subscribeToSelf']) {
      delete this.options[opt];
    }
 
    // force bind for further event listener calls
    this._channelListener = this._channelListener.bind(this);
    this._reSubscribeListener = this._reSubscribeListener.bind(this);
  }
 
  subscribe () {
    return this.kuzzle.query(this.request, this.options)
      .then(response => {
        this.id = response.result.roomId;
        this.channel = response.result.channel;
 
        // we rely on kuzzle event emitter to not duplicate the listeners here
        this.kuzzle.network.on(this.channel, this._channelListener);
 
        this.kuzzle.addListener('reconnected', this._reSubscribeListener);
 
        return response;
      });
  }
 
  removeListeners () {
    this.kuzzle.removeListener('reconnected', this._reSubscribeListener);
 
    if (this.channel) {
      this.kuzzle.network.removeListener(this.channel, this._channelListener);
    }
  }
 
  _channelListener (data) {
    const fromSelf = data.volatile && data.volatile.sdkInstanceId === this.kuzzle.network.id;
    if (this.subscribeToSelf || !fromSelf) {
      this.callback(data);
    }
  }
 
  _reSubscribeListener () {
    if (this.autoResubscribe) {
      return this.subscribe();
    }
  }
}
 
module.exports = Room;