janpaul123-valle_tmp_393084135551327933207099179023125.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// This approach uses the Hono framework to set up routes for handling comments.
// We will store comments in an SQLite database using the `std/sqlite` module for persistence.
// The main route serves the HTML form and displays the comments.
// The POST route handles new comment submissions.
import { Hono } from "npm:hono";
import { html } from "https://esm.town/v/stevekrouse/html";
import { sqlite } from "https://esm.town/v/std/sqlite";
// Create a table for storing comments if it does not exist
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
)
`);
// Define the Hono app
const app = new Hono();
// Helper function to fetch all comments from the database
async function fetchComments() {
const result = await sqlite.execute(`SELECT * FROM comments ORDER BY timestamp DESC`);
return result.rows;
}
// Main route: serves the HTML form and displays comments
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);
});
// POST route: handles new comment submissions
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 the fetch handler to be used by the runtime
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