legacy-runner.js 1.5 KB

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