Skip to content

Commit 71d61d7

Browse files
fix: Use PassThrough instead of stubbing (#306)
1 parent 9e77721 commit 71d61d7

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

lib/request.js

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
'use strict';
22

33
const http = require('http');
4+
const { PassThrough } = require('stream');
45

56
module.exports = class ServerlessRequest extends http.IncomingMessage {
67
constructor({ method, url, headers, body, remoteAddress }) {
7-
super({
8-
encrypted: true,
9-
readable: false,
10-
remoteAddress,
11-
address: () => ({ port: 443 }),
12-
end: Function.prototype,
13-
destroy: Function.prototype
14-
});
8+
// Create a real readable socket for IncomingMessage instead of a stub.
9+
const socket = new PassThrough();
10+
socket.encrypted = true;
11+
socket.remoteAddress = remoteAddress;
12+
socket.address = () => ({ port: 443 });
13+
14+
super(socket);
1515

1616
if (typeof headers['content-length'] === 'undefined') {
1717
headers['content-length'] = Buffer.byteLength(body);
@@ -29,10 +29,18 @@ module.exports = class ServerlessRequest extends http.IncomingMessage {
2929
url,
3030
});
3131

32+
// Make the request stream readable by pushing the body when consumed.
3233
this._read = () => {
33-
this.push(body);
34+
if (typeof body !== 'undefined' && body !== null) {
35+
this.push(body);
36+
}
3437
this.push(null);
3538
};
36-
}
3739

38-
}
40+
// If there's no body, emit 'end' on next tick so on-finished(req) fires
41+
// even when no one consumes the stream.
42+
if (!body || Buffer.byteLength(body) === 0) {
43+
setImmediate(() => this.emit('end'));
44+
}
45+
}
46+
};

0 commit comments

Comments
 (0)