import { blob } from "https://esm.town/v/std/blob";
import { v4 } from "https://deno.land/std/uuid/mod.ts";
await blob.setJSON("stories", []);
const getAllStories = async () => {
const stories = await blob.getJSON("stories");
return stories;
};
const addStory = async (title, author) => {
const newStory = {
id: v4.generate(),
title,
author,
votes: 0,
};
const stories = await getAllStories();
stories.push(newStory);
await blob.setJSON("stories", stories);
return newStory;
};
const upvoteStory = async (id) => {
const stories = await getAllStories();
const index = stories.findIndex((story) => story.id === id);
if (index !== -1) {
stories[index].votes += 1;
await blob.setJSON("stories", stories);
return stories[index];
} else {
return null;
}
};
export default async function main(req: Request): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;
if (req.method === "GET" && path === "/stories") {
const stories = await getAllStories();
return new Response(JSON.stringify(stories), { headers: { "Content-Type": "application/json" } });
}
if (req.method === "POST" && path === "/stories") {
const formData = await req.json();
const { title, author } = formData;
const newStory = await addStory(title, author);
return new Response(JSON.stringify(newStory), { headers: { "Content-Type": "application/json" } });
}
if (req.method === "PUT" && path === "/stories/upvote") {
const formData = await req.json();
const { id } = formData;
const upvotedStory = await upvoteStory(id);
if (upvotedStory) {
return new Response(JSON.stringify(upvotedStory), { headers: { "Content-Type": "application/json" } });
} else {
return new Response("Story not found", { status: 404 });
}
}
return new Response("Not Found", { status: 404 });
}