(url, hasBar = false, headers = {})
| 12 | * @return {Promise} Promise response |
| 13 | */ |
| 14 | export function get(url, hasBar = false, headers = {}) { |
| 15 | const xhr = new XMLHttpRequest(); |
| 16 | const on = function () { |
| 17 | xhr.addEventListener.apply(xhr, arguments); |
| 18 | }; |
| 19 | |
| 20 | const cached = cache[url]; |
| 21 | |
| 22 | if (cached) { |
| 23 | return { then: cb => cb(cached.content, cached.opt), abort: noop }; |
| 24 | } |
| 25 | |
| 26 | xhr.open('GET', url); |
| 27 | for (const i in headers) { |
| 28 | if (hasOwn.call(headers, i)) { |
| 29 | xhr.setRequestHeader(i, headers[i]); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | xhr.send(); |
| 34 | |
| 35 | return { |
| 36 | then: function (success, error = noop) { |
| 37 | if (hasBar) { |
| 38 | const id = setInterval( |
| 39 | _ => |
| 40 | progressbar({ |
| 41 | step: Math.floor(Math.random() * 5 + 1), |
| 42 | }), |
| 43 | 500 |
| 44 | ); |
| 45 | |
| 46 | on('progress', progressbar); |
| 47 | on('loadend', evt => { |
| 48 | progressbar(evt); |
| 49 | clearInterval(id); |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | on('error', error); |
| 54 | on('load', ({ target }) => { |
| 55 | if (target.status >= 400) { |
| 56 | error(target); |
| 57 | } else { |
| 58 | const result = (cache[url] = { |
| 59 | content: target.response, |
| 60 | opt: { |
| 61 | updatedAt: xhr.getResponseHeader('last-modified'), |
| 62 | }, |
| 63 | }); |
| 64 | |
| 65 | success(result.content, result.opt); |
| 66 | } |
| 67 | }); |
| 68 | }, |
| 69 | abort: _ => xhr.readyState !== 4 && xhr.abort(), |
| 70 | }; |
| 71 | } |
no test coverage detected