Code coverage report for nock/lib/delayed_body.js

Statements: 59.57% (28 / 47)      Branches: 72.22% (13 / 18)      Functions: 46.15% (6 / 13)      Lines: 59.57% (28 / 47)      Ignored: none     

All files » nock/lib/ » delayed_body.js
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 75 76 77 78 79 80 81 82 83 84 85 86                    1   1 1 1 1 1   1 6 6     1                                                       1 3   3 3 3   3 2 2     2 2     2     3 3         3       1   1 3 3  
'use strict';
 
/**
 * Creates a stream which becomes the response body of the interceptor when a
 * delay is set. The stream outputs the intended body and EOF after the delay.
 *
 * @param  {String|Buffer|Stream} body - the body to write/pipe out
 * @param  {Integer} ms - The delay in milliseconds
 * @constructor
 */
module.exports = DelayedBody;
 
var Transform = require('stream').Transform;
var EventEmitter = require('events').EventEmitter;
var noop = function () {};
var util = require('util');
var timers = require('timers');
 
function isStream(obj) {
  var is = obj && (typeof a !== 'string') && (! Buffer.isBuffer(obj)) && (typeof obj.setEncoding === 'function');
  return is;
}
 
Iif (!Transform) {
  // for barebones compatibility for node < 0.10
  var FakeTransformStream = function () {
    EventEmitter.call(this);
  };
  util.inherits(FakeTransformStream, EventEmitter);
  FakeTransformStream.prototype.pause = noop;
  FakeTransformStream.prototype.resume = noop;
  FakeTransformStream.prototype.setEncoding = noop;
  FakeTransformStream.prototype.write = function (chunk, encoding) {
    var self = this;
    process.nextTick(function () {
      self.emit('data', chunk, encoding);
    });
  };
  FakeTransformStream.prototype.end = function (chunk) {
    var self = this;
    if (chunk) {
      self.write(chunk);
    }
    process.nextTick(function () {
      self.emit('end');
    });
  };
 
  Transform = FakeTransformStream;
}
 
function DelayedBody(ms, body) {
  Transform.call(this);
 
  var self = this;
  var data = '';
  var ended = false;
 
  if (isStream(body)) {
    body.on('data', function (chunk) {
      data += Buffer.isBuffer(chunk) ? chunk.toString() : chunk;
    });
 
    body.once('end', function () {
      ended = true;
    });
 
    body.resume();
  }
 
  setTimeout(function () {
    Iif (isStream(body) && !ended) {
      body.once('end', function () {
        self.end(data);
      });
    } else {
      self.end(data || body);
    }
  }, ms);
}
util.inherits(DelayedBody, Transform);
 
DelayedBody.prototype._transform = function (chunk, encoding, cb) {
  this.push(chunk);
  process.nextTick(cb);
};