Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix signal handling for Request objects #613

Merged
merged 4 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions source/core/Ky.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,10 @@ export class Ky {

if (supportsAbortController) {
this.abortController = new globalThis.AbortController();
if (this._options.signal) {
const originalSignal = this._options.signal;

this._options.signal.addEventListener('abort', () => {
this.abortController!.abort(originalSignal.reason);
});
}
const originalSignal = this._options.signal ?? (this._input as Request).signal;
originalSignal?.addEventListener('abort', () => {
this.abortController!.abort(originalSignal.reason);
});

this._options.signal = this.abortController.signal;
}
Expand Down
17 changes: 17 additions & 0 deletions test/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,23 @@ test('throws DOMException/Error with name AbortError when aborted by user', asyn
t.is(error.name, 'AbortError', `Expected AbortError, got ${error.name}`);
});

test('throws AbortError when aborted via Request', async t => {
const server = await createHttpTestServer();
// eslint-disable-next-line @typescript-eslint/no-empty-function
server.get('/', () => {});

const abortController = new AbortController();
const {signal} = abortController;
const request = new Request(server.url, {signal});
const response = ky(request);
abortController.abort();

const error = (await t.throwsAsync(response))!;

t.true(['DOMException', 'Error'].includes(error.constructor.name), `Expected DOMException or Error, got ${error.constructor.name}`);
t.is(error.name, 'AbortError', `Expected AbortError, got ${error.name}`);
});

test('supports Request instance as input', async t => {
const server = await createHttpTestServer();
const inputRequest = new Request(server.url, {method: 'POST'});
Expand Down