-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
ajax.js
71 lines (61 loc) · 1.63 KB
/
ajax.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* eslint-disable no-unused-vars */
import progressbar from '../render/progressbar';
import { noop, hasOwn } from '../util/core';
const cache = {};
/**
* Ajax GET implmentation
* @param {string} url Resource URL
* @param {boolean} [hasBar=false] Has progress bar
* @param {String[]} headers Array of headers
* @return {Promise} Promise response
*/
export function get(url, hasBar = false, headers = {}) {
const xhr = new XMLHttpRequest();
const on = function() {
xhr.addEventListener.apply(xhr, arguments);
};
const cached = cache[url];
if (cached) {
return { then: cb => cb(cached.content, cached.opt), abort: noop };
}
xhr.open('GET', url);
for (const i in headers) {
if (hasOwn.call(headers, i)) {
xhr.setRequestHeader(i, headers[i]);
}
}
xhr.send();
return {
then: function(success, error = noop) {
if (hasBar) {
const id = setInterval(
_ =>
progressbar({
step: Math.floor(Math.random() * 5 + 1),
}),
500
);
on('progress', progressbar);
on('loadend', evt => {
progressbar(evt);
clearInterval(id);
});
}
on('error', error);
on('load', ({ target }) => {
if (target.status >= 400) {
error(target);
} else {
const result = (cache[url] = {
content: target.response,
opt: {
updatedAt: xhr.getResponseHeader('last-modified'),
},
});
success(result.content, result.opt);
}
});
},
abort: _ => xhr.readyState !== 4 && xhr.abort(),
};
}