UNPKG

counterfact

Version:

a library for building a fake REST API for testing

24 lines (23 loc) 991 B
import nodePath from "node:path"; import { fileURLToPath } from "node:url"; import createDebug from "debug"; import Handlebars from "handlebars"; import { readFile } from "../util/read-file.js"; const __dirname = nodePath.dirname(fileURLToPath(import.meta.url)); const debug = createDebug("counterfact:server:page-middleware"); Handlebars.registerHelper("escape_route", (route) => route.replaceAll(/[^\w/]/gu, "-")); export function pageMiddleware(pathname, templateName, locals) { return async (ctx, next) => { const pathToHandlebarsTemplate = nodePath .join(__dirname, `../client/${templateName}.html.hbs`) .replaceAll("\\", "/"); const render = Handlebars.compile(await readFile(pathToHandlebarsTemplate)); if (ctx.URL.pathname === pathname) { debug("rendering page: %s", pathname); debug("locals: %o", locals); ctx.body = render(locals); return; } await next(); }; }