Skip to content

Commit

Permalink
Attempt to skip emitting uploadProgress after destroy
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Sep 2, 2022
1 parent b671480 commit 693de21
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
6 changes: 4 additions & 2 deletions source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,8 @@ export default class Request extends Duplex implements RequestEvents<Request> {
return;
}

if (!error) {
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && this._request!.destroyed) {
this._bodySize = this._uploadedSize;

this.emit('uploadProgress', this.uploadProgress);
Expand Down Expand Up @@ -1178,7 +1179,8 @@ export default class Request extends Duplex implements RequestEvents<Request> {
}

this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
if (!error) {
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);

const progress = this.uploadProgress;
Expand Down
28 changes: 28 additions & 0 deletions test/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,31 @@ test('formdata retry', withServer, async (t, server, got) => {
message: 'Cannot retry with consumed body stream',
});
});

test('does not emit uploadProgress after cancelation', withServer, async (t, server, got) => {
server.post('/', () => {});

const stream = got.stream.post();

stream.once('uploadProgress', () => { // 0%
stream.once('uploadProgress', () => { // 'foo'
stream.write('bar');

process.nextTick(() => {
process.nextTick(() => {
stream.on('uploadProgress', () => {
t.fail('Emitted uploadProgress after cancelation');
});

stream.destroy();
});
});
});
});

stream.write('foo');

await pEvent(stream, 'close');

t.pass();
});

0 comments on commit 693de21

Please sign in to comment.