Skip to content

Commit

Permalink
refactor: Convert DelayedBody to a class (#1634)
Browse files Browse the repository at this point in the history
As the start of some modernization / stylistic updates, I started converting the Foo.prototype's to ES6 classes.
  • Loading branch information
paulmelnikow committed Jul 19, 2019
1 parent f385edd commit 08b1b6b
Showing 1 changed file with 30 additions and 31 deletions.
61 changes: 30 additions & 31 deletions lib/delayed_body.js
Expand Up @@ -8,46 +8,45 @@
* @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)
module.exports = class DelayedBody extends Transform {
constructor(ms, body) {
super()

const self = this
let data = ''
let ended = false
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()
}
if (common.isStream(body)) {
body.on('data', function(chunk) {
data += Buffer.isBuffer(chunk) ? chunk.toString() : chunk
})

// 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)
ended = true
})
} else {
self.end(data || body)

body.resume()
}
}, ms)
}
util.inherits(DelayedBody, Transform)

DelayedBody.prototype._transform = function(chunk, encoding, cb) {
this.push(chunk)
process.nextTick(cb)
// 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)
}

_transform(chunk, encoding, cb) {
this.push(chunk)
process.nextTick(cb)
}
}

0 comments on commit 08b1b6b

Please sign in to comment.