-
Notifications
You must be signed in to change notification settings - Fork 271
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Replaced fetch by promisified xmlhttprequest (#61)
- Loading branch information
Showing
3 changed files
with
465 additions
and
118 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
} |
Oops, something went wrong.