UNPKG

1.52 kBJavaScriptView Raw
1const _ = require('lodash');
2const selectFields = require('../utils/select-fields');
3const utils = require('./utils');
4
5module.exports = function(contexts, req) {
6 _(contexts)
7 .filter(context => !context.ran)
8 .flatMap(context => {
9 return _(selectFields(req, context))
10 .map(field => ({ field, context }))
11 .groupBy(pair => pair.field.path)
12 .map(pairs => pairs[0])
13 .value();
14 })
15 .forEach(pairs => {
16 const { field, context } = pairs;
17
18 context.validators.map(validatorCfg => {
19 const result = validatorCfg.validator(
20 validatorCfg.custom ? field.value : utils.toString(field.value),
21 ...validatorCfg.options
22 );
23
24 const errorObj = {
25 location: field.location,
26 value: field.value,
27 param: utils.formatParamOutput(field.path),
28 msg: utils.replaceArgs(
29 validatorCfg.message || context.message || 'Invalid value',
30 [field.value, ...validatorCfg.options]
31 )
32 };
33
34 if (result && result.then) {
35 req._asyncValidationErrors.push(result.then(() => {
36 validatorCfg.negated && req._validationErrors.push(errorObj);
37 }, () => {
38 !validatorCfg.negated && req._validationErrors.push(errorObj);
39 }));
40 } else if ((!validatorCfg.negated && !result) || (validatorCfg.negated && result)) {
41 req._validationErrors.push(errorObj);
42 }
43 });
44
45 context.ran = true;
46 });
47};
\No newline at end of file