import { serve } from "https://deno.land/std@0.115.0/http/server.ts";
import { ulid } from "https://cdn.jsdelivr.net/npm/ulid@2.3.5/+esm";
import { blob } from "https://esm.town/v/std/blob";
const key = "comments";
async function getComments(): Promise<Array<{ id: string; content: string }>> {
const comments = await blob.getJSON(key) as Array<{ id: string; content: string }> | undefined;
return comments ?? [];
}
async function addComment(content: string) {
const comments = await getComments();
comments.push({ id: ulid(), content });
await blob.setJSON(key, comments);
}
export default async function main(req: Request): Promise<Response> {
if (req.method === "POST") {
const formData = await req.formData();
const content = formData.get("content")?.toString();
if (content) {
await addComment(content);
}
return Response.redirect(req.url);
}
if (req.method === "GET") {
const comments = await getComments();
let html = `
<html>
<head>
<title>Comment Box</title>
<style>
body { font-family: sans-serif; padding: 20px; }
textarea { width: 100%; height: 100px; }
form { margin-bottom: 20px; }
.comment { margin-bottom: 10px; padding: 10px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Comment Box</h1>
<form method="post">
<textarea name="content" required></textarea><br />
<button type="submit">Submit</button>
</form>
<h2>Comments</h2>
${comments.map(c => `<div class="comment">${c.content}</div>`).join('')}
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
}
return new Response("Method not allowed", { status: 405 });
}