swaf/src/components/ExpressAppComponent.ts
2020-04-22 17:49:58 +02:00

40 lines
1.1 KiB
TypeScript

import ApplicationComponent from "../ApplicationComponent";
import express, {Express, Router} from "express";
import Logger from "../Logger";
import {Server} from "http";
export default class ExpressAppComponent extends ApplicationComponent<void> {
private readonly port: number;
private server?: Server;
constructor(port: number) {
super();
this.port = port;
}
public async start(app: Express, router: Router): Promise<void> {
this.server = app.listen(this.port, 'localhost', () => {
Logger.info(`Web server running on localhost:${this.port}.`);
});
router.use(express.json());
router.use(express.urlencoded());
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;
}
}