All files / js.socket/src/connection-observer index.js

92.86% Statements 13/14
100% Branches 0/0
85.71% Functions 6/7
100% Lines 12/12

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                          9x 9x 9x 9x               5x 5x 5x                   6x 36x   6x                     6x       1x  
/**
 * Responsible for attaching a dispacther to all data events on a socket
 */
class ConnectionObserver
{
  /**
   * @param {Logger} log
   * @param {Dispatcher} dispatcher
   * @param {Emitter} emitter
   * @param {ContextFactory} contextFactory
   */
  constructor(log, dispatcher, emitter, contextFactory)
  {
    this.log            = log
    this.dispatcher     = dispatcher
    this.emitter        = emitter
    this.contextFactory = contextFactory
  }
 
  /**
   * @param {net.Socket} socket
   */
  onConnection(socket)
  {
    this.logSocketEvents(socket, this.log)
    const context = this.contextFactory.create(socket, this.emitter)
    this.attachDataEventToDispatcherWithAContext(socket, this.dispatcher, context)
  }
 
  /**
   * @protected
   * @param {net.Socket} socket
   * @param {Logger} log
   */
  logSocketEvents(socket, log)
  {
    ['close','connection','drain','end','lookup','timeout']
    .forEach((event) => socket.on(event, () => log.info('connection:', event)))
 
    socket.on('error', (...a) => log.info('connection:', 'error', ...a))
  }
 
  /**
   * @protected
   * @param {net.Socket} socket
   * @param {Dispatcher} dispatcher
   * @param {Context} context
   */
  attachDataEventToDispatcherWithAContext(socket, dispatcher, context)
  {
    socket.on('data', dispatcher.dispatch.bind(dispatcher, context))
  }
}
 
module.exports = ConnectionObserver