import { Hono } from "npm:hono";
import { blob } from "https://esm.town/v/std/blob";
interface Story {
id: number;
title: string;
url: string;
points: number;
}
const app = new Hono();
const BLOB_KEY = "hacker_news_stories";
async function initializeStories() {
let stories: Story[] = [];
for (let i = 1; i <= 30; i++) {
stories.push({
id: i,
title: `Sample Story ${i}`,
url: `https://example.com/${i}`,
points: Math.floor(Math.random() * 100),
});
}
await blob.setJSON(BLOB_KEY, stories);
}
initializeStories();
app.get("/", async (c) => {
const stories = (await blob.getJSON(BLOB_KEY)) as Story[];
return c.json(stories);
});
app.post("/submit", async (c) => {
const { title, url } = await c.req.json();
const stories = (await blob.getJSON(BLOB_KEY)) as Story[];
const newStory: Story = {
id: stories.length + 1,
title,
url,
points: 0,
};
stories.push(newStory);
await blob.setJSON(BLOB_KEY, stories);
return c.json(newStory);
});
app.post("/upvote/:id", async (c) => {
const stories = (await blob.getJSON(BLOB_KEY)) as Story[];
const story = stories.find(s => s.id === parseInt(c.req.param("id")));
if (!story) {
return c.notFound({ message: "Story not found" });
}
story.points += 1;
await blob.setJSON(BLOB_KEY, stories);
return c.json(story);
});
export default app.fetch;