summaryrefslogtreecommitdiff
path: root/static/js/controllers/base_controller.js
blob: 84d7dbb3c5adc566ce67a7b940568ab39ca5c969 (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
/* @license 
magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0 
@license-end */

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, form = new FormData(event.target)) {
		event.preventDefault();

		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;
		}
	}
}