Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
HTML
<style>
.apitester {
    box-sizing: border-box;
    border: 1px solid #eaeaea;
    font-family: sans-serif;
}

.apitester * {
    box-sizing: border-box;
}

.apitester h3.api input,
.api button {
    margin: 0;
}

.apitester pre {
    margin: 0;
    font-family: monospace;
}

.apitester-editor {
    padding: 1rem;
}

.apitester-editor>div {
    margin-top: 0.5rem;
}

.apitester-link {
    display: inline-block;
    margin-left: 1rem;
    color: #0000EE;
}

.apitester-link:hover {
    text-decoration: none;
}

.apitester-link:visited {
    color: #0000EE;
}


.apitester [data-ref=method] {
    display: inline-block;
}

.apitester [data-ref=host] {
    display: inline-block;
    resize: horizontal;
    border: 1px solid #eaeaea;
    padding: 0.5rem;
    white-space: pre-wrap;
    font-family: monospace;
}

.apitester [data-ref=url] {
    display: inline-block;
    padding: 0;
    white-space: pre-wrap;
}

.apitester [data-ref=body] {
    display: block;
    resize: vertical;
    width: 100%;
    min-height: 3rem;
    border: 1px solid #eaeaea;
    padding: 0.5rem;
    white-space: pre-wrap;
}

.apitester [data-ref=execute] {
    padding: 0.5rem 1rem;
}

.apitester [data-ref=output] {
    background: #eaeaea;
    padding: 0.5rem 1rem;
    white-space: pre-wrap;
}

.apitester-error {
    border-color: red;
}
0.125rem 0.25rem;
font-size: 1rem;
} </style>
HTML
<script>
"use strict";

const DEFAULTBASE_HOSTURL = "httpshttp://suggestions.dadata.ru:443localhost:8080/";

function stringify(obj) {
    let objStr = JSON.stringify(obj, null, 4);
    if (objStr == "{}") {
        objStr = obj.toString();
    }
    return objStr;
}

function show(el) {
    el.style.display = "";
}

function hide(el) {
    el.style.display = "none";
}

class ApiTester {
    constructor(selector, httpMethod, apiMethod, body) {
        this.state = {
            host: localStorage.getItem("apitester.hostname") || DEFAULT_HOST,
            httpMethod: httpMethod,
            apiMethod: apiMethod,
            body: body,
            isExecuting: false,
            output: null,
        };
        this.el = this.initEl(selector);
        this.ui = this.initUi(this.el);
        this.listen();
        this.render();
    }

    get isMixedContent() {
        return (
            location.protocol == "https:" && this.state.host.startsWith("http:")
        );
    }

    initEl(selector) {
        const elloadBaseUrl() {
    const txtUrl = document.querySelector(selector);
        el.innerHTML = `
        <div class="apitester-editor">
            <h3>
                API-тестер
                <a data-ref="enable-http" class="apitester-link" href="#" title="Если вы открыли Confluence через HTTPS, запросы к HTTP-серверам подсказок работать не будут. Переключайтесь на HTTP, чтобы заработали">включить HTTP</a>
                <a data-ref="enable-https" class="apitester-link" href="#">включить HTTPS</a>
            </h3>
            <div>
                <pre data-ref="method"></pre>
                <input data-ref="host">
                <pre data-ref="url"></pre>
            </div>
            <div>
                <textarea data-ref="body"></textarea>
            </div>
            <div>
                <button data-ref="execute">Выполнить</button>
                <a data-ref="clear" class="apitester-link" href="#">очистить</a>
            </div>
        </div>
        <pre data-ref="output">
        </pre>
        `;
        return el;
    }

    initUi(el"#api-url");
    if (!txtUrl) {
        return {;
            enableHttp: el.querySelector("[data-ref=enable-http]"),}
            enableHttps: el.querySelector("[data-ref=enable-https]"),
            method: el.querySelector("[data-ref=method]"),
            host: el.querySelector("[data-ref=host]"),
            url: el.querySelector("[data-ref=url]"),
            body: el.querySelector("[data-ref=body]"),
            execute: el.querySelector("[data-ref=execute]"),
            clear: el.querySelector("[data-ref=clear]"),
            output: this.el.querySelector("[data-ref=output]"),
        };
    }

    listen() {
        this.el.addEventListener("keydown", (event) => {
            this.onKeydown(event);
        });
        this.ui.enableHttp.addEventListener("click", (event) => {
            this.onSwitchProtocol("http:", event);
        });
        this.ui.enableHttps.addEventListener("click", (event) => {
            this.onSwitchProtocol("https:", event);
        });
        this.ui.host.addEventListener("txtUrl.value = localStorage.getItem("suggestions-api-url") || "";
    txtUrl.addEventListener("change", (event) => {
            this.onEdit(event);
        });
        this.ui.body.addEventListener("change", (event) => {
            this.onEdit(event);
        });
        this.ui.execute.addEventListener("click", (event) => {
            this.onExecute(event);
        });
        this.ui.clear.addEventListener("click", (event) => {
            this.onClear(event);
        });
    }

    onKeydown(eventlocalStorage.setItem("suggestions-api-url", event.target.value);
    });
}

function openApiTester(path) {
        if (event.keyCode == 13 && (event.ctrlKey || event.metaKey)) {
            // Ctrl + Enter
            event.preventDefault();
            this.onEdit();
            this.onExecute();
        }
    }

    onSwitchProtocol(protocol, event) {
        event.preventDefault();
        window.location.protocol = protocol;
    }

    onEdit() {
        this.state.host = this.ui.host.value;
        this.state.body = this.ui.body.value;
        localStorage.setItem("apitester.hostname", this.state.hostconst txtUrl = document.querySelector("#api-url");
        this.render();
    }

    onExecute() {
        this.markAsExecuting();
        this.execute()
            .then((response) => {
      if (!txtUrl) {
          return response.json();
            })
            .then((response) => {
                this.showResponse(response);
            })
            .catch((err) => {
                this.showResponse(err);
            });
    }

    onClear(event) {
        event.preventDefault();
        this.state.output = null;
        this.render();
    }

    markAsExecuting() {
        this.state.output = null;
        this.state.isExecuting = true;
        this.render();
    }

    showResponse(response) {
        this.state.output = stringify(response);
        this.state.isExecuting = false;
        this.render();
    }

    execute() {
        const baseUrl = txtUrl.value || BASE_URL;
    const url = this.state.host + this.state.apiMethod;
        const options = {
            method: this.state.httpMethod,
            mode: "cors",
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token 7fd18aaabd7d53ffa4846e4521c1f736c13490eb",
            },
        }baseUrl + "suggestions/service/" + path + "#api";
        if (this.state.httpMethod == "POST") {
            options.body = this.state.body;
        }
        return fetchwindow.open(url, options);
    }

    render() {
        if (this.isMixedContent) {
            show(this.ui.enableHttp);
        } else {
            hide(this.ui.enableHttp);
        }
        if (location.protocol == "http:"_blank").focus();
}

if (document.readyState === "complete") {
            show(this.ui.enableHttpsloadBaseUrl();
        } else {
            hide(this.ui.enableHttps);
        }
        this.ui.method.innerHTML = this.state.httpMethod;
        this.ui.host.value = this.state.host;
        this.ui.url.innerHTML = this.state.apiMethod;
        this.ui.body.value = this.state.body;
        if (this.state.isExecuting) {
            this.ui.execute.setAttribute("disabled", "disabled");
        } else {
            this.ui.execute.removeAttribute("disabled");
        }
        this.ui.output.innerHTML = this.state.output;
        if (this.state.output) {
            show(this.ui.output);
            show(this.ui.clear);
        } else {
            hide(this.ui.output);
            hide(this.ui.clear);
        }
    }window.addEventListener("DOMContentLoaded", loadBaseUrl);
}
</script>