janpaul123-valle_tmp_39122300029538671437128838517412.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
// We'll create a simple comment system using an input field and a button to submit comments.
// Comments will be persisted using SQLite and displayed below the input box.
import { Hono } from "npm:hono@3.0.0";
import { sqlite } from "https://esm.town/v/std/sqlite";
import { html } from "https://esm.town/v/stevekrouse/html";
// Initialize SQLite and create the comments table if it doesn't exist.
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL
)
`);
// Define the main function to handle HTTP requests.
export default async function main(req: Request): Promise<Response> {
if (req.method === "POST") {
const formData = await req.formData();
const content = formData.get("content");
if (typeof content === "string" && content.trim() !== "") {
await sqlite.execute("INSERT INTO comments (content) VALUES (?)", [content]);
}
return Response.redirect(new URL(req.url).origin);
}
// Retrieve all comments from the database.
const { values: comments } = await sqlite.execute("SELECT content FROM comments");
// Generate HTML for the comments.
const commentsHTML = comments.map(({ content }) => `<p>${content}</p>`).join("");
// Return the HTML response with the form and comments.
const responseHTML = `
<html>
<head>
<title>Comment Box</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
form { margin-bottom: 20px; }
</style>
</head>
<body>
<h1>Comment Box</h1>
<form method="POST">
<textarea name="content" rows="4" cols="50" placeholder="Type your comment here..." required></textarea>
<br>
<button type="submit">Submit</button>
</form>
<h2>Comments:</h2>
${commentsHTML}
</body>
</html>
`;
return html(responseHTML);
}
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