Files
CLProject/public/js/api.js
T
2026-04-19 21:14:16 +02:00

51 lines
1.3 KiB
JavaScript

/*
* API communication module. Centralizes fetch calls and service-worker
* registration so network details stay out of rendering and state logic.
*/
import { API_BASE } from './constants.js';
/*
* Generic JSON fetcher. All frontend API calls pass through this function so
* error handling, header defaults, and base path are consistent everywhere.
*/
export async function fetchJson(path, options = {}) {
const url = path.startsWith('http') ? path : `${API_BASE}${path}`;
const requestOptions = {
...options,
headers: {
Accept: 'application/json',
...(options.headers || {})
}
};
const response = await fetch(url, requestOptions);
if (!response.ok) {
let message = `Request failed for ${url}: ${response.status}`;
try {
const errorPayload = await response.json();
if (errorPayload?.message) {
message = errorPayload.message;
}
} catch {
/* Ignore JSON parse errors for non-JSON responses. */
}
throw new Error(message);
}
return response.json();
}
export function registerServiceWorker() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch((error) => {
console.error('Service worker registration failed', error);
});
}
}