janpaul123-valle_tmp_65773463412544294175217031213487.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
import { Hono } from "npm:hono";
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
// Initialize SQLite database and comments table if it doesn't exist
const initDB = async () => {
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
};
await initDB();
const app = new Hono();
// Serves the comment page
app.get("/", async (c) => {
const result = await sqlite.execute("SELECT * FROM comments ORDER BY timestamp DESC");
const comments = result.rows;
return html(`
<html>
<head>
<title>Comment Box</title>
<style>
body { font-family: sans-serif; }
.comment-box { margin-top: 20px; }
.comment { border-bottom: 1px solid #ccc; padding: 10px; }
.timestamp { color: #999; font-size: 0.8em; }
</style>
</head>
<body>
<h1>Comment Box</h1>
<form method="POST" action="/comment">
<textarea name="text" placeholder="Your comment" required></textarea><br>
<button type="submit">Submit</button>
</form>
<div class="comment-box">
${comments.map(comment => `
<div class="comment">
<p>${comment.text}</p>
<span class="timestamp">${new Date(comment.timestamp).toLocaleString()}</span>
</div>
`).join('')}
</div>
</body>
</html>
`);
});
// Handles the comment submission
app.post("/comment", async c => {
const formData = await c.req.parseBody();
const text = formData?.text;
if (typeof text !== 'string') {
return c.text('Invalid comment text', 400);
}
// Insert the comment into the database
await sqlite.execute("INSERT INTO comments (text) VALUES (?)", [text]);
// Redirect back to the main page
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