import * as ExpressValidator from 'express-validator'; import express from 'express'; import { StatusCodes } from 'http-status-codes'; class ParamsValidatorMiddleware { validate(validations: Array<ExpressValidator.ValidationChain> | ExpressValidator.Schema): (req: express.Request, res: express.Response, next: express.NextFunction) => void { return async (req: express.Request, res: express.Response, next: express.NextFunction) => { if ( !(validations instanceof Array) ) { validations = ExpressValidator.checkSchema(validations); } await Promise.all(validations.map(validation => validation.run(req))); const errors = ExpressValidator.validationResult(req); if ( !errors.isEmpty() ) { return req.session.sendResponse(res, StatusCodes.BAD_REQUEST, { errors: errors.array() }); } return next(); }; } } export default new ParamsValidatorMiddleware();