All files / src/controllers/realtime room.js

100% Statements 30/30
86.67% Branches 13/15
100% Functions 5/5
100% Lines 30/30

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                      17x 17x 17x 17x 17x 17x   17x 17x     17x             17x 68x 68x     17x     17x       17x 34x       17x       3x   3x 3x     3x   3x         1x 1x           7x 1x       6x   6x 5x         1x  
class Room {
 
  /**
   * @param {RealTimeController} controller
   * @param {string} index
   * @param {string} collection
   * @param {object} body
   * @param {function} callback
   * @param {object} options
   */
  constructor (controller, index, collection, body, callback, options = {}) {
    this.controller = controller;
    this.kuzzle = controller.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
      : this.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);
  }
 
  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.protocol.on(this.channel, this._channelListener);
 
        return response;
      });
  }
 
  removeListeners () {
    Eif (this.channel) {
      this.kuzzle.protocol.removeListener(this.channel, this._channelListener);
    }
  }
 
  _channelListener (data) {
    // intercept token expiration messages and relay them to kuzzle
    if (data.type === 'TokenExpired') {
      return this.kuzzle.tokenExpired();
    }
 
    const fromSelf =
      data.volatile && data.volatile.sdkInstanceId === this.kuzzle.protocol.id;
 
    if (this.subscribeToSelf || !fromSelf) {
      this.callback(data);
    }
  }
}
 
module.exports = Room;