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
// Import the required modules
import { blob } from "https://esm.town/v/std/blob";
// Fetch all stories or initialize an empty array if no data exists yet
export default async function main(req: Request): Promise<Response> {
let stories = await blob.getJSON("hackerNewsStories") || [];
// Check the request method to determine the action
if (req.method === "GET") {
// Return the list of stories
return new Response(JSON.stringify(stories), { headers: { "Content-Type": "application/json" }});
} else if (req.method === "POST" || req.method === "PUT") {
// Parse the request body to get the new story data
const data = await req.json();
// Add the new story to the list
stories.push({ title: data.title, upvotes: 0 });
// Store the updated list back to the blob storage
await blob.setJSON("hackerNewsStories", stories);
// Return success response
return new Response(JSON.stringify({ message: "Story submitted successfully" }), { headers: { "Content-Type": "application/json" }});
} else if (req.method === "PATCH") {
// Parse the request body to get the story index to upvote
const data = await req.json();
const storyIndex = data.index;
// Increment the upvotes count for the selected story
if (stories[storyIndex]) {
stories[storyIndex].upvotes += 1;
}
// Store the updated list back to the blob storage
await blob.setJSON("hackerNewsStories", stories);
// Return success response
return new Response(JSON.stringify({ message: "Story upvoted successfully" }), { headers: { "Content-Type": "application/json" }});
} else {
// For unsupported requests, return a 405 Method Not Allowed response
return new Response("Method Not Allowed", { status: 405 });
}
}
janpaul123-valle_tmp_0849921550869434716277180134862967.web.val.run
July 17, 2024