From e1b5e7fdad6b0781ac52d0885efbeb6b59b5bee2 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Sat, 25 Apr 2020 16:09:47 +0200 Subject: [PATCH] Add Controller.validate and automatically handle validation errors --- src/Controller.ts | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) 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; } }