import { Hono } from "npm:hono";
import { html } from "https://esm.town/v/stevekrouse/html";
import { sqlite } from "https://esm.town/v/std/sqlite";
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
comment TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
const app = new Hono();
async function fetchComments() {
const result = await sqlite.execute(`SELECT * FROM comments ORDER BY timestamp DESC`);
return result.rows;
}
app.get("/", async (c) => {
const comments = await fetchComments();
const commentsHTML = comments.map(
(row) => `<div><strong>${row[1]}</strong> (${row[3]}): <p>${row[2]}</p></div>`
).join("");
const body = `
<html>
<head>
<title>Comment Box</title>
<style>
* { font-family: sans-serif; }
form { margin-bottom: 20px; }
input, textarea { display: block; margin: 10px 0; width: 100%; }
</style>
</head>
<body>
<h1>Comment Box</h1>
<form action="/comment" method="POST">
<input type="text" name="name" placeholder="Your name" required />
<textarea name="comment" placeholder="Your comment" required></textarea>
<button type="submit">Submit</button>
</form>
<div>
<h2>Previous Comments</h2>
${commentsHTML}
</div>
</body>
</html>
`;
return c.html(body);
});
app.post("/comment", async (c) => {
const data = await c.req.parseBody();
const { name, comment } = data;
if (name && comment) {
await sqlite.execute(
"INSERT INTO comments (name, comment) VALUES (?, ?)",
[name, comment]
);
}
return c.redirect("/");
});
export default app.fetch;