2025-08-08 20:36:21 -04:00

49 lines
1.7 KiB
JavaScript

// js/api.js
import { showLoading, showMessage } from './utils.js';
const API_BASE_URL = '/api';
// This function will be the single point of contact with the server.
export async function apiCall(endpoint, method = 'GET', body = null) {
const authToken = localStorage.getItem('authToken');
const headers = { 'Content-Type': 'application/json' };
if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
try {
showLoading(true);
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
method,
headers,
body: body ? JSON.stringify(body) : null
});
// The original logic for handling responses remains the same.
if (response.status === 401) {
// We'll need to pass the signOut function in or handle it differently
// For now, let's just redirect.
localStorage.clear();
window.location.reload();
// A more robust solution would use a custom event.
return { success: false, message: 'Session expired.' };
}
const text = await response.text();
let data;
try {
data = text ? JSON.parse(text) : null;
} catch (error) {
if (!response.ok) { throw new Error(text || `Request failed with status ${response.status}`); }
return { success: true, data: text };
}
if (!response.ok) { throw new Error(data.message || `An unknown error occurred.`); }
return { success: true, data };
} catch (error) {
showMessage(error.message, 'error');
return { success: false };
} finally {
showLoading(false);
}
}