validation-result.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const _ = require('lodash');
  2. module.exports = withDefaults();
  3. module.exports.withDefaults = withDefaults;
  4. function withDefaults(options = {}) {
  5. const defaults = {
  6. formatter: error => error
  7. };
  8. _.defaults(options, defaults);
  9. function decorateAsValidationResult(obj, errors = []) {
  10. let formatter = options.formatter;
  11. obj.isEmpty = () => !errors.length;
  12. obj.array = ({ onlyFirstError } = {}) => {
  13. const used = {};
  14. let filteredErrors = !onlyFirstError ? errors : errors.filter(error => {
  15. if (used[error.param]) {
  16. return false;
  17. }
  18. used[error.param] = true;
  19. return true;
  20. });
  21. return filteredErrors.map(formatter);
  22. };
  23. obj.mapped = () => errors.reduce((mapping, error) => {
  24. if (!mapping[error.param]) {
  25. mapping[error.param] = formatter(error);
  26. }
  27. return mapping;
  28. }, {});
  29. obj.formatWith = errorFormatter => {
  30. formatter = errorFormatter;
  31. return obj;
  32. };
  33. obj.throw = () => {
  34. if (errors.length) {
  35. throw decorateAsValidationResult(new Error('Validation failed'), errors).formatWith(formatter);
  36. }
  37. };
  38. return obj;
  39. }
  40. return req => decorateAsValidationResult({}, req._validationErrors)
  41. }