Add Controller.validate and automatically handle validation errors

This commit is contained in:
Alice Gaudon 2020-04-25 16:09:47 +02:00
parent 49fc92df5c
commit e1b5e7fdad

View File

@ -2,7 +2,7 @@ import {RequestHandler, Router} from "express";
import {PathParams} from "express-serve-static-core";
import config from "config";
import Logger from "./Logger";
import Validator from "./db/Validator";
import Validator, {ValidationBag} from "./db/Validator";
export default abstract class Controller {
private static readonly routes: { [p: string]: string } = {};
@ -82,9 +82,24 @@ export default abstract class Controller {
private wrap(handler: RequestHandler): RequestHandler {
return (req, res, next) => {
function handleErr(e: any) {
if (e instanceof ValidationBag) {
req.flash('validation', e.getMessages());
res.redirectBack();
} else {
next(e);
}
}
try {
const promise = handler.call(this, req, res, next);
if (promise instanceof Promise) {
promise.catch(err => next(err));
promise.catch(e => {
handleErr(e);
});
}
} catch (e) {
handleErr(e);
}
};
}
@ -118,12 +133,22 @@ export default abstract class Controller {
}
protected async validate(validationMap: { [p: string]: Validator<any> }, body: any): Promise<void> {
const bag = new ValidationBag();
for (const p in validationMap) {
if (validationMap.hasOwnProperty(p)) {
try {
await validationMap[p].execute(p, body[p], false);
}
} catch (e) {
if (e instanceof ValidationBag) {
bag.addBag(e);
} else throw e;
}
}
}
if (bag.hasMessages()) throw bag;
}
}
export type RouteParams = { [p: string]: string } | string[] | string | number;