all files / networkWrapper/wrappers/ websocket.js

96% Statements 72/75
80.65% Branches 25/31
100% Functions 14/14
96% Lines 72/75
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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176     18× 18×   18× 18× 18× 18× 18× 18× 18× 18× 18×                   18× 16×       16× 15× 15×     16×   16×           16×                                 16×         16×                         18×             18×             18×             18×               18×             18×                                    
var
  KuzzleEventEmitter = require('../../eventEmitter');
 
function WSNode(host, port, ssl) {
  var self = this;
  KuzzleEventEmitter.call(this);
 
  this.WebSocket = typeof WebSocket !== 'undefined' ? WebSocket : require('ws');
  this.host = host;
  this.port = port;
  this.ssl = ssl;
  this.client = null;
  this.wasConnected = false;
  this.retrying = false;
  this.lasturl = null;
  this.stopRetryingToConnect = false;
 
  /**
   * Creates a new socket from the provided arguments
   *
   * @constructor
   * @param {boolean} autoReconnect
   * @param {int} reconnectionDelay
   * @returns {Object} Socket
   */
  this.connect = function (autoReconnect, reconnectionDelay) {
    var
      url = (this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port,
      options = typeof window !== 'undefined' ? undefined : {perMessageDeflate: false};
 
    if (url !== this.lasturl) {
      self.wasConnected = false;
      this.lasturl = url;
    }
 
    this.client = new this.WebSocket(url, options);
 
    this.client.onopen = function () {
      if (self.wasConnected) {
        self.emitEvent('reconnect');
      }
      else {
        self.emitEvent('connect');
      }
      self.wasConnected = true;
      self.stopRetryingToConnect = false;
    };
 
    this.client.onclose = function (closeEvent, message) {
      var error;
      var status;
      var reason = message;
 
      Eif (typeof closeEvent === 'number') {
        status = closeEvent;
      }
      else {
        status = closeEvent.code;
 
        if (closeEvent.reason) {
          reason = closeEvent.reason;
        }
      }
 
      if (status === 1000) {
        self.emitEvent('disconnect');
      }
      else {
        error = new Error(reason);
        error.status = status;
 
        onClientNetworkError(self, autoReconnect, reconnectionDelay, error);
      }
    };
 
    this.client.onerror = function (error) {
      Eif (!(error instanceof Error)) {
        error = new Error(error);
      }
 
      onClientNetworkError(self, autoReconnect, reconnectionDelay, error);
    };
 
    this.client.onmessage = function (payload) {
      var data = JSON.parse(payload.data || payload);
 
      if (data.room) {
        self.emitEvent(data.room, data);
      }
      else {
        self.emitEvent('discarded', data);
      }
    };
  };
 
  /**
   * Fires the provided callback whence a connection is established
   *
   * @param {function} callback
   */
  this.onConnect = function (callback) {
    this.addListener('connect', callback);
  };
 
  /**
   * Fires the provided callback whenever a connection error is received
   * @param {function} callback
   */
  this.onConnectError = function (callback) {
    this.addListener('networkError', callback);
  };
 
  /**
   * Fires the provided callback whenever a disconnection occurred
   * @param {function} callback
   */
  this.onDisconnect = function (callback) {
    this.addListener('disconnect', callback);
  };
 
  /**
   * Fires the provided callback whenever a connection has been reestablished
   * @param {function} callback
   */
  this.onReconnect = function (callback) {
    this.addListener('reconnect', callback);
  };
 
  /**
   * Sends a payload to the connected server
   *
   * @param {Object} payload
   */
  this.send = function (payload) {
    if (this.client && this.client.readyState === this.client.OPEN) {
      this.client.send(JSON.stringify(payload));
    }
  };
 
  /**
   * Closes the connection
   */
  this.close = function () {
    this.removeAllListeners();
    this.wasConnected = false;
    this.client.close();
    this.client = null;
    self.stopRetryingToConnect = true;
  };
}
WSNode.prototype = Object.create(KuzzleEventEmitter.prototype);
WSNode.prototype.constructor = WSNode;
 
 
/**
 * Called when the connection closes with an error state
 *
 * @param {WSNode} 
 * @param {boolean} autoReconnect
 * @param {number} reconnectionDelay
 * @param {Error} error
 */
function onClientNetworkError(ws, autoReconnect, reconnectionDelay, error) {
  if (autoReconnect && !ws.retrying && !ws.stopRetryingToConnect) {
    ws.retrying = true;
    setTimeout(function () {
      ws.retrying = false;
      ws.connect(autoReconnect, reconnectionDelay);
    }, reconnectionDelay);
  }
 
  ws.emitEvent('networkError', error);
}
 
module.exports = WSNode;