Skip to content

Commit

Permalink
WIP generic remove listener interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Jul 16, 2020
1 parent 9d85038 commit 20d70d3
Showing 1 changed file with 57 additions and 26 deletions.
83 changes: 57 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ function compression (options) {
var stream

var _end = res.end
var _removeListener = res.removeListener
var _write = res.write

// proxy drain events from stream
Expand All @@ -80,6 +79,23 @@ function compression (options) {
}
})

interceptRemoveListener(res, function (type, listener) {
if (!listeners || type !== 'drain') {
// skip intercept
return false
} else if (stream) {
// remove listener from stream
stream.removeListener(type, listener)
} else {
// remove buffered listener
for (var i = listeners.length - 1; i >= 0; i--) {
if (listeners[i][0] === type && listeners[i][1] === listener) {
listeners.splice(i, 1)
}
}
}
})

// flush
res.flush = function flush () {
if (stream) {
Expand Down Expand Up @@ -130,31 +146,6 @@ function compression (options) {
: stream.end()
}

res.removeListener = function removeListener (type, listener) {
if (!listeners || type !== 'drain') {
return _removeListener.call(this, type, listener)
}

if (stream) {
return stream.removeListener(type, listener)
}

// remove buffered listener
for (var i = listeners.length - 1; i >= 0; i--) {
if (listeners[i][0] === type && listeners[i][1] === listener) {
listeners.splice(i, 1)
}
}

return this
}

/* istanbul ignore next */
if (res.off) {
// emitter.off was added in Node.js v10+; don't add it to earlier versions
res.off = res.removeListener
}

function nocompress (msg) {
debug('no compression: %s', msg)
addListeners(res, _addListener, listeners)
Expand Down Expand Up @@ -310,6 +301,46 @@ function interceptAddListener (ee, fn) {
}
}

/**
* Intercept add listener on event emitter.
* @private
*/

function interceptRemoveListener (ee, fn) {
var _removeListener = ee.removeListener
var _off = ee.off

if (_removeListener) {
Object.defineProperty(ee, 'removeListener', {
configurable: true,
value: removeListener,
writable: true
})
}

if (_off) {
Object.defineProperty(ee, 'off', {
configurable: true,
value: off,
writable: true
})
}

return _removeListener || _off || noop

function removeListener (type, listener) {
return fn.call(this, type, listener) === false
? _removeListener.call(this, type, listener)
: this
}

function off (type, listener) {
return fn.call(this, type, listener) === false
? _off.call(this, type, listener)
: this
}
}

/**
* Reusable no-op function.
* @private
Expand Down

0 comments on commit 20d70d3

Please sign in to comment.