2021-04-28 14:04:56 +02:00
|
|
|
import {Express} from "express";
|
2021-05-03 19:29:22 +02:00
|
|
|
|
2021-11-24 22:08:38 +01:00
|
|
|
import LazyLocalsCoreComponent from "../components/core/LazyLocalsCoreComponent.js";
|
2021-05-04 17:04:14 +02:00
|
|
|
import AssetPreCompiler from "./AssetPreCompiler.js";
|
2021-03-24 21:41:13 +01:00
|
|
|
|
2021-05-04 17:04:14 +02:00
|
|
|
export default abstract class ViewEngine extends AssetPreCompiler {
|
2021-03-24 21:41:13 +01:00
|
|
|
protected constructor(
|
2021-05-04 17:04:14 +02:00
|
|
|
targetDir: string,
|
|
|
|
assetType: string,
|
|
|
|
extension: string,
|
|
|
|
outputToPublicDir: boolean,
|
2021-03-24 21:41:13 +01:00
|
|
|
...additionalViewPaths: string[]
|
|
|
|
) {
|
2021-05-04 17:04:14 +02:00
|
|
|
super(targetDir, assetType, extension, outputToPublicDir, ...additionalViewPaths);
|
2021-03-24 21:41:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public abstract render(
|
|
|
|
file: string,
|
|
|
|
locals: Record<string, unknown>,
|
2021-04-28 14:53:46 +02:00
|
|
|
): Promise<string>;
|
2021-03-24 21:41:13 +01:00
|
|
|
|
2021-11-24 22:08:38 +01:00
|
|
|
public setup(app: Express, main: boolean, lazyLocalsComponent: LazyLocalsCoreComponent): void {
|
2021-05-04 17:04:14 +02:00
|
|
|
app.engine(this.extension, (path, options, callback) => {
|
2021-11-24 22:08:38 +01:00
|
|
|
const locals = {...options};
|
|
|
|
|
|
|
|
lazyLocalsComponent.setupLazyLocals(locals);
|
2021-04-28 14:04:56 +02:00
|
|
|
|
2021-04-28 14:53:46 +02:00
|
|
|
this.render(path, locals)
|
|
|
|
.then(value => callback(null, value))
|
2021-04-28 14:04:56 +02:00
|
|
|
.catch(err => callback(err));
|
|
|
|
});
|
2021-03-24 21:41:13 +01:00
|
|
|
|
2021-04-28 14:07:11 +02:00
|
|
|
const existingViewPaths = app.get('views');
|
2021-05-04 17:04:14 +02:00
|
|
|
app.set('views', Array.isArray(existingViewPaths) ?
|
2021-04-28 14:53:46 +02:00
|
|
|
[...new Set([
|
2021-05-04 17:04:14 +02:00
|
|
|
...existingViewPaths,
|
2021-04-28 14:53:46 +02:00
|
|
|
...this.getViewPaths(),
|
|
|
|
])] :
|
2021-04-28 14:07:11 +02:00
|
|
|
this.getViewPaths());
|
2021-03-24 21:41:13 +01:00
|
|
|
|
2021-04-28 14:07:11 +02:00
|
|
|
if (main) {
|
2021-05-04 17:04:14 +02:00
|
|
|
app.set('view engine', this.extension);
|
2021-04-28 14:07:11 +02:00
|
|
|
}
|
2021-03-24 21:41:13 +01:00
|
|
|
}
|
|
|
|
}
|