All files / js.socket/src/client index.js

94.12% Statements 16/17
100% Branches 0/0
85.71% Functions 6/7
100% Lines 15/15

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 661x                                 3x   3x 3x                   2x 2x 2x   2x                   2x 2x   2x                   3x 27x   3x       1x  
const Socket = require('../socket')
 
/**
 * When a server needs to connect with another, a client connection needs to be
 * esablished. This class is representing that client.
 *
 * @extends Socket
 */
class Client extends Socket
{
  /**
   * @param {Logger} log
   * @param {ConnectionObserver} connectionObserver
   * @param {net.Socket} client
   */
  constructor(log, connectionObserver, client)
  {
    super(log, connectionObserver)
 
    this.client = client
    this.logClientEvents(client, log)
  }
 
  /**
   * @param {number} port an unsigned integer
   * @param {string} host the host address to connect to
   */
  connect(port, host)
  {
    const
    observer  = this.connectionObserver,
    client    = this.client,
    callback  = observer.onConnection.bind(observer, client)
 
    this.client.connect(port, host, callback)
  }
 
  /**
   * @param {string} event
   * @param {*} data
   */
  async emit(...args)
  {
    const
    emitter = this.connectionObserver.emitter,
    client  = this.client
 
    await emitter.emit(client, ...args)
  }
 
  /**
   * @protected
   * @param {net.Socket} client
   * @param {Logger} log
   */
  logClientEvents(client, log)
  {
    ['close','connect','data','drain','end','error','lookup','ready','timeout']
    .forEach((event) => client.on(event, () => log.info(event)))
 
    client.on('error', (...a) => log.info('error', ...a))
  }
}
 
module.exports = Client