import { v4 } from "node:uuid";
import { blob } from "https://esm.town/v/std/blob";
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
const router = new Router();
let stories = [];
await blob.getJSON("stories").then((data) => {
if (data) {
stories = data;
}
});
router.get("/stories", (ctx) => {
ctx.response.body = stories;
});
router.post("/stories", async (ctx) => {
const { title, url } = await ctx.request.body().value;
const newStory = { id: v4.generate(), title, url, votes: 0 };
stories.push(newStory);
await blob.setJSON("stories", stories);
ctx.response.body = { message: "Story submitted successfully", story: newStory };
});
router.put("/stories/:id/vote", async (ctx) => {
const { id } = ctx.params;
const story = stories.find((s) => s.id === id);
if (story) {
story.votes++;
await blob.setJSON("stories", stories);
ctx.response.body = { message: "Story upvoted successfully", story };
} else {
ctx.response.status = 404;
ctx.response.body = { message: "Story not found" };
}
});
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });