match.js 864 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. var rules = require('./rules');
  6. /**
  7. * Match a miscellaneous rule
  8. * Returns an empty list on success,
  9. * or a list of errors if things go wrong
  10. */
  11. module.exports = function matchRule (data, ruleName, args) {
  12. var self = this;
  13. // if args is an array we need to make it a nested array
  14. if (Array.isArray(args) && ruleName !== 'len') {
  15. args = [args];
  16. }
  17. // Ensure args is a list, then prepend it with data
  18. if (!_.isArray(args)) {
  19. args = [args];
  20. }
  21. // push data on to front
  22. args.unshift(data);
  23. // Lookup rule and determine outcome
  24. var rule = rules[ruleName];
  25. if (!rule) {
  26. throw new Error('Unknown rule: ' + ruleName);
  27. }
  28. var errorMessage = rule.apply(self, args);
  29. if (errorMessage) { return [{rule: ruleName, message: errorMessage}]; }
  30. return [];
  31. };