Skip to content

Commit

Permalink
fix: add more strict check for streams in `util.isStream()' (#628)
Browse files Browse the repository at this point in the history
* fix: add more strict check for streams in `util.isStream()'

* fix: split `isReadable()` & `isWritable()` for more specific checks

* fix: delete was not working to remove `destroy()`
  • Loading branch information
jarrodconnolly authored Mar 27, 2021
1 parent 858a0f4 commit f098adf
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/core/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class Request {

if (body == null) {
this.body = null
} else if (util.isStream(body)) {
} else if (util.isReadable(body)) {
this.body = body
} else if (util.isBuffer(body)) {
this.body = body.length ? body : null
Expand Down
15 changes: 13 additions & 2 deletions lib/core/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,18 @@ const { InvalidArgumentError } = require('./errors')

function nop () {}

function isStream (body) {
return !!(body && typeof body.on === 'function')
function isReadable (obj) {
return !!(obj && typeof obj.pipe === 'function' &&
typeof obj.on === 'function')
}

function isWritable (obj) {
return !!(obj && typeof obj.write === 'function' &&
typeof obj.on === 'function')
}

function isStream (obj) {
return isReadable(obj) || isWritable(obj)
}

function parseURL (url) {
Expand Down Expand Up @@ -163,6 +173,7 @@ module.exports = {
getServerName,
errnoException,
isStream,
isReadable,
isDestroyed,
parseHeaders,
parseKeepAliveTimeout,
Expand Down
4 changes: 3 additions & 1 deletion test/stream-compat.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const { test } = require('tap')
const { Client } = require('..')
const { createServer } = require('http')
const { Readable } = require('stream')
const EE = require('events')

test('stream body without destroy', (t) => {
Expand All @@ -17,7 +18,8 @@ test('stream body without destroy', (t) => {
t.teardown(client.destroy.bind(client))

const signal = new EE()
const body = new EE()
const body = new Readable({ read () {} })
body.destroy = undefined
body.on('error', (err) => {
t.ok(err)
})
Expand Down
21 changes: 21 additions & 0 deletions test/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict'

const t = require('tap')
const { test } = t
const { Stream } = require('stream')
const { EventEmitter } = require('events')

const util = require('../lib/core/util')

test('isStream', (t) => {
t.plan(3)

const stream = new Stream()
t.ok(util.isStream(stream))

const buffer = Buffer.alloc(0)
t.notOk(util.isStream(buffer))

const ee = new EventEmitter()
t.notOk(util.isStream(ee))
})

0 comments on commit f098adf

Please sign in to comment.