Skip to content

Commit

Permalink
Apply destroy patch
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Feb 26, 2021
1 parent 2675046 commit 31d80ef
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import http2wrapper = require('http2-wrapper');
import lowercaseKeys = require('lowercase-keys');
import ResponseLike = require('responselike');
import is, {assert} from '@sindresorhus/is';
import applyDestroyPatch from './utils/apply-destroy-patch';
import getBodySize from './utils/get-body-size';
import isFormData from './utils/is-form-data';
import proxyEvents from './utils/proxy-events';
Expand Down Expand Up @@ -1379,6 +1380,9 @@ export default class Request extends Duplex implements RequestEvents<Request> {
highWaterMark: 0
});

// TODO: Remove this when targeting Node.js 14
applyDestroyPatch(this);

this[kDownloadedSize] = 0;
this[kUploadedSize] = 0;
this.requestInitialized = false;
Expand Down
18 changes: 18 additions & 0 deletions source/core/utils/apply-destroy-patch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {Readable, Writable} from 'stream';

export default function applyDestroyPatch(stream: Readable | Writable): void {
const kDestroy = Symbol('destroy');

if (Number(process.versions.node.split('.')[0]) >= 14) {
return;
}

// @ts-expect-error
stream[kDestroy] = stream.destroy;
stream.destroy = (...args) => {
if (!stream.destroyed) {
// @ts-expect-error
return stream[kDestroy](...args);
}
};
}
17 changes: 17 additions & 0 deletions test/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as FormData from 'form-data';
import is from '@sindresorhus/is';
import got, {RequestError} from '../source/index';
import withServer from './helpers/with-server';
import delay = require('delay');

const pStreamPipeline = promisify(stream.pipeline);

Expand Down Expand Up @@ -419,6 +420,22 @@ test('async iterator works', withServer, async (t, server, got) => {
t.is(Buffer.concat(chunks).toString(), payload);
});

test('destroys only once', async t => {
const stream = got.stream('https://example.com');
stream.destroy();
stream.destroy(new Error('oh no'));

let errored = false;

stream.once('error', () => {
errored = true;
});

await delay(1);

t.false(errored);
});

if (Number.parseInt(process.versions.node.split('.')[0]!, 10) <= 12) {
test('does not emit end event on error', withServer, async (t, server, got) => {
server.get('/', infiniteHandler);
Expand Down

0 comments on commit 31d80ef

Please sign in to comment.