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
/**
* This val creates a simple hacker news clone with 30 fake sample stories.
* It uses blob storage to store story data, including the ability to submit
* new stories and upvote existing stories.
*/
import { Hono } from "npm:hono";
import { blob } from "https://esm.town/v/std/blob";
interface Story {
id: number;
title: string;
url: string;
points: number;
createdAt: string;
}
const DEFAULT_STORIES: Story[] = Array.from({ length: 30 }).map((_, idx) => ({
id: idx,
title: `Sample Story ${idx + 1}`,
url: `https://example.com/story${idx + 1}`,
points: Math.floor(Math.random() * 100),
createdAt: new Date().toISOString(),
}));
const STORIES_KEY = "hn_clone_stories";
async function getStories(): Promise<Story[]> {
return (await blob.getJSON(STORIES_KEY)) ?? DEFAULT_STORIES;
}
async function saveStories(stories: Story[]): Promise<void> {
await blob.setJSON(STORIES_KEY, stories);
}
const app = new Hono();
app.get("/", async (c) => {
const stories = await getStories();
return c.json(stories);
});
app.post("/submit", async (c) => {
const newStory = await c.req.json() as Story;
const stories = await getStories();
newStory.id = stories.length ? stories[stories.length - 1].id + 1 : 0;
newStory.points = 0;
newStory.createdAt = new Date().toISOString();
stories.push(newStory);
await saveStories(stories);
return c.json(newStory);
});
app.post("/upvote/:id", async (c) => {
const id = parseInt(c.req.param("id"));
const stories = await getStories();
const story = stories.find((story) => story.id === id);
if (!story) {
return c.json({ error: "Story not found" }, 404);
}
story.points += 1;
await saveStories(stories);
return c.json(story);
});
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