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 for AbortController #380

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

oliver-s-lee
Copy link

Hi there, thanks for the nice project.

This small PR adds support for Node's AbortController, which is the currently recommended way to abort requests in flight. I couldn't see any way to achieve this in the current version, and as the change is relatively minor I've put this PR quickly together to demonstrate what I mean. AbortControllers are already supported by the underlying http.request() and https.request() methods; this PR simply passes an optional AbortSignal object through the various function calls to the underlying request.

Usage:

// Abort controllers are setup in the usual way.
const controller = new AbortController();

// RestClient also supported.
const client = new HttpClient(
    // Other options.
);

// When you make a request, you can pass the signal from the AbortController.
const request = client.get(
    "https://github.com/",
    {},  // Headers.
    controller.signal
);

// If we change our minds, we can now cancel the request.
controller.abort("No longer needed");

// Causing the promise to reject.
try {
    const val = await request;
} catch (err) {
    console.log(err); // AbortError: No longer needed
}

Abort controllers are (sadly) single use only so specifying at the constructor/object level doesn't really make sense, hence the addition to the method call directly. Some of the method signatures are now getting a bit messy however, it might be more desirable to add signal to the IRequestOptions or similar instead...

Apologies if this functionality is unwanted/covered elsewhere.

@oliver-s-lee oliver-s-lee requested review from a team as code owners November 20, 2024 16:08
@oliver-s-lee
Copy link
Author

@microsoft-github-policy-service agree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant