document.getElementById("soudan").innerHTML = `
Make a comment
`;
document.write(``);
const url = "http://127.0.0.1:8080";
const form = document.getElementById("soudan-comment-form");
const commentContainer = document.getElementById("soudan-comments");
const commentContainerHeader = document.getElementById("soudan-comments-header");
const contentId = document.querySelector("meta[name=\"soudan-content-id\"]").getAttribute("content");
form.addEventListener("submit", e => {
let data = {
url: window.location.href,
comment: { contentId }
};
new FormData(form).forEach((value, key) => {
data.comment[key] = value === "" ? null : value;
});
fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" }
})
.then(response => {
if (!response.ok) {
return;
}
form.querySelector("textarea").value = "";
reloadComments();
})
e.preventDefault();
});
function reloadComments() {
fetch(`${url}/${contentId}`)
.then(response => {
return response.json().then(json => {
return response.ok ? json : Promise.reject(json);
});
})
.then(comments => {
commentContainerHeader.innerHTML = `${comments.length} Comment${comments.length == 1 ? "" : "s"}`;
let html = "";
if (comments.length == 0) {
html = "No comments yet! Be the first to make one.
";
} else {
comments.forEach(comment => {
html += `${comment.author ? comment.author : "Anonymous"} commented ${moment(new Date(comment.timestamp * 1000)).fromNow()}:
${comment.text}
`;
});
}
commentContainer.innerHTML = html;
});
}
reloadComments();