import { blob } from "https://esm.town/v/std/blob";
import { Hono } from "npm:hono";
import { html } from "https://esm.town/v/stevekrouse/html";
const SAMPLE_STORIES_KEY = "hn_sample_stories";
async function initializeSampleStories() {
const existingStories = await blob.getJSON(SAMPLE_STORIES_KEY);
if (!existingStories) {
const sampleStories = Array.from({ length: 30 }).map((_, idx) => ({
id: idx + 1,
title: `Sample Story ${idx + 1}`,
url: `https://example.com/story${idx + 1}`,
votes: Math.floor(Math.random() * 100),
}));
await blob.setJSON(SAMPLE_STORIES_KEY, sampleStories);
}
}
await initializeSampleStories();
const app = new Hono();
app.get("/", async (c) => {
const stories = await blob.getJSON(SAMPLE_STORIES_KEY) || [];
const storiesHtml = stories
.sort((a, b) => b.votes - a.votes)
.map(story => `<li>${story.title} - ${story.votes} votes
<a href="${story.url}" target="_blank">(link)</a>
<form method="POST" action="/vote" style="display:inline;">
<input type="hidden" name="id" value="${story.id}" />
<button type="submit">Upvote</button>
</form>
</li>`).join("");
return html(`<ul>${storiesHtml}</ul>
<h2>Submit a New Story</h2>
<form method="POST" action="/submit">
<input type="text" name="title" placeholder="Title" required />
<input type="url" name="url" placeholder="URL" required />
<button type="submit">Submit</button>
</form>`);
});
app.post("/submit", async (c) => {
const formData = await c.req.parseBody();
const title = formData.title;
const url = formData.url;
const stories = await blob.getJSON(SAMPLE_STORIES_KEY) || [];
const newStory = {
id: stories.length + 1,
title,
url,
votes: 0,
};
stories.push(newStory);
await blob.setJSON(SAMPLE_STORIES_KEY, stories);
return c.redirect("/");
});
app.post("/vote", async (c) => {
const formData = await c.req.parseBody();
const id = parseInt(formData.id, 10);
const stories = await blob.getJSON(SAMPLE_STORIES_KEY) || [];
const story = stories.find(s => s.id === id);
if (story) {
story.votes += 1;
await blob.setJSON(SAMPLE_STORIES_KEY, stories);
}
return c.redirect("/");
});
export default app.fetch;