1
0
Fork 0
mirror of https://github.com/SinTan1729/chhoto-url synced 2024-10-16 21:33:54 -05:00
chhoto-url/src/main/resources/public/js/main.js

105 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-02-14 12:52:14 -06:00
const refreshData = async () => {
2020-02-16 08:46:29 -06:00
let data = await fetch("/api/all").then(res => res.text());
2020-02-14 12:52:14 -06:00
data = data
.split("\n")
.filter(line => line !== "")
.map(line => line.split(","))
.map(arr => ({
2022-11-03 16:53:04 -05:00
short: arr[0],
2020-02-14 12:52:14 -06:00
long: arr[1],
2022-11-03 16:53:04 -05:00
hits: arr[2]
2020-02-14 12:52:14 -06:00
}));
displayData(data);
};
const displayData = (data) => {
const table = document.querySelector("#url-table");
table.innerHTML = ''; // Clear
data.map(TR)
.forEach(tr => table.appendChild(tr));
};
const TR = (row) => {
const tr = document.createElement("tr");
const longTD = TD(A(row.long));
const shortTD = TD(A_INT(row.short));
2022-11-03 16:53:04 -05:00
const hitsTD = TD(row.hits);
2020-02-16 09:52:54 -06:00
const btn = deleteButton(row.short);
2020-02-14 12:52:14 -06:00
tr.appendChild(shortTD);
tr.appendChild(longTD);
2022-11-03 16:53:04 -05:00
tr.appendChild(hitsTD);
2020-02-16 09:52:54 -06:00
tr.appendChild(btn);
2020-02-14 12:52:14 -06:00
return tr;
};
const A = (s) => `<a href='${s}'>${s}</a>`;
const A_INT = (s) => `<a href='/${s}'>${window.location.host}/${s}</a>`;
2020-02-16 09:52:54 -06:00
const deleteButton = (shortUrl) => {
const btn = document.createElement("button");
btn.innerHTML = "&times;";
btn.onclick = e => {
e.preventDefault();
fetch(`/api/${shortUrl}`, {
method: "DELETE"
}).then(_ => refreshData());
};
return btn;
};
2020-02-14 12:52:14 -06:00
const TD = (s) => {
const td = document.createElement("td");
2022-11-03 15:19:22 -05:00
const div = document.createElement("div");
div.innerHTML = s;
td.appendChild(div);
2020-02-14 12:52:14 -06:00
return td;
};
const submitForm = () => {
const form = document.forms.namedItem("new-url-form");
const longUrl = form.elements["longUrl"];
const shortUrl = form.elements["shortUrl"];
const url = `/api/new`;
2020-02-14 12:52:14 -06:00
fetch(url, {
method: "POST",
body: `${longUrl.value};${shortUrl.value}`
2020-02-14 12:52:14 -06:00
})
2022-11-08 18:23:41 -06:00
.then((res) => {
if (!res.ok) {
2022-11-08 18:39:23 -06:00
if (document.getElementById("errBox") == null) {
controls = document.querySelector(".pure-controls");
errBox = document.createElement("p");
errBox.setAttribute("id", "errBox");
errBox.setAttribute("style", "color:red");
errBox.innerHTML = "Short URL not valid or already in use!";
controls.appendChild(errBox);
}
2022-11-08 18:23:41 -06:00
}
else {
document.getElementById("errBox")?.remove();
longUrl.value = "";
shortUrl.value = "";
refreshData();
}
});
2020-02-14 12:52:14 -06:00
};
(async () => {
await refreshData();
const form = document.forms.namedItem("new-url-form");
form.onsubmit = e => {
e.preventDefault();
submitForm();
}
})();