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
78
79
// This approach will use the Notion API to update a block's color.
// We'll create a simple HTML page with a button, and use JavaScript to handle
// the click event and make a request to our Val Town function.
// The function will then make a request to the Notion API to update the block.
import { Hono } from "npm:hono";
const app = new Hono();
// Main page with the button
app.get("/", (c) => {
return c.html(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Randomize Notion Block Color</title>
<style>
body { margin: 0; padding: 20px; }
button {
padding: 10px 20px;
font-size: 18px;
background-color: #4a90e2;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
border: 1px solid rgba(255,255,255,0.3);
}
</style>
</head>
<body>
<button id="randomizeBtn">RANDOMIZE</button>
<script>
document.getElementById('randomizeBtn').addEventListener('click', async () => {
const response = await fetch('/randomize', { method: 'POST' });
const result = await response.json();
alert(result.message);
});
</script>
</body>
</html>
`);
});
// Endpoint to handle randomization
app.post("/randomize", async (c) => {
const blockId = Deno.env.get("TOWNIE_BLOCK_ID");
const notionApiKey = Deno.env.get("TOWNIE_NOTION_API_KEY");
if (!blockId || !notionApiKey) {
return c.json({ message: "Missing environment variables" }, 500);
}
const colors = ["blue_background", "brown_background", "gray_background", "green_background", "orange_background", "pink_background", "purple_background", "red_background", "yellow_background"];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
const response = await fetch(`https://api.notion.com/v1/blocks/${blockId}`, {
method: "PATCH",
headers: {
"Authorization": `Bearer ${notionApiKey}`,
"Notion-Version": "2022-06-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
callout: { color: randomColor }
}),
});
if (response.ok) {
return c.json({ message: `Block color changed to ${randomColor}` });
} else {
return c.json({ message: "Failed to update block color" }, 500);
}
});
export default app.fetch;
jdan-grimpinklimpet.web.val.run
August 8, 2024