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
69
70
71
import { blob } from "https://esm.town/v/std/blob";
// Unique key for blob storage
const BLOB_KEY = "hn_sample_stories_blob";
// Interface for story
interface Story {
id: number;
title: string;
url: string;
votes: number;
}
export default async function main(req: Request): Promise<Response> {
const { method, url } = req;
const { pathname, searchParams } = new URL(url);
// Get all stories
if (method === "GET" && pathname === "/stories") {
let stories: Story[] = await blob.getJSON(BLOB_KEY) || generateSampleStories();
return new Response(JSON.stringify(stories), {
headers: { "Content-Type": "application/json" },
});
}
// Submit a new story
if (method === "POST" && pathname === "/stories") {
const newStory = await req.json() as Story;
let stories: Story[] = await blob.getJSON(BLOB_KEY) || [];
newStory.id = stories.length ? Math.max(...stories.map(s => s.id)) + 1 : 1;
newStory.votes = 0;
stories.push(newStory);
await blob.setJSON(BLOB_KEY, stories);
return new Response(JSON.stringify(newStory), {
headers: { "Content-Type": "application/json" },
});
}
// Upvote a story
if (method === "POST" && pathname.startsWith("/upvote")) {
const id = parseInt(pathname.split("/")[2]);
let stories: Story[] = await blob.getJSON(BLOB_KEY) || [];
let story = stories.find(s => s.id === id);
if (story) {
story.votes += 1;
await blob.setJSON(BLOB_KEY, stories);
return new Response(JSON.stringify(story), {
headers: { "Content-Type": "application/json" },
});
}
return new Response("Story not found", { status: 404 });
}
// Return a 404 for unknown paths
return new Response("Not Found", { status: 404 });
}
// Helper function to generate sample stories
function generateSampleStories(): Story[] {
const sampleStories: Story[] = [];
for (let i = 1; i <= 30; i++) {
sampleStories.push({
id: i,
title: `Sample Story ${i}`,
url: `https://example.com/story${i}`,
votes: Math.floor(Math.random() * 100),
});
}
return sampleStories;
}