Add very basic support for finding and rendering templates

This commit is contained in:
2026-01-10 13:50:44 -06:00
parent 9e3329fa58
commit 6e96c33457
4 changed files with 67 additions and 0 deletions

18
express/basic/routes.ts Normal file
View File

@@ -0,0 +1,18 @@
import { DateTime } from "ts-luxon";
import type { Call, Result, Route } from "../types";
import { html, render } from "../util";
const routes: Record<string, Route> = {
hello: {
path: "/hello",
methods: ["GET"],
handler: async (call: Call): Promise<Result> => {
const now = DateTime.now();
const c = await render("basic/hello", { now });
return html(c);
},
},
};
export { routes };

View File

@@ -3,6 +3,7 @@
import nunjucks from "nunjucks"; import nunjucks from "nunjucks";
import { DateTime } from "ts-luxon"; import { DateTime } from "ts-luxon";
import { authRoutes } from "./auth/routes"; import { authRoutes } from "./auth/routes";
import { routes as basicRoutes } from "./basic/routes";
import { contentTypes } from "./content-types"; import { contentTypes } from "./content-types";
import { multiHandler } from "./handlers"; import { multiHandler } from "./handlers";
import { httpCodes } from "./http-codes"; import { httpCodes } from "./http-codes";
@@ -24,6 +25,7 @@ const okText = (result: string): Result => {
const routes: Route[] = [ const routes: Route[] = [
...authRoutes, ...authRoutes,
basicRoutes.hello,
{ {
path: "/slow", path: "/slow",
methods: ["GET"], methods: ["GET"],

36
express/util.ts Normal file
View File

@@ -0,0 +1,36 @@
import { readFile } from "node:fs/promises";
import nunjucks from "nunjucks";
import { contentTypes } from "./content-types";
import { executionContext } from "./execution-context";
import { httpCodes } from "./http-codes";
import type { Result } from "./types";
// FIXME: Handle the error here
const loadFile = async (path: string): Promise<string> => {
// Specifying 'utf8' returns a string; otherwise, it returns a Buffer
const data = await readFile(path, "utf8");
return data;
};
const render = async (path: string, ctx: object): Promise<string> => {
const fullPath = `${executionContext.diachron_root}/templates/${path}.html.njk`;
const template = await loadFile(fullPath);
const retval = nunjucks.renderString(template, ctx);
return retval;
};
const html = (payload: string): Result => {
const retval: Result = {
code: httpCodes.success.OK,
result: payload,
contentType: contentTypes.text.html,
};
return retval;
};
export { render, html };

View File

@@ -0,0 +1,11 @@
<html>
<head></head>
<body>
<p>
Hello.
</p>
<p>
The current time is {{ now }}.
</p>
</body>
</html>