import { blob } from "https://esm.town/v/std/blob";
let stories = [
{ id: 1, title: "Fake Story 1", votes: 10 },
{ id: 2, title: "Fake Story 2", votes: 15 },
{ id: 30, title: "Fake Story 30", votes: 20 },
];
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 });
}
}
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" } });
}
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 });
}
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 });
}
}