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