Overhaul networkUtils and expand auth

This commit is contained in:
Ryan
2025-04-17 01:20:18 -04:00
committed by GitHub
parent 75d3bf5a9b
commit 22cce5a898
7 changed files with 263 additions and 209 deletions

View File

@@ -1,31 +1,31 @@
// public/js/networkUtils.js
export function sendRequest(url, method = "GET", data = null, customHeaders = {}) {
const options = {
method,
credentials: 'include',
headers: {}
headers: { ...customHeaders }
};
// Merge custom headers
Object.assign(options.headers, customHeaders);
// If data is provided and is not FormData, assume JSON.
if (data && !(data instanceof FormData)) {
if (!options.headers["Content-Type"]) {
options.headers["Content-Type"] = "application/json";
}
options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/json';
options.body = JSON.stringify(data);
} else if (data instanceof FormData) {
options.body = data;
}
return fetch(url, options)
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error(`HTTP error ${response.status}: ${text}`);
});
.then(async res => {
const text = await res.text();
let payload;
try {
payload = JSON.parse(text);
} catch {
payload = text;
}
const clonedResponse = response.clone();
return response.json().catch(() => clonedResponse.text());
if (!res.ok) {
// Reject with the parsed JSON (or raw text) so .catch(error) gets it
throw payload;
}
return payload;
});
}