stage 1
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user