swaf/src/components/ServeStaticDirectoryComponent.ts
Alice Gaudon a3ebf46b54 Add ApplicationComponent init lifecycle step and unstatic globals
This renames ApplicationComponent (previous) init to initRoutes and handle to handleRoutes
2021-05-13 16:03:59 +02:00

31 lines
970 B
TypeScript

import express, {Router} from "express";
import {PathParams} from "express-serve-static-core";
import * as path from "path";
import ApplicationComponent from "../ApplicationComponent.js";
import {logger} from "../Logger.js";
export default class ServeStaticDirectoryComponent extends ApplicationComponent {
private readonly root: string;
private readonly path?: PathParams;
public constructor(root: string, routePath?: PathParams) {
super();
this.root = root;
this.path = routePath;
}
public async initRoutes(router: Router): Promise<void> {
const resolvedRoot = path.resolve(this.root);
if (this.path) {
router.use(this.path, express.static(resolvedRoot, {maxAge: 1000 * 3600 * 72}));
} else {
router.use(express.static(resolvedRoot, {maxAge: 1000 * 3600 * 72}));
}
logger.info('Serving static files in', resolvedRoot, ' on ', this.path || '/');
}
}