summaryrefslogtreecommitdiff
path: root/static/js/controllers/base_controller.js
blob: fc05e290855b0be5924816afdfd92927c3704344 (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
export class BaseController {
    constructor() {
	this.comments_server_url = document.getElementById('comments-client').src;
	this.origin = window.location.origin;
	this.protocol = this.getProtocol();
	this.domain = this.getDomain();
	this.post = window.location.pathname;
	this.comments_server_host = `${this.protocol}//${this.domain}`;
	this.parser = new DOMParser();
    }

    async submit(event, route) {
	event.preventDefault();
	const form = new FormData(event.target);

	try {
	    const response = await fetch(route, { method: "POST", body: form });

	    response.text().then((response_document) => {
		this.renderSubmitResponse(response_document);
	    });
	} catch(error) {}
    }

    getDomain() {
	return this.comments_server_url.split('/')[2];
    }

    getProtocol() {
	return this.comments_server_url.split('/')[0];
    }

    htmlFromResponse(body) {
	return this.parser.parseFromString(body, "text/html");
    }

    async get(route) {
	try {
	    const response = await fetch(`${this.comments_server_host}${route}`);

	    return response.text().then(this.htmlFromResponse.bind(this));
	} catch(error) {
	    return null;
	}
    }
}