-
Notifications
You must be signed in to change notification settings - Fork 2
/
validator.js
30 lines (27 loc) · 984 Bytes
/
validator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { matchedData, validationResult } from "express-validator";
import ApplicationError from "../utils/utils.js";
/**
* @description express-validator schema validator
*
* @param {Array} schema
* @param {Number} status - http statusCode
*
* @returns {Array} array of validation results and middleware
*/
export default (schemas, status = 400) => {
const validationCheck = async (request, _, next) => {
const errors = validationResult(request);
request = { ...request, ...matchedData(request) };
if (!errors.isEmpty()) {
const mappedErrors = Object.entries(errors.mapped()).reduce((accumulator, [key, value]) => {
accumulator[key] = value.msg;
return accumulator;
}, {});
const validationErrors = new ApplicationError(status, mappedErrors, mappedErrors);
console.log(validationErrors);
return next(validationErrors);
}
return next();
};
return [...(schemas.length && [schemas]), validationCheck];
};