"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const passwordInput = document.getElementById("password");
const loginInput = document.getElementById("login");
const idInput = document.getElementById("id");
const removeBtn = document.getElementById("removeBtn");
const editBtn = document.getElementById("editBtn");
const testErrorBtn = document.getElementById("testError");
const testNormalBtn = document.getElementById("testNormal");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/customer");
const data = await response.json();
data.forEach(customer => {
table.innerHTML +=
`
${customer.id} |
${customer.login} |
${customer.password} |
`;
})
}
const create = async function (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/customer?login=${login}&password=${password}`, requestParams);
return await response.json();
}
async function remove(id) {
const requestParams = {
method: "DELETE",
};
const response = await fetch(host + `/customer/${id}`, requestParams);
return await response.json();
}
async function edit(id, login, password) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/customer/${id}?login=${login}&password=${password}`, requestParams);
return await response.json();
}
const test = async function (testObject) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(testObject),
};
const response = await fetch(host + "/test", requestParams);
if (response.status === 200) {
const data = await response.json();
alert(`TestDto=[id=${data.id}, name=${data.name}, data=${data.data}]`);
}
if (response.status === 400) {
const data = await response.text();
alert(data);
}
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create(loginInput.value, passwordInput.value).then((result) => {
getData();
loginInput.value = "";
passwordInput.value = "";
alert(`Customer[id=${result.id}, login=${result.login}, password=${result.password}]`);
});
});
testErrorBtn.addEventListener("click", function () {
test({});
});
testNormalBtn.addEventListener("click", function () {
test({id: 10, name: "test"});
});
removeBtn.addEventListener("click", function (event) {
event.preventDefault();
remove(idInput.value).then((result) => {
getData();
loginInput.value = "";
passwordInput.value = "";
idInput.value = "";
});
});
editBtn.addEventListener("click", function (event) {
event.preventDefault();
edit(idInput.value, loginInput.value, passwordInput.value).then((result) => {
getData();
loginInput.value = "";
passwordInput.value = "";
idInput.value = "";
});
});
getData();
});