swaf/src/components/ServeStaticDirectoryCompone...

30 lines
1023 B
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
import express, {Router} from "express";
2020-04-22 15:52:17 +02:00
import {PathParams} from "express-serve-static-core";
import * as path from "path";
import {logger} from "../Logger";
2020-04-22 15:52:17 +02:00
export default class ServeStaticDirectoryComponent extends ApplicationComponent {
2020-04-22 15:52:17 +02:00
private readonly root: string;
private readonly path?: PathParams;
public constructor(root: string, routePath?: PathParams) {
2020-04-22 15:52:17 +02:00
super();
this.root = root;
2020-04-22 15:52:17 +02:00
this.path = routePath;
}
public async init(router: Router): Promise<void> {
const resolvedRoot = path.join(__dirname, this.getApp().isInNodeModules() ? '../../../' : '../../', this.root);
if (this.path) {
router.use(this.path, express.static(resolvedRoot, {maxAge: 1000 * 3600 * 72}));
2020-04-22 15:52:17 +02:00
} else {
router.use(express.static(resolvedRoot, {maxAge: 1000 * 3600 * 72}));
2020-04-22 15:52:17 +02:00
}
logger.info('Serving static files in', resolvedRoot, ' on ', this.path || '/');
2020-04-22 15:52:17 +02:00
}
}