swaf/src/components/ExpressAppComponent.ts

60 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
import express, {Express, NextFunction, Request, Response, Router} from "express";
2020-04-22 15:52:17 +02:00
import Logger from "../Logger";
import {Server} from "http";
import {MulterError} from "multer";
import {FileError, ValidationBag} from "../db/Validator";
2020-04-22 15:52:17 +02:00
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}.`);
});
this.app?.setupRequestParsingMiddlewares(router);
// Multer error handler
router.use((err: any, req: Request, res: Response, next: NextFunction) => {
if (err instanceof MulterError) {
const bag = new ValidationBag();
const validationError = new FileError(err.message);
validationError.thingName = err.field;
bag.addMessage(validationError);
req.flash('validation', bag.getMessages());
res.redirectBack();
} else {
next(err);
}
});
2020-04-22 15:52:17 +02:00
router.use(express.json());
router.use(express.urlencoded({
extended: true,
}));
2020-04-22 15:52:17 +02:00
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;
}
}