swaf/src/frontend/ViewEngine.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

import {Express} from "express";
import LazyLocalsCoreComponent from "../components/core/LazyLocalsCoreComponent.js";
import AssetPreCompiler from "./AssetPreCompiler.js";
2021-03-24 21:41:13 +01:00
export default abstract class ViewEngine extends AssetPreCompiler {
2021-03-24 21:41:13 +01:00
protected constructor(
targetDir: string,
assetType: string,
extension: string,
outputToPublicDir: boolean,
2021-03-24 21:41:13 +01:00
...additionalViewPaths: string[]
) {
super(targetDir, assetType, extension, outputToPublicDir, ...additionalViewPaths);
2021-03-24 21:41:13 +01:00
}
public abstract render(
file: string,
locals: Record<string, unknown>,
): Promise<string>;
2021-03-24 21:41:13 +01:00
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));
});
2021-03-24 21:41:13 +01:00
const existingViewPaths = app.get('views');
app.set('views', Array.isArray(existingViewPaths) ?
[...new Set([
...existingViewPaths,
...this.getViewPaths(),
])] :
this.getViewPaths());
2021-03-24 21:41:13 +01:00
if (main) {
app.set('view engine', this.extension);
}
2021-03-24 21:41:13 +01:00
}
}