aboutsummaryrefslogtreecommitdiff
path: root/internal/ui/static/js/request_builder.js
blob: e19168fcfcba3941ba5a54e057570f5bdf9323c1 (plain) (blame)
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
class RequestBuilder {
    constructor(url) {
        this.callback = null;
        this.url = url;
        this.options = {
            method: "POST",
            cache: "no-cache",
            credentials: "include",
            body: null,
            headers: new Headers({
                "Content-Type": "application/json",
                "X-Csrf-Token": this.getCsrfToken()
            })
        };
    }

    withHttpMethod(method) {
        this.options.method = method;
        return this;
    }

    withBody(body) {
        this.options.body = JSON.stringify(body);
        return this;
    }

    withCallback(callback) {
        this.callback = callback;
        return this;
    }

    getCsrfToken() {
        let element = document.querySelector("body[data-csrf-token]");
        if (element !== null) {
            return element.dataset.csrfToken;
        }

        return "";
    }

    execute() {
        fetch(new Request(this.url, this.options)).then((response) => {
            if (this.callback) {
                this.callback(response);
            }
        });
    }
}