Skip to content

Commit

Permalink
Make http requests cancelable
Browse files Browse the repository at this point in the history
  • Loading branch information
serg-plusplus authored Nov 22, 2020
1 parent 94866af commit 6a0e47b
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion packages/taquito-http-utils/src/taquito-http-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ interface HttpRequestOptions {
json?: boolean;
query?: { [key: string]: any };
headers?: { [key: string]: string };
signal?: AbortSignal;
}

export class HttpResponseError implements Error {
Expand Down Expand Up @@ -85,10 +86,15 @@ export class HttpBackend {
* @param options contains options to be passed for the HTTP request (url, method and timeout)
*/
createRequest<T>(
{ url, method, timeout, query, headers = {}, json = true }: HttpRequestOptions,
{ url, method, timeout, query, headers = {}, json = true, signal }: HttpRequestOptions,
data?: {}
) {
return new Promise<T>((resolve, reject) => {
const cancel = () => reject(new Error("Request cancelled"));
if (signal && signal.aborted) {
return cancel();
}

const request = this.createXHR();
request.open(method || 'GET', `${url}${this.serialize(query)}`);
request.setRequestHeader('Content-Type', 'application/json');
Expand Down Expand Up @@ -127,6 +133,22 @@ export class HttpBackend {
request.onerror = function(err) {
reject(new HttpRequestFailed(url, err));
};

request.onabort = function() {
cancel();
};

if (signal) {
const abort = () => request.abort();
signal.addEventListener("abort", abort);

request.onreadystatechange = function() {
if (this.readyState === 4) {
// clean handler after XHR done
signal.removeEventListener("abort", abort);
}
};
}

if (data) {
const dataStr = JSON.stringify(data);
Expand Down

0 comments on commit 6a0e47b

Please sign in to comment.