Search code examples
typescriptautorest

How do you cancel ongoing client request when using Autorest with typescript?


Is there a way to abort an ongoing client request when using Autorest with typescript?

I noticed the ServiceClient object has the ability to specify RequestPrepareOptions, but I'm unclear how to pass the request options to the outgoing request method. Or perhaps there's another means to do the cancelation?


Solution

  • It seems you can use the browser abortController mechanism. You have to create an abort signal:

    The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.

    var controller = new AbortController();
    var signal = controller.signal;
    

    ...

    Then pass it in OperationArguments.options.abortSignal when calling

    function sendOperationRequest<T>(operationArguments: OperationArguments, operationSpec: OperationSpec)
    

    Then call aborton then abortController :

    abortBtn.addEventListener('click', function() {
      controller.abort();
      console.log('Download aborted');
    });
    

    ...and the promise returned by sendOperationRequest shall be rejected with an abortError.

    See provided javascript example : https://mdn.github.io/dom-examples/abort-api/

    Note: The feature is marked experimental, so it may not be supported by all browsers.