63 lines
1.7 KiB
TypeScript
63 lines
1.7 KiB
TypeScript
import ApplicationComponent from "../ApplicationComponent";
|
|
import express, {Express, Router} from "express";
|
|
import Logger from "../Logger";
|
|
import {Server} from "http";
|
|
import compression from "compression";
|
|
|
|
export default class ExpressAppComponent extends ApplicationComponent<void> {
|
|
private readonly addr: string;
|
|
private readonly port: number;
|
|
private server?: Server;
|
|
private expressApp?: Express;
|
|
|
|
public constructor(addr: string, port: number) {
|
|
super();
|
|
this.addr = addr;
|
|
this.port = port;
|
|
}
|
|
|
|
public async start(app: Express): Promise<void> {
|
|
this.server = app.listen(this.port, this.addr, () => {
|
|
Logger.info(`Web server running on ${this.addr}:${this.port}.`);
|
|
});
|
|
|
|
// Proxy
|
|
app.set('trust proxy', 'loopback');
|
|
|
|
this.expressApp = app;
|
|
}
|
|
|
|
public async init(router: Router): Promise<void> {
|
|
router.use(express.json({
|
|
type: req => req.headers['content-type']?.match(/^application\/(.+\+)?json$/)
|
|
}));
|
|
router.use(express.urlencoded({
|
|
extended: true,
|
|
}));
|
|
|
|
// gzip
|
|
router.use(compression());
|
|
|
|
router.use((req, res, next) => {
|
|
req.models = {};
|
|
req.modelCollections = {};
|
|
next();
|
|
});
|
|
}
|
|
|
|
public async stop(): Promise<void> {
|
|
if (this.server) {
|
|
await this.close('Webserver', this.server, this.server.close);
|
|
}
|
|
}
|
|
|
|
public getServer(): Server {
|
|
if (!this.server) throw 'Server was not initialized.';
|
|
return this.server;
|
|
}
|
|
|
|
public getExpressApp(): Express {
|
|
return this.expressApp!;
|
|
}
|
|
}
|