|
| 1 | +/* @flow */ |
| 2 | + |
| 3 | +type Options = { |
| 4 | + method?: string, |
| 5 | + url: string, |
| 6 | + params?: |
| 7 | + | string |
| 8 | + | { |
| 9 | + [name: string]: string, |
| 10 | + }, |
| 11 | + headers?: Object, |
| 12 | + timeout?: number, |
| 13 | +}; |
| 14 | + |
| 15 | +/** |
| 16 | + * Utility that promisifies XMLHttpRequest in order to have a nice API that supports cancellation. |
| 17 | + * @param method |
| 18 | + * @param url |
| 19 | + * @param params -> This is the body payload for POST requests |
| 20 | + * @param headers |
| 21 | + * @param timeout -> Timeout for rejecting the promise and aborting the API request |
| 22 | + * @returns {Promise} |
| 23 | + */ |
| 24 | +export default function makeHttpRequest( |
| 25 | + { method = 'get', url, params, headers, timeout = 10000 }: Options = {}, |
| 26 | +) { |
| 27 | + return new Promise((resolve: any, reject: any) => { |
| 28 | + const xhr = new XMLHttpRequest(); |
| 29 | + |
| 30 | + const tOut = setTimeout(() => { |
| 31 | + xhr.abort(); |
| 32 | + reject('timeout'); |
| 33 | + }, timeout); |
| 34 | + |
| 35 | + xhr.open(method, url); |
| 36 | + xhr.onload = function onLoad() { |
| 37 | + if (this.status >= 200 && this.status < 300) { |
| 38 | + clearTimeout(tOut); |
| 39 | + resolve(xhr.response); |
| 40 | + } else { |
| 41 | + clearTimeout(tOut); |
| 42 | + reject({ |
| 43 | + status: this.status, |
| 44 | + statusText: xhr.statusText, |
| 45 | + }); |
| 46 | + } |
| 47 | + }; |
| 48 | + xhr.onerror = function onError() { |
| 49 | + clearTimeout(tOut); |
| 50 | + reject({ |
| 51 | + status: this.status, |
| 52 | + statusText: xhr.statusText, |
| 53 | + }); |
| 54 | + }; |
| 55 | + if (headers) { |
| 56 | + Object.keys(headers).forEach((key: string) => { |
| 57 | + xhr.setRequestHeader(key, headers[key]); |
| 58 | + }); |
| 59 | + } |
| 60 | + let requestParams = params; |
| 61 | + // We'll need to stringify if we've been given an object |
| 62 | + // If we have a string, this is skipped. |
| 63 | + if (requestParams && typeof requestParams === 'object') { |
| 64 | + requestParams = Object.keys(requestParams) |
| 65 | + .map( |
| 66 | + (key: string) => |
| 67 | + `${encodeURIComponent(key)}=${encodeURIComponent( |
| 68 | + // $FlowFixMe |
| 69 | + requestParams[key], |
| 70 | + )}`, |
| 71 | + ) |
| 72 | + .join('&'); |
| 73 | + } |
| 74 | + xhr.send(params); |
| 75 | + }); |
| 76 | +} |
0 commit comments