micro-toolkit/event-bus-zeromq

View on GitHub
lib/event.js

Summary

Maintainability
A
45 mins
Test Coverage
var uuidGen = require('uuid')
var _ = require('lodash')
var msgpack = require('msgpack')

// Convert event into a frame format
function toFrames(msg) {
  // Message is formatted on wire as 6 frames:
  // Frame 0: event topic, as 0MQ string
  // Frame 1: sequence number, 8 bytes in network order
  // Frame 2: event producer unique id, as 0MQ string
  // Frame 3: event producer timestamp, as 0MQ string in ISO-8601 format
  // Frame 4: event UUID, as 0MQ string formatted in v4 as specified at rfc4122
  // Frame 5: event data, as blob generated by Message Pack serialization
  var topic = msg.topic || ''
  var seq = msg.sequence || null
  var data = msgpack.pack(msg.data)
  var timestamp = msg.timestamp.toISOString()
  return [ topic, seq, msg.producer, timestamp, msg.uuid, data ]
}

// get a event object from frames
function fromFrames(frames) {
  return {
    topic: frames[0].toString(),
    sequence: parseInt(frames[1].toString(), 10),
    producer: frames[2].toString(),
    timestamp: new Date(frames[3]),
    uuid: frames[4].toString(),
    data: msgpack.unpack(frames[5])
  }
}

// return a event instance fullfilled with data
function getInstance(producer, topic, data, sequence, uuid, timestamp) {
  var instance

  if (_.isArray(producer)){
    // when the first argument is a array we are receiving the frames
    instance = fromFrames(producer)
  }
  else {
    instance = {
      topic: topic || null,
      sequence: sequence || null,
      uuid: uuid || uuidGen.v4(),
      producer: producer,
      timestamp: timestamp || new Date(),
      data: data
    }
  }

  instance.toFrames = _.partial(toFrames, instance)

  return instance
}

module.exports = {
  getInstance: getInstance
}