94 lines
2.3 KiB
JavaScript
94 lines
2.3 KiB
JavaScript
// API and connection helpers shared by WebUI classic scripts.
|
|
// API 连接状态:连续失败 N 次才算 error,避免轻微抖动闪烁
|
|
let _apiFailStreak = 0;
|
|
const _apiFailThreshold = 2;
|
|
|
|
function setConnState(state) {
|
|
const dot = document.getElementById("appConnDot");
|
|
const txt = document.getElementById("appConnText");
|
|
if (!dot || !txt) return;
|
|
if (state === "ok") {
|
|
dot.dataset.state = "ok";
|
|
txt.textContent = "已连接";
|
|
dot.title = "API 通信正常";
|
|
} else if (state === "error") {
|
|
dot.dataset.state = "error";
|
|
txt.textContent = "连接异常";
|
|
dot.title = "API 请求连续失败,检查后端是否运行";
|
|
} else {
|
|
dot.dataset.state = "idle";
|
|
txt.textContent = "就绪";
|
|
dot.title = "等待首个 API 请求";
|
|
}
|
|
}
|
|
|
|
function notifyApiOk() {
|
|
_apiFailStreak = 0;
|
|
setConnState("ok");
|
|
}
|
|
|
|
function notifyApiFail() {
|
|
_apiFailStreak++;
|
|
if (_apiFailStreak >= _apiFailThreshold) setConnState("error");
|
|
}
|
|
|
|
async function apiGet(path) {
|
|
try {
|
|
const res = await fetch(path, { cache: "no-store" });
|
|
if (!res.ok) {
|
|
notifyApiFail();
|
|
throw new Error(await res.text());
|
|
}
|
|
notifyApiOk();
|
|
return await res.json();
|
|
} catch (e) {
|
|
notifyApiFail();
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
// CSRF token 缓存
|
|
let _csrfToken = null;
|
|
|
|
async function getCsrfToken() {
|
|
if (_csrfToken) return _csrfToken;
|
|
try {
|
|
const res = await fetch("/api/csrf-token", { cache: "no-store" });
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
_csrfToken = data.token || "";
|
|
}
|
|
} catch (e) {
|
|
console.warn("[CSRF] 获取 token 失败:", e);
|
|
}
|
|
return _csrfToken || "";
|
|
}
|
|
|
|
async function apiPost(path, body) {
|
|
try {
|
|
const token = await getCsrfToken();
|
|
const res = await fetch(path, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-CSRF-Token": token,
|
|
},
|
|
body: JSON.stringify(body || {}),
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) {
|
|
notifyApiFail();
|
|
const errorMsg = data.error || data.message || res.statusText;
|
|
const error = new Error(errorMsg);
|
|
error.status = res.status;
|
|
error.data = data;
|
|
throw error;
|
|
}
|
|
notifyApiOk();
|
|
return data;
|
|
} catch (e) {
|
|
notifyApiFail();
|
|
throw e;
|
|
}
|
|
}
|