Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
/** 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.
* Tailwind CSS is used for styling.
*/
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>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-6">
<div class="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
<div class="md:flex">
<div class="p-8">
<h1 class="block mt-1 text-lg leading-tight font-medium text-black">Comment Box</h1>
<form method="POST" class="mt-4">
<textarea name="comment" rows="4" cols="50" class="w-full p-2 border rounded-lg focus:outline-none focus:shadow-outline" placeholder="Write your comment here..."></textarea><br />
<button class="mt-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" type="submit">Submit</button>
</form>
<h2 class="mt-8 text-xl leading-tight font-medium text-black">Previous Comments:</h2>
<ul class="mt-4 space-y-2">
${comments.map(comment => `<li class="p-4 bg-gray-50 rounded-lg shadow-md">${comment}</li>`).join('')}
</ul>
</div>
</div>
</div>
</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" }
});
}
janpaul123-valle_tmp_18509498710822885445406823160177.web.val.run
July 17, 2024