nopaque/app/static/js/requests/index.js

43 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

nopaque.requests = {};
2023-03-08 10:42:53 +00:00
nopaque.requests.JSONfetch = (input, init={}) => {
2023-03-08 10:42:53 +00:00
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))
2023-03-08 10:42:53 +00:00
.then(
(response) => {
2023-03-09 13:55:08 +00:00
if (response.ok) {
resolve(response.clone());
} else {
reject(response);
}
if (response.status === 204) {
return;
}
2023-03-08 10:42:53 +00:00
response.json()
.then(
(json) => {
2023-07-03 09:06:43 +00:00
let message = json.message;
2023-03-08 10:42:53 +00:00
let category = json.category || 'message';
2023-07-03 09:06:43 +00:00
if (message) {
app.flash(message, category);
}
2023-03-08 10:42:53 +00:00
},
(error) => {
app.flash(`[${response.status}]: ${response.statusText}`, 'error');
}
);
},
(response) => {
app.flash('Something went wrong', 'error');
reject(response);
}
);
});
};