Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
72
73
74
75
76
77
import { blob } from "https://esm.town/v/std/blob";
// Function to initialize the stories in blob storage
const initializeStories = async () => {
const initialStories = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
title: `Sample Story ${i + 1}`,
author: `Author ${i + 1}`,
points: 0,
}));
await blob.setJSON("stories", initialStories);
};
// Function to get all stories
const getAllStories = async () => {
return await blob.getJSON("stories");
};
// Function to submit a new story
const submitNewStory = async (newStory) => {
const stories = await getAllStories();
const newId = stories.length + 1;
const storyWithId = { id: newId, ...newStory, points: 0 };
stories.push(storyWithId);
await blob.setJSON("stories", stories);
return storyWithId;
};
// Function to upvote a story
const upvoteStory = async (storyId) => {
const stories = await getAllStories();
const storyIndex = stories.findIndex((story) => story.id === storyId);
if (storyIndex !== -1) {
stories[storyIndex].points++;
await blob.setJSON("stories", stories);
return stories[storyIndex];
} else {
return null;
}
};
// Initialize the stories in blob storage
initializeStories();
export default async function main(req: Request): Promise<Response> {
const url = new URL(req.url);
if (url.pathname === "/stories" && req.method === "GET") {
const stories = await getAllStories();
return new Response(JSON.stringify(stories), { headers: { "Content-Type": "application/json" } });
}
if (url.pathname === "/submit" && req.method === "POST") {
const body = await req.json();
const newStory = await submitNewStory(body);
return new Response(JSON.stringify(newStory), { headers: { "Content-Type": "application/json" } });
}
if (url.pathname.startsWith("/upvote/") && req.method === "PATCH") {
const storyId = parseInt(url.pathname.split("/upvote/")[1]);
const upvotedStory = await upvoteStory(storyId);
if (upvotedStory) {
return new Response(JSON.stringify(upvotedStory), { headers: { "Content-Type": "application/json" } });
} else {
return new Response("Story not found", { status: 404 });
}
}
return new Response("Not Found", { status: 404 });
}
janpaul123-valle_tmp_86669542161959955391274329473221.web.val.run
July 17, 2024