swaf/src/components/ExpressAppComponent.ts

71 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
import express, {Express, Router} from "express";
import {logger, preventContextCorruptionMiddleware} from "../Logger";
2020-04-22 15:52:17 +02:00
import {Server} from "http";
2020-07-09 14:18:05 +02:00
import compression from "compression";
import Middleware from "../Middleware";
import {Type} from "../Utils";
2020-04-22 15:52:17 +02:00
export default class ExpressAppComponent extends ApplicationComponent {
private readonly addr: string;
2020-04-22 15:52:17 +02:00
private readonly port: number;
private server?: Server;
private expressApp?: Express;
2020-04-22 15:52:17 +02:00
public constructor(addr: string, port: number) {
2020-04-22 15:52:17 +02:00
super();
this.addr = addr;
2020-04-22 15:52:17 +02:00
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}.`);
2020-04-22 15:52:17 +02:00
});
2020-07-15 12:35:14 +02:00
// Proxy
app.set('trust proxy', 'loopback');
this.expressApp = app;
}
2020-04-22 15:52:17 +02:00
public async init(router: Router): Promise<void> {
router.use(preventContextCorruptionMiddleware(express.json({
type: req => req.headers['content-type']?.match(/^application\/(.+\+)?json$/),
})));
router.use(preventContextCorruptionMiddleware(express.urlencoded({
extended: true,
})));
2020-04-22 15:52:17 +02:00
2020-07-09 14:18:05 +02:00
// gzip
router.use(compression());
2020-04-22 15:52:17 +02:00
router.use((req, res, next) => {
req.middlewares = [];
req.as = <M extends Middleware>(type: Type<M>): M => {
const middleware = req.middlewares.find(m => m.constructor === type);
if (!middleware) throw new Error('Middleware ' + type.name + ' not present in this request.');
return middleware as M;
};
2020-04-22 15:52:17 +02:00
next();
});
}
public async stop(): Promise<void> {
const server = this.server;
if (server) {
await this.close('Webserver', callback => server.close(callback));
2020-04-22 15:52:17 +02:00
}
}
public getServer(): Server {
if (!this.server) throw 'Server was not initialized.';
return this.server;
}
public getExpressApp(): Express {
if (!this.expressApp) throw new Error('Express app not initialized.');
return this.expressApp;
}
2020-06-14 21:47:18 +02:00
}