janpaul123-valle_tmp_125920830351466952258206466703858.web.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// This val will create a simple comment box using a form. Comments are persisted using SQLite
// and it will display all previous comments. The HTTP route uses a server-side approach to
// handle both displaying comments and submitting new ones.
import { blob } from "https://esm.town/v/std/blob?v=11";
import { sqlite } from "https://esm.town/v/std/sqlite?v=11";
import { Hono } from "npm:hono";
// Initialize SQLite table
await sqlite.execute(`CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`);
const app = new Hono();
// Display the comment box and all previous comments
app.get("/", async (c) => {
const comments = await sqlite.query("SELECT text, created_at FROM comments ORDER BY created_at DESC");
const commentsHtml = comments.map(({ text, created_at }) =>
`<div><strong>${new Date(created_at).toLocaleString()}:</strong> ${text}</div>`).join("");
return c.html(`
<!DOCTYPE html>
<html>
<head>
<title>Comments</title>
</head>
<body>
<form action="/submit" method="POST">
<textarea name="comment" required></textarea><br>
<button type="submit">Submit</button>
</form>
<hr>
${commentsHtml}
</body>
</html>
`);
});
// Handle form submission and persist the comment
app.post("/submit", async (c) => {
const formData = await c.req.parseBody();
const comment = formData.comment;
if (comment) {
await sqlite.execute("INSERT INTO comments (text) VALUES (?)", [comment]);
}
return c.redirect("/");
});
export default app.fetch;
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 17, 2024