Add very basic support for finding and rendering templates
This commit is contained in:
36
express/util.ts
Normal file
36
express/util.ts
Normal 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 };
|
||||
Reference in New Issue
Block a user