diff --git a/core/packages/teeny-request/src/index.ts b/core/packages/teeny-request/src/index.ts index 931861ad798c..313e4ab101a0 100644 --- a/core/packages/teeny-request/src/index.ts +++ b/core/packages/teeny-request/src/index.ts @@ -278,10 +278,18 @@ function teenyRequest( let responseStream: any; requestStream.once('reading', () => { if (responseStream) { - pipeline(responseStream, requestStream, () => {}); + if (!requestStream.destroyed) { + pipeline(responseStream, requestStream, () => {}); + } else if (responseStream && typeof responseStream.destroy === 'function') { + responseStream.destroy(); + } } else { requestStream.once('response', () => { - pipeline(responseStream, requestStream, () => {}); + if (!requestStream.destroyed) { + pipeline(responseStream, requestStream, () => {}); + } else if (responseStream && typeof responseStream.destroy === 'function') { + responseStream.destroy(); + } }); } }); diff --git a/core/packages/teeny-request/test/index.ts b/core/packages/teeny-request/test/index.ts index e34d697a2a58..a7e4cb3de4f1 100644 --- a/core/packages/teeny-request/test/index.ts +++ b/core/packages/teeny-request/test/index.ts @@ -298,6 +298,25 @@ describe('teeny', () => { }); }); + it('should not pipe if request stream is destroyed early', done => { + const scope = mockJson(); + + const stream = teenyRequest({uri}); + stream.on('error', done); + + stream.once('response', response => { + response.body.once('close', () => { + scope.done(); + done(); + }); + + // Destroy the stream before piping can be fully set up + stream.destroy(); + }); + + stream.resume(); + }); + it('should expose TeenyStatistics instance', () => { assert.ok(teenyRequest.stats instanceof TeenyStatistics); });