2020-04-22 15:52:17 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
2020-06-14 21:47:18 +02:00
|
|
|
import express, {Express, RequestHandler, Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
import Logger from "../Logger";
|
|
|
|
import {Server} from "http";
|
2020-06-14 21:47:18 +02:00
|
|
|
import {IncomingForm} from "formidable";
|
2020-06-14 16:26:36 +02:00
|
|
|
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}.`);
|
|
|
|
});
|
|
|
|
|
|
|
|
router.use(express.json());
|
2020-06-14 15:08:56 +02:00
|
|
|
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;
|
|
|
|
}
|
2020-06-14 21:47:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export const FILE_UPLOAD_MIDDLEWARE: (formFactory: () => IncomingForm, defaultField: string) => RequestHandler = (formFactory: () => IncomingForm, defaultField: string) => {
|
|
|
|
return async (req, res, next) => {
|
|
|
|
const form = formFactory();
|
|
|
|
try {
|
|
|
|
await new Promise<any>((resolve, reject) => {
|
|
|
|
form.parse(req, (err, fields, files) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
req.body = fields;
|
|
|
|
req.files = files;
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
const bag = new ValidationBag();
|
|
|
|
const fileError = new FileError(e);
|
|
|
|
fileError.thingName = defaultField;
|
|
|
|
bag.addMessage(fileError);
|
|
|
|
next(bag);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
};
|