ObjectMatcherRulePlugin.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  7. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  8. class ObjectMatcherRulePlugin {
  9. /**
  10. * @param {string} ruleProperty the rule property
  11. * @param {string=} dataProperty the data property
  12. */
  13. constructor(ruleProperty, dataProperty) {
  14. this.ruleProperty = ruleProperty;
  15. this.dataProperty = dataProperty || ruleProperty;
  16. }
  17. /**
  18. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  19. * @returns {void}
  20. */
  21. apply(ruleSetCompiler) {
  22. const { ruleProperty, dataProperty } = this;
  23. ruleSetCompiler.hooks.rule.tap(
  24. "ObjectMatcherRulePlugin",
  25. (path, rule, unhandledProperties, result) => {
  26. if (unhandledProperties.has(ruleProperty)) {
  27. unhandledProperties.delete(ruleProperty);
  28. const value = rule[ruleProperty];
  29. for (const property of Object.keys(value)) {
  30. const nestedDataProperties = property.split(".");
  31. const condition = ruleSetCompiler.compileCondition(
  32. `${path}.${ruleProperty}.${property}`,
  33. value[property]
  34. );
  35. result.conditions.push({
  36. property: [dataProperty, ...nestedDataProperties],
  37. matchWhenEmpty: condition.matchWhenEmpty,
  38. fn: condition.fn
  39. });
  40. }
  41. }
  42. }
  43. );
  44. }
  45. }
  46. module.exports = ObjectMatcherRulePlugin;