Skip to content

Commit 659bf01

Browse files
mastermattpaulmelnikow
authored andcommitted
fix: alias connection to socket. (#1590)
`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>
1 parent 9472ad0 commit 659bf01

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

lib/request_overrider.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,18 +89,22 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
8989
)
9090
}
9191

92-
if (!req.connection) {
93-
req.connection = new EventEmitter()
94-
}
95-
9692
req.path = options.path
9793
req.method = options.method
9894

9995
options.getHeader = function(name) {
10096
return getHeader(req, name)
10197
}
10298

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

105109
req.write = function(buffer, encoding, callback) {
106110
debug('write', arguments)

tests/test_request_overrider.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,21 @@ test('request emits socket', t => {
329329
})
330330
})
331331

332+
test('socket is shared and aliased correctly', t => {
333+
nock('http://example.test')
334+
.get('/')
335+
.reply()
336+
337+
const req = http.get('http://example.test')
338+
339+
req.once('response', res => {
340+
t.is(req.socket, req.connection)
341+
t.is(req.socket, res.socket)
342+
t.is(res.socket, res.connection)
343+
t.end()
344+
})
345+
})
346+
332347
test('socket emits connect and secureConnect', t => {
333348
t.plan(3)
334349

0 commit comments

Comments
 (0)