All files / src/networkWrapper/protocols websocket.js

98.08% Statements 51/52
77.78% Branches 28/36
100% Functions 9/9
98.08% Lines 51/52

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 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      1x             34x   34x       34x 34x 34x             30x   30x 30x   30x   30x 26x 26x     30x   30x 8x 8x     30x     7x   7x 6x     1x   1x 1x       7x 3x       4x 2x 2x   2x       30x 2x   2x   2x 2x       30x 3x     3x 2x     1x                         2x 1x               1x 1x 1x 1x 1x   1x 1x 1x       1x  
'use strict';
 
const
  RTWrapper = require('./abstract/realtime');
 
let WebSocketClient;
 
class WSNode extends RTWrapper {
 
  constructor(options = {}) {
    super(options);
 
    Iif (typeof this.host !== 'string' || this.host === '') {
      throw new Error('options.host is required');
    }
 
    WebSocketClient = typeof WebSocket !== 'undefined' ? WebSocket : require('uws');
    this.client = null;
    this.lasturl = null;
  }
 
  /**
   * Connect to the websocket server
   */
  connect () {
    return new Promise((resolve, reject) => {
      const
        url = (this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port,
        opts = typeof window !== 'undefined' ? undefined : {perMessageDeflate: false};
 
      super.connect();
 
      if (url !== this.lasturl) {
        this.wasConnected = false;
        this.lasturl = url;
      }
 
      this.client = new WebSocketClient(url, opts);
 
      this.client.onopen = () => {
        this.clientConnected();
        return resolve();
      };
 
      this.client.onclose = (closeEvent, message) => {
        let
          status,
          reason = message;
 
        if (typeof closeEvent === 'number') {
          status = closeEvent;
        }
        else {
          status = closeEvent.code;
 
          Eif (closeEvent.reason) {
            reason = closeEvent.reason;
          }
        }
 
        if (status === 1000) {
          this.clientDisconnected();
        }
        // do not forward a connection close error if no
        // connection has been previously established
        else if (this.wasConnected) {
          const error = new Error(reason);
          error.status = status;
 
          this.clientNetworkError(error);
        }
      };
 
      this.client.onerror = error => {
        const err = (error instanceof Error) && error || new Error(error);
 
        this.clientNetworkError(err);
 
        Eif ([this.client.CLOSING, this.client.CLOSED].indexOf(this.client.readyState) > -1) {
          return reject(err);
        }
      };
 
      this.client.onmessage = payload => {
        const data = JSON.parse(payload.data || payload);
 
        // for responses, data.room == requestId
        if (data.room) {
          this.emit(data.room, data);
        }
        else {
          this.emit('discarded', data);
        }
      };
 
    });
  }
 
  /**
   * Sends a payload to the connected server
   *
   * @param {Object} payload
   */
  send (payload) {
    if (this.client && this.client.readyState === this.client.OPEN) {
      this.client.send(JSON.stringify(payload));
    }
  }
 
  /**
   * Closes the connection
   */
  close () {
    this.state = 'offline';
    this.removeAllListeners();
    this.wasConnected = false;
    Eif (this.client) {
      this.client.close();
    }
    this.client = null;
    this.stopRetryingToConnect = true;
    super.close();
  }
}
 
module.exports = WSNode;