diff --git a/src/Controller.ts b/src/Controller.ts index d9ab8ab..bbdbd53 100644 --- a/src/Controller.ts +++ b/src/Controller.ts @@ -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) => { - const promise = handler.call(this, req, res, next); - if (promise instanceof Promise) { - promise.catch(err => next(err)); + 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(e => { + handleErr(e); + }); + } + } catch (e) { + handleErr(e); } }; } @@ -118,11 +133,21 @@ export default abstract class Controller { } protected async validate(validationMap: { [p: string]: Validator }, body: any): Promise { + const bag = new ValidationBag(); + for (const p in validationMap) { 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; } }