All files / src dispatcher.js

94.44% Statements 17/18
66.67% Branches 2/3
100% Functions 5/5
94.44% Lines 17/18

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 751x                       11x 11x                 11x 11x                 3x 3x 3x                 4x   4x   5x 5x 5x                             2x     1x 1x         1x  
const Events = require('events')
 
/**
 * Responsible for dispatching events from the payload stack
 */
class Dispatcher
{
  /**
   * @param {Logger} log
   */
  static from(log)
  {
    const events = new Events
    return new Dispatcher(log, events)
  }
 
  /**
   * @param {Logger} log
   * @param {events} events
   */
  constructor(log, events)
  {
    this.log    = log
    this.events = events
  }
 
  /**
   * @param {Context} context
   * @param {Buffer} buffer
   */
  dispatch(context, buffer)
  {
    this.log.info('data')
    context.payloadStack.push(buffer)
    this.loopThroughContextBufferToDispatchEachMessageOneByOne(context)
  }
 
  /**
   * @protected
   * @param {Context} context
   */
  loopThroughContextBufferToDispatchEachMessageOneByOne(context)
  {
    try
    {
      while(context.payloadStack.stack.length)
      {
        const dto = context.payloadStack.shift()
        this.log.info('trigger:', dto.event, dto.data)
        this.events.emit(dto.event, context, dto.data)
      }
    }
    catch(error)
    {
      this.handleError(error)
    }
  }
 
  /**
   * @protected
   * @param {Error} error
   */
  handleError(error)
  {
    switch(error.code)
    {
      case 'ERR_OUT_OF_RANGE':
      case 'ERR_INCOMPLETE_MESSAGE': break
      default: throw error
    }
  }
}
 
module.exports = Dispatcher