nopaque/app/static/js/requests/index.js
2024-12-02 09:34:17 +01:00

43 lines
1.2 KiB
JavaScript

nopaque.requests = {};
nopaque.requests.JSONfetch = (input, init={}) => {
return new Promise((resolve, reject) => {
let fixedInit = {};
fixedInit.headers = {};
fixedInit.headers['Accept'] = 'application/json';
if (init.hasOwnProperty('body')) {
fixedInit.headers['Content-Type'] = 'application/json';
}
fetch(input, nopaque.Utils.mergeObjectsDeep(init, fixedInit))
.then(
(response) => {
if (response.ok) {
resolve(response.clone());
} else {
reject(response);
}
if (response.status === 204) {
return;
}
response.json()
.then(
(json) => {
let message = json.message;
let category = json.category || 'message';
if (message) {
app.ui.flash(message, category);
}
},
(error) => {
app.ui.flash(`[${response.status}]: ${response.statusText}`, 'error');
}
);
},
(response) => {
app.ui.flash('Something went wrong', 'error');
reject(response);
}
);
});
};