ObjectMatcherRulePlugin.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. constructor(ruleProperty, dataProperty) {
  10. this.ruleProperty = ruleProperty;
  11. this.dataProperty = dataProperty || ruleProperty;
  12. }
  13. /**
  14. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  15. * @returns {void}
  16. */
  17. apply(ruleSetCompiler) {
  18. const { ruleProperty, dataProperty } = this;
  19. ruleSetCompiler.hooks.rule.tap(
  20. "ObjectMatcherRulePlugin",
  21. (path, rule, unhandledProperties, result) => {
  22. if (unhandledProperties.has(ruleProperty)) {
  23. unhandledProperties.delete(ruleProperty);
  24. const value = rule[ruleProperty];
  25. for (const property of Object.keys(value)) {
  26. const nestedDataProperties = property.split(".");
  27. const condition = ruleSetCompiler.compileCondition(
  28. `${path}.${ruleProperty}.${property}`,
  29. value[property]
  30. );
  31. result.conditions.push({
  32. property: [dataProperty, ...nestedDataProperties],
  33. matchWhenEmpty: condition.matchWhenEmpty,
  34. fn: condition.fn
  35. });
  36. }
  37. }
  38. }
  39. );
  40. }
  41. }
  42. module.exports = ObjectMatcherRulePlugin;