swaf/src/frontend/ViewEngine.ts

56 lines
1.6 KiB
TypeScript

import {Express} from "express";
import {logger} from "../Logger.js";
import AssetPreCompiler from "./AssetPreCompiler.js";
export default abstract class ViewEngine extends AssetPreCompiler {
private static readonly globals: Record<string, unknown> = {};
public static getGlobals(): Record<string, unknown> {
return {...this.globals};
}
public static setGlobal(key: string, value: unknown): void {
this.globals[key] = value;
}
protected constructor(
targetDir: string,
assetType: string,
extension: string,
outputToPublicDir: boolean,
...additionalViewPaths: string[]
) {
super(targetDir, assetType, extension, outputToPublicDir, ...additionalViewPaths);
}
public abstract render(
file: string,
locals: Record<string, unknown>,
): Promise<string>;
public setup(app: Express, main: boolean): void {
app.engine(this.extension, (path, options, callback) => {
// Props (locals)
const locals = Object.assign(options, ViewEngine.getGlobals());
this.render(path, locals)
.then(value => callback(null, value))
.catch(err => callback(err));
});
const existingViewPaths = app.get('views');
app.set('views', Array.isArray(existingViewPaths) ?
[...new Set([
...existingViewPaths,
...this.getViewPaths(),
])] :
this.getViewPaths());
if (main) {
app.set('view engine', this.extension);
}
}
}