janpaul123-valle_tmp_43654664469855205133021678427796.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
// This val creates a simple comment box where users can submit a comment,
// and it stores all comments in blob storage. It displays all previous comments
// and allows new comments to be added.
import { blob } from "https://esm.town/v/std/blob?v=12";
import { Hono } from "npm:hono@3";
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
// Key for blob storage
const COMMENTS_KEY = "comments_storage";
// HTML template for the comment box
const template = (comments: any) => `
<html>
<head>
<title>Comment Box</title>
<style>
body { font-family: Arial, sans-serif; }
.comment { margin-bottom: 1em; }
.comment-list { margin-bottom: 2em; }
</style>
</head>
<body>
<h1>Comments</h1>
<div class="comment-list">
${comments.map((comment: string) => `<div class="comment">${comment}</div>`).join("")}
</div>
<form method="POST">
<textarea name="comment" rows="4" cols="50" required></textarea><br>
<button type="submit">Submit Comment</button>
</form>
</body>
</html>
`;
const app = new Hono();
app.get("/", async (c) => {
// Retrieve stored comments
const comments = await blob.getJSON(COMMENTS_KEY) || [];
// Generate HTML response
return c.html(template(comments));
});
app.post("/", async (c) => {
// Extract comment from form data
const formData = await c.req.parseBody();
const newComment = formData.comment;
// Retrieve existing comments from storage
const comments = await blob.getJSON(COMMENTS_KEY) || [];
// Add the new comment to the list
comments.push(newComment);
// Save updated comments back to storage
await blob.setJSON(COMMENTS_KEY, comments);
// Redirect back to the main page to show updated comments
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