ObjectMatcherRulePlugin.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. /** @typedef {import("./RuleSetCompiler").RuleConditionFunction} RuleConditionFunction */
  9. class ObjectMatcherRulePlugin {
  10. /**
  11. * @param {string} ruleProperty the rule property
  12. * @param {string=} dataProperty the data property
  13. * @param {RuleConditionFunction=} additionalConditionFunction need to check
  14. */
  15. constructor(ruleProperty, dataProperty, additionalConditionFunction) {
  16. this.ruleProperty = ruleProperty;
  17. this.dataProperty = dataProperty || ruleProperty;
  18. this.additionalConditionFunction = additionalConditionFunction;
  19. }
  20. /**
  21. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  22. * @returns {void}
  23. */
  24. apply(ruleSetCompiler) {
  25. const { ruleProperty, dataProperty } = this;
  26. ruleSetCompiler.hooks.rule.tap(
  27. "ObjectMatcherRulePlugin",
  28. (path, rule, unhandledProperties, result) => {
  29. if (unhandledProperties.has(ruleProperty)) {
  30. unhandledProperties.delete(ruleProperty);
  31. const value = rule[ruleProperty];
  32. for (const property of Object.keys(value)) {
  33. const nestedDataProperties = property.split(".");
  34. const condition = ruleSetCompiler.compileCondition(
  35. `${path}.${ruleProperty}.${property}`,
  36. value[property]
  37. );
  38. if (this.additionalConditionFunction) {
  39. result.conditions.push({
  40. property: [dataProperty],
  41. matchWhenEmpty: condition.matchWhenEmpty,
  42. fn: this.additionalConditionFunction
  43. });
  44. }
  45. result.conditions.push({
  46. property: [dataProperty, ...nestedDataProperties],
  47. matchWhenEmpty: condition.matchWhenEmpty,
  48. fn: condition.fn
  49. });
  50. }
  51. }
  52. }
  53. );
  54. }
  55. }
  56. module.exports = ObjectMatcherRulePlugin;