2020-07-11 11:08:57 +02:00
|
|
|
import {IncomingForm} from "formidable";
|
2020-09-25 22:03:22 +02:00
|
|
|
import Middleware from "./Middleware";
|
|
|
|
import {NextFunction, Request, Response} from "express";
|
|
|
|
import {FileError, ValidationBag} from "./db/Validator";
|
2020-07-11 11:08:57 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default abstract class FileUploadMiddleware extends Middleware {
|
|
|
|
protected abstract makeForm(): IncomingForm;
|
2020-07-11 11:08:57 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
protected abstract getDefaultField(): string;
|
|
|
|
|
|
|
|
public async handle(req: Request, res: Response, next: NextFunction): Promise<void> {
|
|
|
|
const form = this.makeForm();
|
|
|
|
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 = this.getDefaultField();
|
|
|
|
bag.addMessage(fileError);
|
|
|
|
next(bag);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
next();
|
2020-07-11 11:08:57 +02:00
|
|
|
}
|
|
|
|
}
|