From f8d59fd9c9da5565cf05e93e9c91615882be8c1b Mon Sep 17 00:00:00 2001 From: Arthur Lu Date: Tue, 11 Jul 2023 21:14:54 +0000 Subject: [PATCH] implement better HTTP request types handling, add live updating of instances using statushash endpoint to reduce data transfer --- scripts/index.js | 14 ++++++++++++++ scripts/utils.js | 11 ++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/scripts/index.js b/scripts/index.js index 56b095e..6b7b31b 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -4,6 +4,9 @@ import { PVE } from "../vars.js"; window.addEventListener("DOMContentLoaded", init); +let currentHash; +const refreshRate = 5000; + async function init () { setTitleAndHeader(); const cookie = document.cookie; @@ -11,13 +14,24 @@ async function init () { goToPage("login.html"); } + currentHash = (await requestAPI("/cluster/statushash")).data; await populateInstances(); const addInstanceBtn = document.querySelector("#instance-add"); addInstanceBtn.addEventListener("click", handleInstanceAdd); + + window.setInterval(async () => { + const newHash = (await requestAPI("/cluster/statushash")).data; + if (currentHash !== newHash) { + currentHash = newHash; + populateInstances(); + } + }, refreshRate); } async function populateInstances () { + const newHash = (await requestAPI("/cluster/statushash")).data; + currentHash = newHash; const resources = await requestPVE("/cluster/resources", "GET"); const instanceContainer = document.getElementById("instance-container"); const instances = []; diff --git a/scripts/utils.js b/scripts/utils.js index f0d0478..39dca91 100644 --- a/scripts/utils.js +++ b/scripts/utils.js @@ -192,13 +192,18 @@ export async function requestAPI (path, method, body = null) { async function request (url, content) { const response = await fetch(url, content); + const contentType = response.headers.get("Content-Type"); let data = null; - try { + if (contentType.includes("application/json")) { data = await response.json(); data.status = response.status; } - catch { - data = null; + else if (contentType.includes("text/html")) { + data = { data: await response.text() }; + data.status = response.status; + } + else { + data = response; } if (!response.ok) {