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

Support AbortController #2020

Merged
merged 20 commits into from Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions documentation/2-options.md
Expand Up @@ -209,6 +209,29 @@ await got('https://httpbin.org/anything');
#### **Note:**
> - If you're passing an absolute URL as `url`, you need to set `prefixUrl` to an empty string.


### `signal`

**Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)**

You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).

*Requires Node.js 16 or later.*

```js
import got from 'got';

const abortController = new AbortController();

const request = got('https://httpbin.org/anything', {
signal: abortController.signal
});

setTimeout(() => {
abortController.abort();
}, 100);
```

### `method`

**Type: `string`**\
Expand Down
6 changes: 6 additions & 0 deletions documentation/8-errors.md
Expand Up @@ -97,3 +97,9 @@ When the request is aborted with `promise.cancel()`.
**Code: `ERR_RETRYING`**

Always triggers a new retry when thrown.

### `AbortError`

**Code: `ERR_ABORTED`**

When the request is aborted with [AbortController.abort()](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort).
10 changes: 10 additions & 0 deletions source/core/errors.ts
Expand Up @@ -170,3 +170,13 @@ export class RetryError extends RequestError {
this.code = 'ERR_RETRYING';
}
}

/**
An error to be thrown when the request is aborted by AbortController.
*/
export class AbortError extends RequestError {
constructor(request: Request, error?: Error) {
super('This operation was aborted.', {...error, code: 'ERR_ABORTED'}, request);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of cloning error, please set this.code like in errors above.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since error (abortsignal.reason) is optional here, it seems passing error into the second argument of the constructor cause compile error.

// Compile error occurs

// Argument of type 'ErrnoException | undefined' is not assignable to parameter of type 'Partial<ErrnoException & { code?: string | undefined; }>'.
// Type 'undefined' is not assignable to type 'Partial<ErrnoException & { code?: string | undefined; }>'
super('This operation was aborted.', error, request);
this.code = 'ERR_ABORTED';

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, thanks for clarifying. In this case you can just skip this. Like so:

super('This operation was aborted.', {}, request);
this.name = 'AbortError';
this.code = 'ERR_ABORTED';

The reason is user accessible via controller.signal.reason, so I don't think we need to expose it for now. That might be for #1953

this.name = 'AbortError';
}
}
9 changes: 9 additions & 0 deletions source/core/index.ts
Expand Up @@ -31,6 +31,7 @@ import {
TimeoutError,
UploadError,
CacheError,
AbortError,
} from './errors.js';
import type {PlainResponse} from './response.js';
import type {PromiseCookieJar, NativeRequestOptions, RetryOptions} from './options.js';
Expand Down Expand Up @@ -235,6 +236,14 @@ export default class Request extends Duplex implements RequestEvents<Request> {
return;
}

if (this.options.signal?.aborted) {
this.destroy(new AbortError(this, (this.options.signal as any).reason));
}

this.options.signal?.addEventListener('abort', () => {
this.destroy(new AbortError(this, (this.options.signal as any).reason));
});

// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
Expand Down
32 changes: 32 additions & 0 deletions source/core/options.ts
Expand Up @@ -827,6 +827,7 @@ const defaultInternals: Options['_internals'] = {
},
setHost: true,
maxHeaderSize: undefined,
signal: undefined,
};

const cloneInternals = (internals: typeof defaultInternals) => {
Expand Down Expand Up @@ -1484,6 +1485,36 @@ export default class Options {
}
}

/**
You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).

__Requires Node.js 16 or later.__
szmarczak marked this conversation as resolved.
Show resolved Hide resolved

@example
```
import got from 'got';

const abortController = new AbortController();

const request = got('https://httpbin.org/anything', {
signal: abortController.signal
});

setTimeout(() => {
abortController.abort();
}, 100);
```
*/
get signal(): AbortSignal | undefined {
return this._internals.signal;
}

set signal(value: AbortSignal | undefined) {
assert.object(value);

this._internals.signal = value;
}

/**
Ignore invalid cookies instead of throwing an error.
Only useful when the `cookieJar` option has been set. Not recommended.
Expand Down Expand Up @@ -2473,5 +2504,6 @@ export default class Options {
Object.freeze(options.retry.methods);
Object.freeze(options.retry.statusCodes);
Object.freeze(options.context);
Object.freeze(options.signal);
}
}