swaf/src/frontend/ViewEngine.ts

46 lines
1.4 KiB
TypeScript

import {Express} from "express";
import LazyLocalsCoreComponent from "../components/core/LazyLocalsCoreComponent.js";
import AssetPreCompiler from "./AssetPreCompiler.js";
export default abstract class ViewEngine extends AssetPreCompiler {
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, lazyLocalsComponent: LazyLocalsCoreComponent): void {
app.engine(this.extension, (path, options, callback) => {
const locals = {...options};
lazyLocalsComponent.setupLazyLocals(locals);
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);
}
}
}