import { blob } from "https://esm.town/v/std/blob";
export default async function main(req: Request): Promise<Response> {
let stories = await blob.getJSON("hackerNewsStories") || [];
if (req.method === "GET") {
return new Response(JSON.stringify(stories), { headers: { "Content-Type": "application/json" }});
} else if (req.method === "POST" || req.method === "PUT") {
const data = await req.json();
stories.push({ title: data.title, upvotes: 0 });
await blob.setJSON("hackerNewsStories", stories);
return new Response(JSON.stringify({ message: "Story submitted successfully" }), { headers: { "Content-Type": "application/json" }});
} else if (req.method === "PATCH") {
const data = await req.json();
const storyIndex = data.index;
if (stories[storyIndex]) {
stories[storyIndex].upvotes += 1;
}
await blob.setJSON("hackerNewsStories", stories);
return new Response(JSON.stringify({ message: "Story upvoted successfully" }), { headers: { "Content-Type": "application/json" }});
} else {
return new Response("Method Not Allowed", { status: 405 });
}
}