swaf/src/FileUploadMiddleware.ts

36 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-03-30 12:06:10 +02:00
import Formidable from "formidable";
import Middleware from "./Middleware";
import {NextFunction, Request, Response} from "express";
import {FileError, ValidationBag} from "./db/Validator";
export default abstract class FileUploadMiddleware extends Middleware {
2021-03-30 12:06:10 +02:00
protected abstract makeForm(): Formidable;
protected abstract getDefaultField(): string;
public async handle(req: Request, res: Response, next: NextFunction): Promise<void> {
const form = this.makeForm();
try {
await new Promise<void>((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();
}
}