validate.js 990 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Module dependencies
  3. */
  4. var validateRecursive = require('./helpers/validate-recursive');
  5. var consolidateErrors = require('./helpers/consolidate-errors');
  6. /**
  7. * Validate a bit of mystery meat (`actual`) against an `expected` type schema,
  8. * saving up any fatal errors and throwing them in a lump, and otherwise
  9. * returning the value that was accepted (i.e. because some coercion might have
  10. * occurred)
  11. *
  12. * @param {~Schema} expected type schema
  13. * @param {===} actual "mystery meat"
  14. * @return {<expected>}
  15. */
  16. module.exports = function validate (expected, actual) {
  17. var errors = [];
  18. var result = validateRecursive(expected, actual, errors, [], false);
  19. // ( `false` => `strict` -- i.e. ignore minor type errors)
  20. // If there are still errors, coallesce the remaining list of errors into a single
  21. // Error object we can throw.
  22. var err = consolidateErrors(errors, 'validating value');
  23. if (err) {
  24. throw err;
  25. } else {
  26. return result;
  27. }
  28. };