Files
bourbonacci/frontend/js/api.js
T
derekc 866c2e0bed Fix stale DB connections, add Why Bourbonacci section, harden auth
- Add pool_pre_ping and pool_recycle to prevent lost connection errors on idle pool
- Add Why Bourbonacci card to about page
- Redirect to login on 401 in API layer
- Check JWT expiry in isLoggedIn instead of just token presence

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 21:37:04 -07:00

81 lines
2.8 KiB
JavaScript

/* Central API client — all fetch calls go through here */
function escHtml(str) {
return String(str ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
const API = (() => {
const base = '/api';
function token() {
return localStorage.getItem('bb_token');
}
async function request(method, path, body) {
const headers = { 'Content-Type': 'application/json' };
const tok = token();
if (tok) headers['Authorization'] = `Bearer ${tok}`;
const res = await fetch(base + path, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (res.status === 204) return null;
const data = await res.json().catch(() => null);
if (res.status === 401) {
localStorage.removeItem('bb_token');
localStorage.removeItem('bb_user');
window.location.href = '/login.html';
return;
}
if (!res.ok) {
const msg = data?.detail || `HTTP ${res.status}`;
throw new Error(Array.isArray(msg) ? msg.map(e => e.msg).join(', ') : msg);
}
return data;
}
return {
get: (path) => request('GET', path),
post: (path, body) => request('POST', path, body),
put: (path, body) => request('PUT', path, body),
delete: (path) => request('DELETE', path),
auth: {
login: (email, password) => request('POST', '/auth/login', { email, password }),
register: (email, password, display_name) =>
request('POST', '/auth/register', { email, password, display_name }),
},
users: {
me: () => request('GET', '/users/me'),
update: (body) => request('PUT', '/users/me', body),
changePassword: (body) => request('PUT', '/users/me/password', body),
},
entries: {
list: () => request('GET', '/entries'),
stats: () => request('GET', '/entries/stats'),
create: (body) => request('POST', '/entries', body),
delete: (id) => request('DELETE', `/entries/${id}`),
},
public: {
stats: () => request('GET', '/public/stats'),
},
admin: {
listUsers: () => request('GET', '/admin/users'),
createUser: (body) => request('POST', '/admin/users', body),
resetPassword: (id, body) => request('POST', `/admin/users/${id}/reset-password`, body),
disable: (id) => request('POST', `/admin/users/${id}/disable`, {}),
enable: (id) => request('POST', `/admin/users/${id}/enable`, {}),
delete: (id) => request('DELETE', `/admin/users/${id}`),
impersonate: (id) => request('POST', `/admin/users/${id}/impersonate`, {}),
unimpersonate: () => request('POST', '/admin/unimpersonate', {}),
},
};
})();