Skip to content

Commit

Permalink
fix: alias connection to socket. (#1590)
Browse files Browse the repository at this point in the history
`ClientRequest.connection` is an alias for `ClientRequest.socket`.
https://nodejs.org/api/http.html#http_request_socket
https://github.com/nodejs/node/blob/master/lib/_http_client.js#L640-L641

`IncomingMessage.connection` is an alias for `IncomingMessage.socket`.
https://github.com/nodejs/node/blob/master/lib/_http_incoming.js#L44-L45

Co-Authored-By: Paul Melnikow <github@paulmelnikow.com>
  • Loading branch information
2 people authored and gr2m committed Jun 20, 2019
1 parent 9472ad0 commit 659bf01
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/request_overrider.js
Expand Up @@ -89,18 +89,22 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
)
}

if (!req.connection) {
req.connection = new EventEmitter()
}

req.path = options.path
req.method = options.method

options.getHeader = function(name) {
return getHeader(req, name)
}

req.socket = response.socket = Socket({ proto: options.proto })
// ClientRequest.connection is an alias for ClientRequest.socket
// https://nodejs.org/api/http.html#http_request_socket
// https://github.com/nodejs/node/blob/b0f75818f39ed4e6bd80eb7c4010c1daf5823ef7/lib/_http_client.js#L640-L641
// IncomingMessage.connection is an alias for IncomingMessage.socket
// https://github.com/nodejs/node/blob/b0f75818f39ed4e6bd80eb7c4010c1daf5823ef7/lib/_http_incoming.js#L44-L45
// The same Socket is shared between the request and response to mimic native behavior.
req.socket = req.connection = response.socket = response.connection = Socket({
proto: options.proto,
})

req.write = function(buffer, encoding, callback) {
debug('write', arguments)
Expand Down
15 changes: 15 additions & 0 deletions tests/test_request_overrider.js
Expand Up @@ -329,6 +329,21 @@ test('request emits socket', t => {
})
})

test('socket is shared and aliased correctly', t => {
nock('http://example.test')
.get('/')
.reply()

const req = http.get('http://example.test')

req.once('response', res => {
t.is(req.socket, req.connection)
t.is(req.socket, res.socket)
t.is(res.socket, res.connection)
t.end()
})
})

test('socket emits connect and secureConnect', t => {
t.plan(3)

Expand Down

0 comments on commit 659bf01

Please sign in to comment.