Skip to content

Commit

Permalink
fix: correct support for AbortSignal:timeout()
Browse files Browse the repository at this point in the history
  • Loading branch information
katsanva committed Nov 2, 2024
1 parent f4f3ba8 commit ec31144
Show file tree
Hide file tree
Showing 2 changed files with 57 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
51 changes: 51 additions & 0 deletions test/abort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,54 @@ test('support setting the signal as a default option', async t => {

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

// 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: 23,
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: 23,
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 ec31144

Please sign in to comment.