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
48
49
50
51
52
import { blob } from "https://esm.town/v/std/blob";
// Initialize stories with some fake sample data
let stories = [
{ id: 1, title: "Fake Story 1", votes: 10 },
{ id: 2, title: "Fake Story 2", votes: 15 },
// add more fake stories here...
{ id: 30, title: "Fake Story 30", votes: 20 },
];
// Main function to handle HTTP requests
export default async function(req: Request): Promise<Response> {
if (req.method === "GET") {
return getStories(req);
} else if (req.method === "POST") {
return submitStory(req);
} else if (req.method === "PUT") {
return upvoteStory(req);
} else {
return new Response("Method Not Allowed", { status: 405 });
}
}
// Function to get the list of stories
async function getStories(req: Request): Promise<Response> {
let existingStories = await blob.getJSON("hacker-news-stories");
return new Response(JSON.stringify(existingStories), { headers: { "Content-Type": "application/json" } });
}
// Function to submit a new story
async function submitStory(req: Request): Promise<Response> {
const data = await req.json();
const newStory = { id: stories.length + 1, title: data.title, votes: 0 };
stories.push(newStory);
await blob.setJSON("hacker-news-stories", stories);
return new Response("Story submitted successfully", { status: 201 });
}
// Function to upvote a story
async function upvoteStory(req: Request): Promise<Response> {
const data = await req.json();
const storyId = data.id;
const storyIndex = stories.findIndex((story) => story.id === storyId);
if (storyIndex !== -1) {
stories[storyIndex].votes++;
await blob.setJSON("hacker-news-stories", stories);
return new Response("Story upvoted successfully");
} else {
return new Response("Story not found", { status: 404 });
}
}
janpaul123-valle_tmp_41699613582383728637218416331187.web.val.run
July 17, 2024