coerce.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. var validateRecursive = require('./helpers/validate-recursive');
  6. var consolidateErrors = require('./helpers/consolidate-errors');
  7. /**
  8. * Coerce value to type schema
  9. * (very forgiving)
  10. *
  11. * @param {~Schema} expected type schema
  12. * @param {===} actual "mystery meat"
  13. * @return {<expected>}
  14. */
  15. module.exports = function coerce (expected, actual){
  16. // Jump into recursive validation
  17. var errors = [];
  18. var result = validateRecursive(expected, actual, errors, []);
  19. // Strip out "E_NOT_STRICTLY_VALID" errors- they are ok if we're just coercing.
  20. _.remove(errors, {code: 'E_NOT_STRICTLY_VALID'});
  21. // Strip out "E_NOT_EVEN_CLOSE" errors- they are ok if we're just coercing.
  22. _.remove(errors, {code: 'E_NOT_EVEN_CLOSE'});
  23. // Note that it would be more efficient to pass in a list of error codes
  24. // to ignore when calling `validateRecursive`, rather than iterating through
  25. // the list of errors afterwards and stripping them out.
  26. // If there are still errors, coallesce the remaining list of errors into a single
  27. // Error object we can throw.
  28. var err = consolidateErrors(errors, 'coercing value');
  29. if (err) {
  30. throw err;
  31. }
  32. else {
  33. return result;
  34. }
  35. };