'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

const { Transform } = require('stream')
const util = require('util')
const common = require('./common')

function DelayedBody(ms, body) {
  Transform.call(this)

  const self = this
  let data = ''
  let ended = false

  if (common.isStream(body)) {
    body.on('data', function(chunk) {
      data += Buffer.isBuffer(chunk) ? chunk.toString() : chunk
    })

    body.once('end', function() {
      ended = true
    })

    body.resume()
  }

  // TODO: This would be more readable if the stream case were moved into
  // the `if` statement above.
  setTimeout(function() {
    if (common.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)
}

@@ -314,37 +314,8 @@
 %0A */
-%0Amodule.exports = DelayedBody
 %0A%0Aco
@@ -356,37 +356,8 @@
 m')%0A
-const util = require('util')%0A
 cons
@@ -392,65 +392,104 @@
 ')%0A%0A
-function DelayedBody(ms, body) %7B%0A  Transform.call(this
+module.exports = class DelayedBody extends Transform %7B%0A  constructor(ms, body) %7B%0A    super(
 )%0A%0A
+  
   co
@@ -504,16 +504,18 @@
  = this%0A
+  
   let da
@@ -524,16 +524,18 @@
  = ''%0A  
+ 
+ 
 let ende
@@ -545,16 +545,18 @@
  false%0A%0A
+  
   if (co
@@ -578,24 +578,26 @@
 ody)) %7B%0A    
+  
 body.on('dat
@@ -624,16 +624,18 @@
 %7B%0A      
+ 
+ 
 data += 
@@ -684,28 +684,32 @@
 : chunk%0A    
+  
 %7D)%0A%0A
+  
     body.onc
@@ -726,24 +726,26 @@
 unction() %7B%0A
+  
       ended 
@@ -751,28 +751,32 @@
  = true%0A    
+  
 %7D)%0A%0A
+  
     body.res
@@ -785,13 +785,17 @@
 e()%0A
+  
   %7D%0A%0A
+  
   //
@@ -864,16 +864,18 @@
 ed into%0A
+  
   // the
@@ -897,16 +897,18 @@
  above.%0A
+  
   setTim
@@ -925,24 +925,26 @@
 ion() %7B%0A    
+ 
+ 
 if (common.i
@@ -972,24 +972,26 @@
 ed) %7B%0A      
+  
 body.once('e
@@ -1012,24 +1012,26 @@
 ) %7B%0A        
+ 
+ 
 self.end(dat
@@ -1033,16 +1033,18 @@
 d(data)%0A
+  
       %7D)
@@ -1048,16 +1048,18 @@
  %7D)%0A    
+  
 %7D else %7B
@@ -1059,16 +1059,18 @@
  else %7B%0A
+  
       se
@@ -1098,103 +1098,40 @@
     
+  
 %7D%0A  
+ 
+ 
 %7D, ms)%0A
-%7D%0Autil.inherits(DelayedBody, Transform)%0A%0ADelayedBody.prototype._transform = function
+  %7D%0A%0A  _transform
 (chu
@@ -1150,16 +1150,18 @@
 , cb) %7B%0A
+  
   this.p
@@ -1171,16 +1171,18 @@
 (chunk)%0A
+  
   proces
@@ -1196,10 +1196,14 @@
 ick(cb)%0A
+  %7D%0A
 %7D%0A

Convert DelayedBody to a class (#1634)