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 {PathParams} from "express-serve-static-core";
import config from "config"; import config from "config";
import Logger from "./Logger"; import Logger from "./Logger";
import Validator from "./db/Validator"; import Validator, {ValidationBag} from "./db/Validator";
export default abstract class Controller { export default abstract class Controller {
private static readonly routes: { [p: string]: string } = {}; private static readonly routes: { [p: string]: string } = {};
@ -82,9 +82,24 @@ export default abstract class Controller {
private wrap(handler: RequestHandler): RequestHandler { private wrap(handler: RequestHandler): RequestHandler {
return (req, res, next) => { return (req, res, next) => {
const promise = handler.call(this, req, res, next); function handleErr(e: any) {
if (promise instanceof Promise) { if (e instanceof ValidationBag) {
promise.catch(err => next(err)); 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(e => {
handleErr(e);
});
}
} catch (e) {
handleErr(e);
} }
}; };
} }
@ -118,11 +133,21 @@ export default abstract class Controller {
} }
protected async validate(validationMap: { [p: string]: Validator<any> }, body: any): Promise<void> { protected async validate(validationMap: { [p: string]: Validator<any> }, body: any): Promise<void> {
const bag = new ValidationBag();
for (const p in validationMap) { for (const p in validationMap) {
if (validationMap.hasOwnProperty(p)) { if (validationMap.hasOwnProperty(p)) {
await validationMap[p].execute(p, body[p], false); 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;
} }
} }