All files / app/lib collect.js

100% Statements 53/53
100% Branches 16/16
100% Functions 4/4
100% Lines 53/53

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 5321x 21x 21x 40x 40x 40x 20x 20x 20x 40x 20x 20x 20x 20x 20x 40x 21x 21x 21x 21x 21x 21x 61x 61x 61x 61x 61x 7x 7x 7x 61x 61x 21x 21x 21x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 21x 21x 21x 19x 19x 21x 21x 21x
const Streamz = require('streamz');
const util = require('util');
 
function Collect(maxSize,maxDuration,maxTextLength) {
  if (!(this instanceof Streamz))
    return new Collect(maxSize,maxDuration,maxTextLength);
  Streamz.call(this);
  // Allow a custom collection function as first argument
  if (typeof maxSize === 'function')
    this._fn = maxSize;
  this.maxSize = maxSize;
  this.textLength = 0;
  this.maxTextLength = maxTextLength;
  this.maxDuration = maxDuration;
  this.buffer = [];
}
 
util.inherits(Collect,Streamz);
 
Collect.prototype.buffer = undefined;
 
Collect.prototype._push = function() {
  this.textLength = 0;
  if (this.buffer.length)
    this.push(this.buffer);
 
  if (this.timeout) {
    clearTimeout(this.timeout);
    this.timeout = undefined;
  }
 
  this.buffer = [];
};
 
Collect.prototype._fn = function(d) {
  this.buffer.push(d);
  
  if (this.maxDuration && !this.timeout)
    this.timeout = setTimeout(this._push.bind(this),this.maxDuration);
 
  if (this.maxTextLength && (this.textLength += JSON.stringify(d).length) > this.maxTextLength)
    this._push();
 
  if(this.buffer.length >= this.maxSize)
    this._push();
};
 
Collect.prototype._flush = function(cb) {
  this._push();
  setImmediate( () => Streamz.prototype._flush(cb));
};
 
module.exports = Collect;