UNPKG

1.22 kBJavaScriptView Raw
1'use strict'
2
3/**
4 * Creates a stream which becomes the response body of the interceptor when a
5 * delay is set. The stream outputs the intended body and EOF after the delay.
6 *
7 * @param {String|Buffer|Stream} body - the body to write/pipe out
8 * @param {Integer} ms - The delay in milliseconds
9 * @constructor
10 */
11
12const { Transform } = require('stream')
13const common = require('./common')
14
15module.exports = class DelayedBody extends Transform {
16 constructor(ms, body) {
17 super()
18
19 const self = this
20 let data = ''
21 let ended = false
22
23 if (common.isStream(body)) {
24 body.on('data', function(chunk) {
25 data += Buffer.isBuffer(chunk) ? chunk.toString() : chunk
26 })
27
28 body.once('end', function() {
29 ended = true
30 })
31
32 body.resume()
33 }
34
35 // TODO: This would be more readable if the stream case were moved into
36 // the `if` statement above.
37 common.setTimeout(function() {
38 if (common.isStream(body) && !ended) {
39 body.once('end', function() {
40 self.end(data)
41 })
42 } else {
43 self.end(data || body)
44 }
45 }, ms)
46 }
47
48 _transform(chunk, encoding, cb) {
49 this.push(chunk)
50 process.nextTick(cb)
51 }
52}