Skip to content

Commit

Permalink
Fix support for AbortSignal#timeout() (#2388)
Browse files Browse the repository at this point in the history
  • Loading branch information
katsanva authored Nov 4, 2024
1 parent f4f3ba8 commit 92b378e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
7 changes: 6 additions & 1 deletion source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,12 @@ export default class Request extends Duplex implements RequestEvents<Request> {

if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
// See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static#return_value
if (this.options.signal?.reason?.name === 'TimeoutError') {
this.destroy(new TimeoutError(this.options.signal.reason, this.timings!, this));
} else {
this.destroy(new AbortError(this));
}
};

if (this.options.signal.aborted) {
Expand Down
52 changes: 52 additions & 0 deletions test/abort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,55 @@ test('support setting the signal as a default option', async t => {

t.true(signalHandlersRemoved(), 'Abort signal event handlers not removed');
});

const timeoutErrorCode = 23;
// See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
test('support AbortSignal.timeout()', async t => {
const signal = AbortSignal.timeout(1);

const p = got('http://example.com', {signal});

await t.throwsAsync(p, {
code: timeoutErrorCode,
message: 'The operation was aborted due to timeout',
});
});

test('support AbortSignal.timeout() without user abort', async t => {
const {controller, signalHandlersRemoved} = createAbortController();
const timeoutSignal = AbortSignal.timeout(1);
const signal = AbortSignal.any([
controller.signal,
timeoutSignal,
]);
const p = got('http://example.com', {signal});

await t.throwsAsync(p, {
code: timeoutErrorCode,
message: 'The operation was aborted due to timeout',
});

t.true(signalHandlersRemoved(), 'Abort signal event handlers not removed');
});

test('support AbortSignal.timeout() with user abort', async t => {
const {controller, signalHandlersRemoved} = createAbortController();
const timeoutSignal = AbortSignal.timeout(1000);
const signal = AbortSignal.any([
controller.signal,
timeoutSignal,
]);

setTimeout(() => {
controller.abort();
}, 10);

const p = got('http://example.com', {signal});

await t.throwsAsync(p, {
code: 'ERR_ABORTED',
message: 'This operation was aborted.',
});

t.true(signalHandlersRemoved(), 'Abort signal event handlers not removed');
});

0 comments on commit 92b378e

Please sign in to comment.