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
// This val implements a simple comments system using Val Town's Blob storage for persistence.
// It handles GET requests to retrieve comments and POST requests to add new comments.
// The approach uses the built-in Request and Response objects for handling HTTP requests.
// Tradeoffs: This is a basic implementation without user authentication or spam prevention.
import { blob } from "https://esm.town/v/std/blob";
const KEY = new URL(import.meta.url).pathname;
interface Comment {
text: string;
timestamp: number;
}
export default async function main(req: Request): Promise<Response> {
if (req.method === "GET") {
// Retrieve and return all comments
const comments = await blob.getJSON<Comment[]>(KEY) || [];
return Response.json(comments);
} else if (req.method === "POST") {
// Add a new comment
const text = await req.text();
const comments = await blob.getJSON<Comment[]>(KEY) || [];
comments.push({ text, timestamp: Date.now() });
await blob.setJSON(KEY, comments);
return new Response("Comment added successfully", { status: 201 });
} else {
// Handle unsupported methods
return new Response("Method not allowed", { status: 405 });
}
}