janpaul123-valle_tmp_90775096713594030038814365860220246.web.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Hono } from "npm:hono";
import { blob } from "https://esm.town/v/std/blob";
// Define interface for Story object
interface Story {
id: number;
title: string;
url: string;
points: number;
}
const app = new Hono();
const BLOB_KEY = "hacker_news_stories";
// Add 30 fake sample 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);
}
// Ensure stories are initialized
initializeStories();
// Get all stories
app.get("/", async (c) => {
const stories = (await blob.getJSON(BLOB_KEY)) as Story[];
return c.json(stories);
});
// Submit a new story
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);
});
// Upvote a story by ID
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 the Hono app as the default fetch handler
export default app.fetch;
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 17, 2024