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
import { blob } from "https://esm.town/v/std/blob";
// Initialize stories with sample data
let stories = [
{ id: 1, title: "Fake Story 1", upvotes: 10 },
{ id: 2, title: "Fake Story 2", upvotes: 20 },
// Add more sample stories here
];
// Main function to handle HTTP requests
export default async function main(req: Request): Promise<Response> {
if (req.method === "GET") {
// Get the list of stories
return Response.json(stories);
} else if (req.method === "POST") {
const newStory = await req.json();
// Generate a unique ID for the new story
newStory.id = stories.length + 1;
newStory.upvotes = 0;
// Add the new story to the list
stories.push(newStory);
// Save the updated list of stories to blob storage
await blob.setJSON("hackernews_stories", stories);
return new Response("Story added successfully");
} else if (req.method === "PATCH") {
const { id, action } = await req.json();
// Find the story to upvote
const story = stories.find((s) => s.id === id);
// Perform the upvote action
if (action === "upvote" && story) {
story.upvotes++;
await blob.setJSON("hackernews_stories", stories);
return new Response("Story upvoted successfully");
} else {
return new Response("Story or action not found", { status: 404 });
}
}
return new Response("Method not allowed", { status: 405 });
}
janpaul123-valle_tmp_893740469510018430011448967223986.web.val.run
July 17, 2024