2020-07-11 11:46:16 +02:00
|
|
|
import express, {Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
import {PathParams} from "express-serve-static-core";
|
2020-09-24 22:33:37 +02:00
|
|
|
import * as path from "path";
|
2021-05-03 19:29:22 +02:00
|
|
|
|
|
|
|
import ApplicationComponent from "../ApplicationComponent.js";
|
|
|
|
import {logger} from "../Logger.js";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default class ServeStaticDirectoryComponent extends ApplicationComponent {
|
2020-04-22 15:52:17 +02:00
|
|
|
private readonly root: string;
|
|
|
|
private readonly path?: PathParams;
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public constructor(root: string, routePath?: PathParams) {
|
2020-04-22 15:52:17 +02:00
|
|
|
super();
|
2021-03-24 16:08:50 +01:00
|
|
|
this.root = root;
|
2020-04-22 15:52:17 +02:00
|
|
|
this.path = routePath;
|
|
|
|
}
|
|
|
|
|
2020-07-28 12:11:10 +02:00
|
|
|
public async init(router: Router): Promise<void> {
|
2021-05-03 19:29:22 +02:00
|
|
|
const resolvedRoot = path.resolve(this.root);
|
2021-03-24 16:08:50 +01:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
if (this.path) {
|
2021-03-24 16:08:50 +01:00
|
|
|
router.use(this.path, express.static(resolvedRoot, {maxAge: 1000 * 3600 * 72}));
|
2020-04-22 15:52:17 +02:00
|
|
|
} else {
|
2021-03-24 16:08:50 +01:00
|
|
|
router.use(express.static(resolvedRoot, {maxAge: 1000 * 3600 * 72}));
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
2021-03-24 16:08:50 +01:00
|
|
|
|
|
|
|
logger.info('Serving static files in', resolvedRoot, ' on ', this.path || '/');
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
}
|