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
// This approach uses Val Town's Blob storage for persisting comments.
// It handles GET requests to retrieve comments and POST requests to add new ones.
// The main tradeoff is simplicity vs. robustness - there's no user authentication or spam protection.
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", { status: 201 });
} else {
return new Response("Method not allowed", { status: 405 });
}
}
michaelnollox-spotify.web.val.run
August 17, 2024