PPPAIMT-Crest/frontend/src/admin/adminApi.js

35 lines
986 B
JavaScript

/**
* Admin requests use the session cookie and never the physician bearer token.
* @param {string} path
* @param {{ method?: string, body?: Record<string, unknown>, redirectOn401?: boolean }} [options]
*/
export async function adminApi(path, options = {}) {
const headers = { Accept: 'application/json' };
if (options.body) {
headers['Content-Type'] = 'application/json';
}
const response = await fetch(path, {
method: options.method ?? 'GET',
headers,
credentials: 'include',
body: options.body ? JSON.stringify(options.body) : undefined,
});
const data = await response.json().catch(() => ({}));
if (response.status === 401 && options.redirectOn401 !== false) {
if (window.location.pathname !== '/admin/login') {
window.location.assign('/admin/login');
}
}
if (!response.ok) {
const error = new Error(data?.error?.message || 'Request failed');
error.status = response.status;
throw error;
}
return data;
}