Refactor admin frontend into modular SPA
This commit is contained in:
57
frontend/admin/js/api.js
Normal file
57
frontend/admin/js/api.js
Normal file
@@ -0,0 +1,57 @@
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
export function getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
export function isAuthenticatedAsAdmin() {
|
||||
const role = localStorage.getItem('role');
|
||||
return token && role === 'ADMIN';
|
||||
}
|
||||
|
||||
function getHeaders(contentType = 'application/json') {
|
||||
const headers = {
|
||||
'Authorization': `Bearer ${token}`
|
||||
};
|
||||
if (contentType) {
|
||||
headers['Content-Type'] = contentType;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export async function apiFetch(endpoint, method = 'GET', body = null) {
|
||||
const options = {
|
||||
method,
|
||||
headers: getHeaders(body ? 'application/json' : null)
|
||||
};
|
||||
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(endpoint, options);
|
||||
|
||||
// Si status is 401 or 403, we should probably redirect to login,
|
||||
// but for now let's just throw an error or handle it in the view.
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch (e) {
|
||||
data = null;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.message || `Ошибка HTTP: ${response.status}`);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// Shortcut methods
|
||||
export const api = {
|
||||
get: (url) => apiFetch(url, 'GET'),
|
||||
post: (url, body) => apiFetch(url, 'POST', body),
|
||||
put: (url, body) => apiFetch(url, 'PUT', body),
|
||||
delete: (url, body = null) => apiFetch(url, 'DELETE', body)
|
||||
};
|
||||
Reference in New Issue
Block a user