aboutsummaryrefslogtreecommitdiff
path: root/assets_src/js/lib/ajax.js
blob: 048f516e5379aa76f65c1608faa141ee0c1edbef (plain)
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
export class AjaxError extends Error {
	constructor(status, statusText) {
		let message = `${status}: ${statusText}`
		super(message);
		this.name = this.constructor.name;
		this.message = message;
		this.status = status;
		this.statusText = statusText;
		Error.captureStackTrace(this, this.constructor.name)
	}
}

function applyOptions(xhr, options) {
	options.headers = options.headers || [];
	for (let header in options.headers) {
		xhr.setRequestHeader(header, options.headers[header]);
	}
}

function createHandler(xhr, success, fail) {
	return () => {
		if (xhr.readyState !== XMLHttpRequest.DONE) {
			return;
		}
		if (xhr.status === 200) {
			success(xhr.response);
		} else {
			fail(xhr.status, xhr.statusText);
		}
	};
}

function request(method, url, body, options) {
	options = options || {};
	return new Promise((resolve, reject) => {
		let xhr = new XMLHttpRequest();
		xhr.onreadystatechange = createHandler(
			xhr,
			(res) => {
				resolve(res);
			},
			(status, statusText) => {
				reject(new AjaxError(status, statusText));
			});
		xhr.open(method, url, true);
		applyOptions(xhr, options);
		xhr.onerror = function() {
			reject(new AjaxError(-1, 'Network error'));
		};
		xhr.send(body);
	});
}

export async function get(url, options) {
	return request('GET', url, null, options);
}

export async function post(url, body, options) {
	return request('POST', url, body, options);
}