openapi-typescript-codegen icon indicating copy to clipboard operation
openapi-typescript-codegen copied to clipboard

Consider using AbortController.signal to cancel requests

Open aryzing opened this issue 4 years ago • 8 comments

The .cancel() method to cancel requests works great, and it's a great feature to have. It's a popular convention used by many network libraries, however, a convention notheless.

It would be great to add support for an AbortController.signal created outside the generated code so as to use a native browser api rather than a convention.

As an example, react-query has started to create it's own signals in addition to still supporting the .cancel() convention.

aryzing avatar Nov 19 '21 23:11 aryzing

@aryzing The only problem here is XHR support, at the moment we rely on a custom handler for this. Maybe we can reuse the AbortController and hook into that.

ferdikoomen avatar Nov 26 '21 19:11 ferdikoomen

is there any other possible way to cancel request right now?

mstosio avatar Dec 06 '21 16:12 mstosio

@mstosio You can cancel the promises that you get back from the service:

// Save the promise / request that comes out of the service call
const req = SomeService.someCall();

try {
    // Wait for result
    return await req;
} catch (e) {
    // The service can throw two errors (CancelError or ApiError)
    if (e instanceof CancelError) {
        console.log('Request got cancelled');
    }
    if (e instanceof ApiError) {
        console.log('Request returned with an error');
    }
}

// We can cancel the request by canceling the promise
setTimeout(() => {
    req.cancel();
}, 1000);

ferdikoomen avatar Jan 24 '22 22:01 ferdikoomen

@ferdikoomen my org would be willing to contribute a fix to use AbortController because CancelablePromise is just a convention and it also causes teams to have to adjust their jest tests in an inconvenient way rather than using built-in mockImplementation(async () => { ... }). I just have two questions:

  • Which clients should use AbortController?

    • I'm assuming everything except Angular and XHR, based on code observation and your comment above
  • Is it OK that we have an additional condition for this in the handlebar(s) file(s)?

wbern avatar Mar 11 '22 15:03 wbern

@ferdikoomen Additionally, would it make sense to let consumers provide a custom promise transform function as a short term solution? That way, we can change CancelablePromise to Promise, and not break our test APIs.

wbern avatar Mar 17 '22 09:03 wbern

This would be great to use with react-query with just being able to pass the signal through.

sebasptsch avatar Nov 10 '22 11:11 sebasptsch