Public
Script
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
80
81
82
83
84
85
import { zetaLayout } from "https://esm.town/v/rym/zetaLayout";
import { blocks as blocks2 } from "https://esm.town/v/rym/blocks";
// Access via https://api.val.town/v1/express/rym.home
export async function home(req: express.Request, res: express.Response) {
const blocks = await blocks2();
console.log(
`Running 'home' with query: ${JSON.stringify(
req.query
)}\nbody:\n${JSON.stringify(req.body)}\n\nrequest:\n${JSON.stringify(req)}`
);
const pageName = typeof req.query.page === "string" ? req.query.page : null;
if (pageName && pageName !== "home") {
console.log(`Searching for page handler: ${pageName}`);
const currentPage = blocks[pageName];
if (!currentPage) {
res.status(404);
console.error(`missing page: '${pageName}`);
// FIXME: don't email for every 404
console.email(
`request:\n\n'${JSON.stringify(req)}'`,
`missing page: '${pageName}'`
);
const payload = zetaLayout(
"404",
`
<div class="error-page">
<h2>Page '${pageName}' not found!</h2>
<p><a href="?page=home">return to the someplace else...</a>.</p>
</div>
`
);
res.send(payload);
return;
}
const params = JSON.parse(JSON.stringify(req.body));
try {
console.log(`Page found! Trying to render!`);
const newState = currentPage.onSubmit(req.body);
const payload = zetaLayout(
pageName,
`
${currentPage.render(req.body, newState)}
`
);
res.send(payload);
} catch (e) {
console.error(e);
// FIXME: don't email for 'ignorable errors', e.g. validation / batch & then send
console.email(e.message || e.toString(), `error on '${pageName}'`);
const payload = zetaLayout(
"500",
`
<div class="error-page">
<h2>Sorry, something went wrong...</h2>
<p>Please try again or <a href="?page=home">return to the someplace else...</a>.</p>
</div>
`
);
res.send(payload);
res.status(500);
}
return;
}
const payload: string = zetaLayout(
"home",
`
<p>
<ul>
${Object.keys(blocks)
.map((pageId) => {
const linkText = blocks[pageId].title || `Visit: ${pageId}`;
return `
<li>
<a href='?page=${pageId}'>${linkText}</a>
</li>
`;
})
.join("")}
</ul>
</p>
`
);
return res.send(payload);
}
October 23, 2023