runner.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const toString = require('../utils/to-string');
  2. const selectFields = require('../utils/select-fields');
  3. module.exports = (req, context) => {
  4. const validationErrors = [];
  5. const promises = selectFields(req, context).map(field => {
  6. const { location, path, value } = field;
  7. return context.validators.reduce((promise, validatorCfg) => promise.then(() => {
  8. const result = validatorCfg.custom ?
  9. validatorCfg.validator(value, { req, location, path }) :
  10. validatorCfg.validator(toString(value), ...validatorCfg.options);
  11. return getActualResult(result).then(result => {
  12. if ((!validatorCfg.negated && !result) || (validatorCfg.negated && result)) {
  13. return Promise.reject();
  14. }
  15. });
  16. }).catch(err => {
  17. validationErrors.push({
  18. location,
  19. param: path,
  20. value: field.originalValue,
  21. msg: getDynamicMessage([
  22. validatorCfg.message,
  23. err && err.message,
  24. err,
  25. context.message,
  26. 'Invalid value'
  27. ], field, req)
  28. });
  29. }), Promise.resolve());
  30. });
  31. return Promise.all(promises).then(() => validationErrors);
  32. };
  33. function getActualResult(result) {
  34. const promiseLike = result && !!result.then;
  35. return Promise.resolve(result).then(result => {
  36. return result === undefined && promiseLike ? true : result;
  37. });
  38. }
  39. function getDynamicMessage(messageSources, field, req) {
  40. const message = messageSources.find(message => !!message);
  41. if (typeof message !== 'function') {
  42. return message;
  43. }
  44. return message(field.originalValue, {
  45. req,
  46. location: field.location,
  47. path: field.path
  48. });
  49. }