diff options
Diffstat (limited to 'assets_src/js/lib/ajax.js')
-rw-r--r-- | assets_src/js/lib/ajax.js | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/assets_src/js/lib/ajax.js b/assets_src/js/lib/ajax.js new file mode 100644 index 0000000..048f516 --- /dev/null +++ b/assets_src/js/lib/ajax.js | |||
@@ -0,0 +1,60 @@ | |||
1 | export class AjaxError extends Error { | ||
2 | constructor(status, statusText) { | ||
3 | let message = `${status}: ${statusText}` | ||
4 | super(message); | ||
5 | this.name = this.constructor.name; | ||
6 | this.message = message; | ||
7 | this.status = status; | ||
8 | this.statusText = statusText; | ||
9 | Error.captureStackTrace(this, this.constructor.name) | ||
10 | } | ||
11 | } | ||
12 | |||
13 | function applyOptions(xhr, options) { | ||
14 | options.headers = options.headers || []; | ||
15 | for (let header in options.headers) { | ||
16 | xhr.setRequestHeader(header, options.headers[header]); | ||
17 | } | ||
18 | } | ||
19 | |||
20 | function createHandler(xhr, success, fail) { | ||
21 | return () => { | ||
22 | if (xhr.readyState !== XMLHttpRequest.DONE) { | ||
23 | return; | ||
24 | } | ||
25 | if (xhr.status === 200) { | ||
26 | success(xhr.response); | ||
27 | } else { | ||
28 | fail(xhr.status, xhr.statusText); | ||
29 | } | ||
30 | }; | ||
31 | } | ||
32 | |||
33 | function request(method, url, body, options) { | ||
34 | options = options || {}; | ||
35 | return new Promise((resolve, reject) => { | ||
36 | let xhr = new XMLHttpRequest(); | ||
37 | xhr.onreadystatechange = createHandler( | ||
38 | xhr, | ||
39 | (res) => { | ||
40 | resolve(res); | ||
41 | }, | ||
42 | (status, statusText) => { | ||
43 | reject(new AjaxError(status, statusText)); | ||
44 | }); | ||
45 | xhr.open(method, url, true); | ||
46 | applyOptions(xhr, options); | ||
47 | xhr.onerror = function() { | ||
48 | reject(new AjaxError(-1, 'Network error')); | ||
49 | }; | ||
50 | xhr.send(body); | ||
51 | }); | ||
52 | } | ||
53 | |||
54 | export async function get(url, options) { | ||
55 | return request('GET', url, null, options); | ||
56 | } | ||
57 | |||
58 | export async function post(url, body, options) { | ||
59 | return request('POST', url, body, options); | ||
60 | } | ||