2021-03-24 16:07:50 +01:00
|
|
|
import {Express, Router} from "express";
|
2021-03-18 16:22:25 +01:00
|
|
|
import path from "path";
|
|
|
|
import config from "config";
|
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
|
|
|
import {logger} from "../Logger";
|
2021-03-24 16:07:50 +01:00
|
|
|
import "svelte/register";
|
2021-03-24 21:41:13 +01:00
|
|
|
import ViewEngine from "../frontend/ViewEngine";
|
|
|
|
import {readdirRecursively} from "../Utils";
|
|
|
|
import FileCache from "../utils/FileCache";
|
2021-03-18 16:22:25 +01:00
|
|
|
|
|
|
|
export default class FrontendToolsComponent extends ApplicationComponent {
|
2021-03-24 21:41:13 +01:00
|
|
|
private readonly publicAssetsCache: FileCache = new FileCache();
|
2021-03-18 16:22:25 +01:00
|
|
|
|
|
|
|
public constructor(
|
2021-04-28 14:07:11 +02:00
|
|
|
private readonly publicAssetsDir: string,
|
2021-03-24 21:41:13 +01:00
|
|
|
private readonly viewEngine: ViewEngine,
|
2021-03-18 16:22:25 +01:00
|
|
|
) {
|
|
|
|
super();
|
|
|
|
}
|
|
|
|
|
2021-03-24 16:07:50 +01:00
|
|
|
public async start(app: Express): Promise<void> {
|
2021-03-24 21:41:13 +01:00
|
|
|
// Cache public assets
|
2021-04-27 15:08:41 +02:00
|
|
|
if (config.get<boolean>('asset_cache')) {
|
2021-04-28 14:07:11 +02:00
|
|
|
logger.info('Caching assets from', this.publicAssetsDir, '...');
|
2021-03-24 21:41:13 +01:00
|
|
|
await readdirRecursively(
|
2021-04-28 14:07:11 +02:00
|
|
|
this.publicAssetsDir,
|
2021-03-24 21:41:13 +01:00
|
|
|
async file => await this.publicAssetsCache.load(file),
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
logger.info('Asset cache disabled.');
|
|
|
|
}
|
2021-03-18 16:22:25 +01:00
|
|
|
|
2021-03-24 21:41:13 +01:00
|
|
|
// Setup express view engine
|
2021-04-28 14:07:11 +02:00
|
|
|
this.viewEngine.setup(app, true);
|
2021-03-24 16:07:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public async stop(): Promise<void> {
|
2021-03-26 10:56:32 +01:00
|
|
|
await this.viewEngine.stop();
|
2021-03-18 16:22:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public async handle(router: Router): Promise<void> {
|
|
|
|
router.use((req, res, next) => {
|
|
|
|
res.locals.inlineAsset = (urlPath: string) => {
|
2021-04-28 14:07:11 +02:00
|
|
|
return this.publicAssetsCache.getOrFail(path.join(this.publicAssetsDir, urlPath));
|
2021-03-18 16:22:25 +01:00
|
|
|
};
|
2021-03-24 16:07:50 +01:00
|
|
|
|
2021-03-24 21:41:13 +01:00
|
|
|
next();
|
2021-03-18 16:22:25 +01:00
|
|
|
});
|
|
|
|
}
|
2021-03-26 10:56:32 +01:00
|
|
|
|
|
|
|
public async preCompileViews(watch: boolean): Promise<void> {
|
|
|
|
await this.viewEngine.preCompileAll(watch);
|
|
|
|
}
|
2021-03-18 16:22:25 +01:00
|
|
|
}
|