Skip to content

Commit

Permalink
Fix handling of a signal that is already aborted before the request b…
Browse files Browse the repository at this point in the history
…egins (#663)

* fix: throw early if signal is aborted before request is triggered

* fix: abort if the original signal also aborted early

* fix: linter issues

* fix: pass abort reason to early abort

* fix: check if server receives request after abort

* fix: lint issues
  • Loading branch information
kadhirr authored Dec 18, 2024
1 parent 1d92c20 commit 6d06338
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
5 changes: 4 additions & 1 deletion source/core/Ky.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,13 @@ export class Ky {
if (supportsAbortController) {
this.abortController = new globalThis.AbortController();
const originalSignal = this._options.signal ?? (this._input as Request).signal;
if (originalSignal?.aborted) {
this.abortController.abort(originalSignal?.reason);
}

originalSignal?.addEventListener('abort', () => {
this.abortController!.abort(originalSignal.reason);
});

this._options.signal = this.abortController.signal;
}

Expand Down
20 changes: 20 additions & 0 deletions test/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,26 @@ 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 signal was aborted before request', async t => {
const server = await createHttpTestServer();
let requestCount = 0;
server.get('/', () => {
requestCount += 1;
});

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

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}`);
t.is(requestCount, 0, 'Request count is more than 0, server received request.');
});

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

0 comments on commit 6d06338

Please sign in to comment.