Skip to content

Commit

Permalink
[NetworkRequest] make requests cancellable #46 (#56)
Browse files Browse the repository at this point in the history
* only call the xhr abort if the request has been sent

* test request constructor to get at least a bit of coverage
  • Loading branch information
TitanNano authored Jun 15, 2018
1 parent b3282dd commit db67432
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 3 deletions.
20 changes: 20 additions & 0 deletions core/NetworkRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ const stripHashKey = function(object) {
return object;
};

const xhrMap = new WeakMap();

/**
* A network request
*/
Expand Down Expand Up @@ -71,6 +73,9 @@ const NetworkRequest = {
*/
completed: false,

/** @type {Promise} */
promise: null,

/**
* The constructor for the NetworkRequest. It simply sets up the properties.
*
Expand Down Expand Up @@ -159,6 +164,8 @@ const NetworkRequest = {
send() {
const xhr = new XMLHttpRequest();

xhrMap.set(this, xhr);

if (this.method === 'GET' && this._body) {
this.url += `?${ Object.keys(this._body).map((key) => {
return `${key}=${this._body[key]}`;
Expand Down Expand Up @@ -211,9 +218,22 @@ const NetworkRequest = {
xhr.send(this._body);
}

this.promise = promise;

return promise;
},

cancel() {
/** @type {XMLHttpRequest} */
const xhr = xhrMap.get(this);

if (!xhr) {
return;
}

return xhr.abort();
},

__proto__: EventTarget,
};

Expand Down
21 changes: 21 additions & 0 deletions tests/NetworkRequest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/* eslint-env mocha */

const istanbulVM = require('../testable/node/istanbulVM');
const expect = require('chai').expect;


describe('NetworkRequest', () => {
const vm = istanbulVM();

istanbulVM.applyNodeEnv(vm);

vm.runModule('../testable/core/NetworkRequest');

it('should construct a new request', () => {
const result = vm.runModule('./testTasks/NetworkRequest/construct');

expect(result.instance.url).to.equal('https://example.org');
expect(result.instance.method).to.equal('POST');
expect(result.instance.type).to.equal('json');
});
});
4 changes: 1 addition & 3 deletions tests/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ describe('Prototypes', () => {
require('./EventTarget.js');
require('./Catalog');

describe('NetworkReqest', () => {
Import('../../testable/core/NetworkRequest');
});
require('./NetworkRequest');
});

describe('ServiceWorker', () => {
Expand Down
3 changes: 3 additions & 0 deletions tests/testTasks/NetworkRequest/construct.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* global NetworkRequest */
global.NetworkRequest = NetworkRequest;
global.instance = Object.create(NetworkRequest).constructor('https://example.org', { method: 'POST', type: 'json' });

0 comments on commit db67432

Please sign in to comment.