swaf/src/components/FrontendToolsComponent.ts

61 lines
2.0 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(
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>('view.enable_asset_cache')) {
logger.info('Caching assets from', this.viewEngine.getPublicDir(), '...');
await readdirRecursively(
this.viewEngine.getPublicDir(),
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
// Pre-compile and watch in dev mode
if (config.get<boolean>('view.dev')) {
await this.viewEngine.preCompileAll();
await this.viewEngine.watch();
}
2021-03-24 16:07:50 +01:00
2021-03-24 21:41:13 +01:00
// Setup express view engine
app.engine(this.viewEngine.getExtension(), (path, options, callback) => {
this.viewEngine.render(path, options as Record<string, unknown>, callback)
2021-03-24 16:07:50 +01:00
.catch(err => callback(err));
});
2021-03-24 21:41:13 +01:00
app.set('views', this.viewEngine.getViewPaths());
2021-03-24 16:07:50 +01:00
app.set('view engine', 'svelte');
}
public async stop(): Promise<void> {
2021-03-24 21:41:13 +01:00
await this.viewEngine.end?.();
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-03-24 21:41:13 +01:00
return this.publicAssetsCache.getOrFail(path.join(this.viewEngine.getPublicDir(), 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
});
}
}