import { Hono } from "npm:hono@3";
import { blob } from "https://esm.town/v/std/blob";
const STORIES_KEY = "hn_stories";
const INITIAL_STORIES = 30;
async function initStories() {
const stories = [];
for (let i = 1; i <= INITIAL_STORIES; i++) {
stories.push({
id: i,
title: `Sample Story ${i}`,
url: `https://example.com/${i}`,
upvotes: 0,
});
}
await blob.setJSON(STORIES_KEY, stories);
}
await initStories();
const app = new Hono();
app.get("/", async (c) => {
const stories = await blob.getJSON(STORIES_KEY) || [];
return c.json(stories);
});
app.post("/submit", async (c) => {
const { title, url } = await c.req.json();
const stories = await blob.getJSON(STORIES_KEY) || [];
const newId = stories.length ? stories[stories.length - 1].id + 1 : 1;
stories.push({ id: newId, title, url, upvotes: 0 });
await blob.setJSON(STORIES_KEY, stories);
return c.text("Story submitted", 201);
});
app.post("/upvote/:id", async (c) => {
const id = parseInt(c.req.param("id"), 10);
const stories = await blob.getJSON(STORIES_KEY) || [];
const story = stories.find((s) => s.id === id);
if (story) {
story.upvotes += 1;
await blob.setJSON(STORIES_KEY, stories);
return c.text("Upvoted", 200);
}
return c.text("Story not found", 404);
});
export default app.fetch;