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
import { v4 } from "node:uuid";
import { blob } from "https://esm.town/v/std/blob";
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
const router = new Router();
let stories = [];
// Retrieve stories data from blob storage on server start
await blob.getJSON("stories").then((data) => {
if (data) {
stories = data;
}
});
// Endpoint to get all stories
router.get("/stories", (ctx) => {
ctx.response.body = stories;
});
// Endpoint to submit a new story
router.post("/stories", async (ctx) => {
const { title, url } = await ctx.request.body().value;
const newStory = { id: v4.generate(), title, url, votes: 0 };
stories.push(newStory);
// Update blob storage with new stories data
await blob.setJSON("stories", stories);
ctx.response.body = { message: "Story submitted successfully", story: newStory };
});
// Endpoint to upvote a story
router.put("/stories/:id/vote", async (ctx) => {
const { id } = ctx.params;
const story = stories.find((s) => s.id === id);
if (story) {
story.votes++;
// Update blob storage with updated stories data
await blob.setJSON("stories", stories);
ctx.response.body = { message: "Story upvoted successfully", story };
} else {
ctx.response.status = 404;
ctx.response.body = { message: "Story not found" };
}
});
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });
janpaul123-valle_tmp_3373497323659926417371153829721253.web.val.run
July 17, 2024