janpaul123-valle_tmp_069034869725444597641897580363524.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
import { Hono } from "npm:hono@3"; // Use Hono for routing
import { blob } from "https://esm.town/v/std/blob"; // For blob storage
// Define the key for blob storage
const STORIES_KEY = "hn_stories";
const INITIAL_STORIES = 30;
// Generate some sample stories to start with
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);
}
// Initialize the stories if they're not already set
await initStories();
// Define the routes
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;
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