swaf/src/components/FrontendToolsComponent.ts

55 lines
1.7 KiB
TypeScript
Raw Normal View History

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(
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
if (config.get<boolean>('asset_cache')) {
logger.info('Caching assets from', this.publicAssetsDir, '...');
2021-03-24 21:41:13 +01:00
await readdirRecursively(
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
this.viewEngine.setup(app, true);
2021-03-24 16:07:50 +01:00
}
public async stop(): Promise<void> {
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) => {
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
});
}
public async preCompileViews(watch: boolean): Promise<void> {
await this.viewEngine.preCompileAll(watch);
}
2021-03-18 16:22:25 +01:00
}