import { zetaLayout } from "https://esm.town/v/rym/zetaLayout";
import { blocks as blocks2 } from "https://esm.town/v/rym/blocks";
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}`);
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);
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);
}