Skip to content

Commit

Permalink
Replaced fetch by promisified xmlhttprequest (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
comur authored and Raúl Gómez Acuña committed Dec 14, 2017
1 parent 6f13465 commit 458fe55
Show file tree
Hide file tree
Showing 3 changed files with 465 additions and 118 deletions.
15 changes: 7 additions & 8 deletions src/checkInternetAccess.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
/* @flow */
import makeHttpRequest from './makeHttpRequest';

export default function checkInternetAccess(
timeout: number = 3000,
address: string = 'https://google.com',
url: string = 'https://google.com',
): Promise<boolean> {
return new Promise((resolve: (value: boolean) => void) => {
const tm = setTimeout(() => {
resolve(false);
}, timeout);

fetch(address, { method: 'HEAD' })
makeHttpRequest({
method: 'HEAD',
url,
timeout,
})
.then(() => {
clearTimeout(tm);
resolve(true);
})
.catch(() => {
clearTimeout(tm);
resolve(false);
});
});
Expand Down
76 changes: 76 additions & 0 deletions src/makeHttpRequest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/* @flow */

type Options = {
method?: string,
url: string,
params?:
| string
| {
[name: string]: string,
},
headers?: Object,
timeout?: number,
};

/**
* Utility that promisifies XMLHttpRequest in order to have a nice API that supports cancellation.
* @param method
* @param url
* @param params -> This is the body payload for POST requests
* @param headers
* @param timeout -> Timeout for rejecting the promise and aborting the API request
* @returns {Promise}
*/
export default function makeHttpRequest(
{ method = 'get', url, params, headers, timeout = 10000 }: Options = {},
) {
return new Promise((resolve: any, reject: any) => {
const xhr = new XMLHttpRequest();

const tOut = setTimeout(() => {
xhr.abort();
reject('timeout');
}, timeout);

xhr.open(method, url);
xhr.onload = function onLoad() {
if (this.status >= 200 && this.status < 300) {
clearTimeout(tOut);
resolve(xhr.response);
} else {
clearTimeout(tOut);
reject({
status: this.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function onError() {
clearTimeout(tOut);
reject({
status: this.status,
statusText: xhr.statusText,
});
};
if (headers) {
Object.keys(headers).forEach((key: string) => {
xhr.setRequestHeader(key, headers[key]);
});
}
let requestParams = params;
// We'll need to stringify if we've been given an object
// If we have a string, this is skipped.
if (requestParams && typeof requestParams === 'object') {
requestParams = Object.keys(requestParams)
.map(
(key: string) =>
`${encodeURIComponent(key)}=${encodeURIComponent(
// $FlowFixMe
requestParams[key],
)}`,
)
.join('&');
}
xhr.send(params);
});
}
Loading

0 comments on commit 458fe55

Please sign in to comment.