189 lines
5.4 KiB
JavaScript
189 lines
5.4 KiB
JavaScript
/**
|
|
* API client for the bankline admin API.
|
|
*
|
|
* - Sends the raw JWT access token in the Authorization header
|
|
* (the backend middleware expects the bare token, no "Bearer " prefix).
|
|
* - 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 = "/admin/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.";
|
|
}
|
|
}
|
|
|
|
const tokens = {
|
|
get access() {
|
|
return localStorage.getItem(ACCESS_KEY) || "";
|
|
},
|
|
get refresh() {
|
|
return localStorage.getItem(REFRESH_KEY) || "";
|
|
},
|
|
set(pair) {
|
|
localStorage.setItem(ACCESS_KEY, pair.accessToken || "");
|
|
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) {
|
|
// A few endpoints (e.g. JWT middleware errors) don't use the envelope.
|
|
return payload;
|
|
}
|
|
|
|
const serverMessage =
|
|
(payload && (payload.message || payload.error)) || "";
|
|
throw new ApiError(
|
|
friendlyMessage(response.status, serverMessage),
|
|
response.status,
|
|
payload && payload.code
|
|
);
|
|
}
|
|
|
|
async function refreshTokens() {
|
|
const refreshToken = tokens.refresh;
|
|
if (!refreshToken) return false;
|
|
try {
|
|
const response = await fetch("/api/v1/admin/token", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ refreshToken }),
|
|
});
|
|
if (!response.ok) return false;
|
|
const payload = await response.json();
|
|
const pair = payload && payload.data;
|
|
if (pair && pair.accessToken) {
|
|
tokens.set(pair);
|
|
return true;
|
|
}
|
|
return false;
|
|
} 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 });
|
|
} 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,
|
|
};
|
|
})();
|