Files
main-tbbank/backend/web/admin/assets/js/api.js
2026-08-18 00:59:32 +05:00

202 lines
5.7 KiB
JavaScript

/**
* API client for the bankline admin API.
*
* Auth is cookie-based (HttpOnly admin_access / admin_refresh).
* Requests use credentials: "include". Authorization header is optional
* when a legacy localStorage token is still present.
*
* - Unwraps the response envelope { status, message, code, data }.
* - On 401 tries a one-shot refresh via POST /api/v1/admin/token, then retries.
* - Throws ApiError with a friendly, human-readable message.
*/
(function () {
"use strict";
const ACCESS_KEY = "bankline_admin_access";
const REFRESH_KEY = "bankline_admin_refresh";
const LOGIN_PAGE = "/M0n1t0r/login";
class ApiError extends Error {
constructor(message, status, code) {
super(message);
this.name = "ApiError";
this.status = status || 0;
this.code = code || "";
}
}
function friendlyMessage(status, fallback) {
switch (status) {
case 400:
return fallback || "The request is invalid. Please check the form and try again.";
case 401:
return "Your session has expired. Please sign in again.";
case 403:
return "You don't have permission to perform this action.";
case 404:
return "The requested item was not found.";
case 422:
return fallback || "The submitted data is invalid.";
case 500:
return "Something went wrong on the server. Please try again.";
default:
return fallback || "An unexpected error occurred. Please try again.";
}
}
// Legacy localStorage tokens (optional). Session source of truth is HttpOnly cookies.
const tokens = {
get access() {
return localStorage.getItem(ACCESS_KEY) || "";
},
get refresh() {
return localStorage.getItem(REFRESH_KEY) || "";
},
set(pair) {
if (pair && pair.accessToken) {
localStorage.setItem(ACCESS_KEY, pair.accessToken);
}
if (pair && pair.refreshToken) {
localStorage.setItem(REFRESH_KEY, pair.refreshToken);
}
},
clear() {
localStorage.removeItem(ACCESS_KEY);
localStorage.removeItem(REFRESH_KEY);
},
};
function redirectToLogin() {
tokens.clear();
if (!window.location.pathname.startsWith(LOGIN_PAGE)) {
window.location.href = LOGIN_PAGE;
}
}
async function parseEnvelope(response) {
let payload = null;
try {
payload = await response.json();
} catch (_) {
/* non-JSON body */
}
if (response.ok && payload && payload.status === true) {
return payload.data;
}
if (response.ok && payload && payload.status === undefined) {
return payload;
}
const serverMessage =
(payload && (payload.message || payload.error)) || "";
throw new ApiError(
friendlyMessage(response.status, serverMessage),
response.status,
payload && payload.code
);
}
async function refreshTokens() {
try {
const body = {};
if (tokens.refresh) body.refreshToken = tokens.refresh;
const response = await fetch("/api/v1/admin/token", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) return false;
const payload = await response.json();
const pair = payload && payload.data;
if (pair && pair.accessToken) {
tokens.set(pair);
return true;
}
// Cookie-only refresh may return a pair; accept any 200 with status true.
return !!(payload && payload.status === true);
} catch (_) {
return false;
}
}
/**
* Perform an authenticated JSON request.
* @param {string} method HTTP method
* @param {string} path request path, e.g. /api/v1/admin/news
* @param {{ body?: object, query?: object, formData?: FormData, retried?: boolean }} [options]
*/
async function request(method, path, options) {
options = options || {};
let url = path;
if (options.query) {
const params = new URLSearchParams();
Object.entries(options.query).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== "") {
params.set(key, value);
}
});
const qs = params.toString();
if (qs) url += "?" + qs;
}
const headers = {};
if (tokens.access) headers["Authorization"] = tokens.access;
let body;
if (options.formData) {
body = options.formData;
} else if (options.body !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(options.body);
}
let response;
try {
response = await fetch(url, {
method,
headers,
body,
credentials: "include",
});
} catch (_) {
throw new ApiError(
"Network error. Please check your connection and try again.",
0
);
}
if ((response.status === 401 || response.status === 403) && !options.retried) {
const refreshed = await refreshTokens();
if (refreshed) {
return request(method, path, Object.assign({}, options, { retried: true }));
}
redirectToLogin();
throw new ApiError(friendlyMessage(401), response.status);
}
return parseEnvelope(response);
}
/** Upload a file; resolves to its public path (e.g. /images/123.png). */
function upload(file) {
const formData = new FormData();
formData.append("file", file);
return request("POST", "/api/v1/admin/file", { formData });
}
window.Api = {
ApiError,
tokens,
redirectToLogin,
get: (path, query) => request("GET", path, { query }),
post: (path, body) => request("POST", path, { body }),
put: (path, body) => request("PUT", path, { body }),
del: (path) => request("DELETE", path, {}),
request,
upload,
};
})();