From deadff52ecd465e4aa34ff0e8f0c2460680e86ef Mon Sep 17 00:00:00 2001 From: tedraykov Date: Sun, 20 Feb 2022 15:06:05 +0200 Subject: [PATCH] feat: support nested accessor for order attributes restriction Signed-off-by: tedraykov --- .../orderMatchesOrderAttributesRestriction.js | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/util/orderMatchesOrderAttributesRestriction.js b/src/util/orderMatchesOrderAttributesRestriction.js index 61e36b6..6c58094 100644 --- a/src/util/orderMatchesOrderAttributesRestriction.js +++ b/src/util/orderMatchesOrderAttributesRestriction.js @@ -1,6 +1,36 @@ import operators from "@reactioncommerce/api-utils/operators.js"; import propertyTypes from "@reactioncommerce/api-utils/propertyTypes.js"; +/** + * @summary Access nested object property providing accessor with "." separator + * Example: + * const object = { + * property: { + * value: 10 + * } + * } + * getNestedProperty(object, "property.value") // Outputs: 10 + * @param {Object} object - the object + * @param {Object} propertyAccessorString - property accessor with "." separator + * @returns {Object | undefined} - the property of the object + */ +function getNestedProperty(object, propertyAccessorString) { + if (!propertyAccessorString) return object; + + const propertyAccessors = propertyAccessorString.split("."); + let resultObjectProperty = object; + + for (const propertyAccessor of propertyAccessors) { + resultObjectProperty = resultObjectProperty[propertyAccessor]; + + if (resultObjectProperty === undefined) { + break; + } + } + + return resultObjectProperty; +} + /** * @summary Check whether an attribute of an order matches with a provided value based on a provided comparison operator * @param {Object} order - a common order @@ -8,8 +38,12 @@ import propertyTypes from "@reactioncommerce/api-utils/propertyTypes.js"; * @returns {boolean} true / false whether an order attribute matches a value */ function orderMatchesAttribute(order, { operator, property, propertyType, value }) { + const orderProperty = property.includes(".") ? + getNestedProperty(order, property) : + order[property]; + return operators[operator]( - order[property], + orderProperty, propertyTypes[propertyType](value) ); }