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

43 lines
1.2 KiB
JavaScript
Raw 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;
2024-12-02 08:34:17 +00:00
}
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) {
2024-12-02 08:34:17 +00:00
app.ui.flash(message, category);
2023-07-03 09:06:43 +00:00
}
2023-03-08 10:42:53 +00:00
},
(error) => {
2024-12-02 08:34:17 +00:00
app.ui.flash(`[${response.status}]: ${response.statusText}`, 'error');
2023-03-08 10:42:53 +00:00
}
);
},
(response) => {
2024-12-02 08:34:17 +00:00
app.ui.flash('Something went wrong', 'error');
2023-03-08 10:42:53 +00:00
reject(response);
}
);
});
};