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";
import { v4 } from "https://deno.land/std/uuid/mod.ts";
// Initialize blob with an empty array if it doesn't exist
await blob.setJSON("stories", []);
// Function to get all stories
const getAllStories = async () => {
const stories = await blob.getJSON("stories");
return stories;
};
// Function to add a new story
const addStory = async (title, author) => {
const newStory = {
id: v4.generate(),
title,
author,
votes: 0,
};
const stories = await getAllStories();
stories.push(newStory);
await blob.setJSON("stories", stories);
return newStory;
};
// Function to upvote a story
const upvoteStory = async (id) => {
const stories = await getAllStories();
const index = stories.findIndex((story) => story.id === id);
if (index !== -1) {
stories[index].votes += 1;
await blob.setJSON("stories", stories);
return stories[index];
} else {
return null;
}
};
// Export the functions for use in the HTTP server
export default async function main(req: Request): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;
if (req.method === "GET" && path === "/stories") {
const stories = await getAllStories();
return new Response(JSON.stringify(stories), { headers: { "Content-Type": "application/json" } });
}
if (req.method === "POST" && path === "/stories") {
const formData = await req.json();
const { title, author } = formData;
const newStory = await addStory(title, author);
return new Response(JSON.stringify(newStory), { headers: { "Content-Type": "application/json" } });
}
if (req.method === "PUT" && path === "/stories/upvote") {
const formData = await req.json();
const { id } = formData;
const upvotedStory = await upvoteStory(id);
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_88140331236158369280490149661851.web.val.run
July 17, 2024