fetch items from server before locally checking available IDs

This commit is contained in:
jomo 2022-08-11 02:52:00 +02:00
parent ade2219469
commit 6b7c741658

View file

@ -3,13 +3,17 @@ const id = new URLSearchParams(window.location.search).get('id');
document.onreadystatechange = function() {
if (document.readyState === 'interactive') {
fetch('/api/items').then(r => r.json()).then((data) => {
items = data;
fillForm();
});
fetchItems(fillForm);
}
}
function fetchItems(cb) {
fetch('/api/items').then(r => r.json()).then((data) => {
items = data;
cb();
});
}
function fillForm() {
const item = items[id];
knownTypes();
@ -77,39 +81,41 @@ function save() {
hidden: document.getElementById('hidden').checked,
}
if (item.id.includes('?')) {
let n = 1;
while (true) {
const candidate = item.id.replace('?', n++);
if (!Object.keys(items).includes(candidate)) {
item.id = candidate;
break;
fetchItems(() => {
if (item.id.includes('?')) {
let n = 1;
while (true) {
const candidate = item.id.replace('?', n++);
if (!Object.keys(items).includes(candidate)) {
item.id = candidate;
break;
}
}
}
}
if (items[item.id]) {
if (!id || (id && id != item.id)) {
alert(`ID ${item.id} exists. Please chose a different ID or edit the existing ${item.id} item!`);
return;
if (items[item.id]) {
if (!id || (id && id != item.id)) {
alert(`ID ${item.id} exists. Please chose a different ID or edit the existing ${item.id} item!`);
return;
}
}
}
const original_id = id || item.id;
const original_id = id || item.id;
fetch(`/api/items/${original_id}`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(item),
})
.then(r => {
if (r.ok) {
window.location.href = '../';
} else {
r.text().then(t => alert(`Error:\n${t}`));
}
}).catch(error => {
alert(`Error:\n${error}`);
fetch(`/api/items/${original_id}`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(item),
})
.then(r => {
if (r.ok) {
window.location.href = '../';
} else {
r.text().then(t => alert(`Error:\n${t}`));
}
}).catch(error => {
alert(`Error:\n${error}`);
});
});
}