Files
delphi-database/static/js/upload-helper.js
2025-08-13 18:53:35 -05:00

47 lines
1.5 KiB
JavaScript

(function() {
/**
* uploadWithAlerts
* Small helper to perform a fetch for uploads and, on failure, show a UI alert with
* a correlation reference from the server's error envelope. It uses window.http.toError
* and window.http.formatAlert to produce a user-facing message.
*
* Usage:
* const formData = new FormData();
* formData.append('file', input.files[0]);
* const respJson = await uploadWithAlerts(`/api/documents/upload/${fileNo}`, formData);
* // respJson is the parsed JSON on success, otherwise an Error is thrown after alerting
*
* The alert includes "Ref: <correlation-id>" when available.
*/
async function uploadWithAlerts(url, formData, { method = 'POST', extraOptions = {}, alertTitle = 'Upload failed' } = {}) {
const options = {
method,
body: formData,
...extraOptions,
};
const response = await window.http.wrappedFetch(url, options);
if (!response.ok) {
const err = await window.http.toError(response, alertTitle);
const msg = window.http.formatAlert(err, alertTitle);
if (window.alerts && typeof window.alerts.error === 'function') {
window.alerts.error(msg, { html: true, duration: 0 });
} else if (window.showNotification) {
window.showNotification(msg, 'error', 8000);
} else {
alert(String(msg));
}
throw err;
}
try {
return await response.json();
} catch (_) {
return null;
}
}
// Expose globally for pages to use
window.uploadWithAlerts = uploadWithAlerts;
})();