@shopgate/engage
Version:
Shopgate's ENGAGE library.
34 lines • 2.71 kB
JavaScript
import{createSelector}from'reselect';import{getProductState,generateProductRelationsHash,getProducts}from'@shopgate/pwa-common-commerce/product';var getProductRelationsState=createSelector(getProductState,function(product){return product.productRelationsByHash;});/**
* Creates the selector that retrieves the product relations for the current product ID.
* @returns {Function}
*/function makeGetProductRelations(){/**
* Retrieves the product relations for the current product ID.
* @param {Object} state The application state.
* @param {Object} props The component props.
* @param {string} props.productId The product ID.
* @param {string} props.type The relation type.
* @param {number} limit The query limit.
* @returns {Array}
*/return createSelector(getProductRelationsState,function(_,props){return generateProductRelationsHash(props);},function(relationsState,hash){if(relationsState[hash]){return relationsState[hash].productIds;}return[];});}/**
* Creates the selector that retrieves the related products for the current product ID.
* @returns {Function}
*/export function makeGetRelatedProducts(){var getProductRelations=makeGetProductRelations();/**
* Retrieves the related products for the current product ID.
* @param {Object} state The application state.
* @param {Object} props The component props.
* @param {string} props.productId The product ID.
* @param {string} props.type The relation type.
* @param {number} limit The query limit.
* @returns {Array}
*/return createSelector(getProductRelations,getProducts,function(){var relations=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var products=arguments.length>1?arguments[1]:undefined;return relations.filter(function(id){return products[id]&&products[id].productData;}).map(function(id){return products[id].productData;});});}/**
* Creates the selector that retrieves a limited set of related products for the current product ID.
* @returns {Function}
*/export function makeGetMaximumRelatedProducts(){var getRelatedProducts=makeGetRelatedProducts();/**
* Retrieves a limit set of related products for the current product ID.
* @param {Object} state The application state.
* @param {Object} props The component props.
* @param {string} props.productId The product ID.
* @param {string} props.type The relation type.
* @param {number} limit The query limit.
* @returns {Array}
*/return createSelector(getRelatedProducts,function(_,props){return props.max||null;},function(products,max){if(!max||products.length<max){return{products:products,productsCount:products.length};}return{products:products.slice(0,max),productsCount:products.length};});}