swaf/src/FileUploadMiddleware.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

import {NextFunction, Request, Response} from "express";
2021-11-08 00:52:33 +01:00
import IncomingForm from "formidable/Formidable.js";
import {FileError, ValidationBag} from "./db/Validator.js";
import Middleware from "./Middleware.js";
export default abstract class FileUploadMiddleware extends Middleware {
2021-11-08 00:52:33 +01:00
protected abstract makeForm(): IncomingForm;
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();
});
});
2021-11-10 17:48:54 +01:00
} catch (e) {
const bag = new ValidationBag();
2021-11-10 17:48:54 +01:00
const fileError = new FileError(String(e));
fileError.thingName = this.getDefaultField();
bag.addMessage(fileError);
next(bag);
return;
}
next();
}
}