44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import {Express} from "express";
|
|
|
|
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): void {
|
|
app.engine(this.extension, (path, options, callback) => {
|
|
// Props (locals)
|
|
const locals = Object.assign(this.getGlobals().get(), options);
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|