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
/** This code sets up a simple comment box system.
* It leverages Deno's blob storage for persistence,
* and renders an HTML form to accept new comments,
* while displaying all existing comments.
*/
import { blob } from "https://esm.town/v/std/blob";
// Key for blob storage
const COMMENTS_KEY = "comments_storage";
// HTML template for the form and comments list
const getHtml = (comments: string[]) => `
<html>
<head>
<title>Comment Box</title>
</head>
<body>
<h1>Comment Box</h1>
<form method="POST">
<textarea name="comment" rows="4" cols="50"></textarea><br />
<button type="submit">Submit</button>
</form>
<h2>Previous Comments:</h2>
<ul>
${comments.map(comment => `<li>${comment}</li>`).join('')}
</ul>
</body>
</html>
`;
export default async function main(req: Request): Promise<Response> {
// Fetch existing comments
let comments: string[] = await blob.getJSON(COMMENTS_KEY) || [];
if (req.method === "POST") {
const formData = await req.formData();
const newComment = formData.get("comment")?.toString().trim();
if (newComment) {
// Append the new comment and save to blob storage
comments.push(newComment);
await blob.setJSON(COMMENTS_KEY, comments);
// Redirect to avoid resubmission on page refresh
return Response.redirect(new URL(req.url).origin);
}
}
// Return the HTML with comments
return new Response(getHtml(comments), {
headers: { "Content-Type": "text/html" }
});
}