2020-09-25 22:03:22 +02:00
|
|
|
import {NextFunction, Request, Response} from "express";
|
2021-11-08 00:52:33 +01:00
|
|
|
import IncomingForm from "formidable/Formidable.js";
|
2021-05-03 19:29:22 +02:00
|
|
|
|
|
|
|
import {FileError, ValidationBag} from "./db/Validator.js";
|
|
|
|
import Middleware from "./Middleware.js";
|
2020-07-11 11:08:57 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default abstract class FileUploadMiddleware extends Middleware {
|
2021-11-08 00:52:33 +01:00
|
|
|
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 {
|
2020-09-25 23:42:15 +02:00
|
|
|
await new Promise<void>((resolve, reject) => {
|
2020-09-25 22:03:22 +02:00
|
|
|
form.parse(req, (err, fields, files) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
req.body = fields;
|
|
|
|
req.files = files;
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
2021-11-10 17:48:54 +01:00
|
|
|
} catch (e) {
|
2020-09-25 22:03:22 +02:00
|
|
|
const bag = new ValidationBag();
|
2021-11-10 17:48:54 +01:00
|
|
|
const fileError = new FileError(String(e));
|
2020-09-25 22:03:22 +02:00
|
|
|
fileError.thingName = this.getDefaultField();
|
|
|
|
bag.addMessage(fileError);
|
|
|
|
next(bag);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
next();
|
2020-07-11 11:08:57 +02:00
|
|
|
}
|
2020-09-25 23:42:15 +02:00
|
|
|
}
|