UNPKG

@shopgate/pwa-common-commerce

Version:

Commerce library for the Shopgate Connect PWA.

9 lines 2.48 kB
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}import PipelineRequest from'@shopgate/pwa-core/classes/PipelineRequest';import configuration from'@shopgate/pwa-common/collections/Configuration';import{DEFAULT_PRODUCTS_FETCH_PARAMS}from'@shopgate/pwa-common/constants/Configuration';import{shouldFetchData,mutable}from'@shopgate/pwa-common/helpers/redux';import{LoadingProvider}from'@shopgate/pwa-common/providers';import{getCurrentPathname}from'@shopgate/pwa-common/selectors/router';import{SHOPGATE_CATALOG_GET_PRODUCT}from"../constants/Pipelines";import requestProduct from"../action-creators/requestProduct";import receiveProduct from"../action-creators/receiveProduct";import errorProduct from"../action-creators/errorProduct";import receiveProductCached from"../action-creators/receiveProductCached";import{getProductById}from"../selectors/product";/** * Retrieves a product from the Redux store. * @param {string} productId The product ID. * @param {boolean} forceFetch Skips shouldFetchData check. Always fetches. * @return {Function} A redux thunk. */function fetchProduct(productId){var forceFetch=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return function(dispatch,getState){var state=getState();var product=getProductById(state,{productId:productId});if(!forceFetch&&!shouldFetchData(product)){if(product.productData){/* This timeout is needed here to make sure receivedVisibleProduct$ comes after productWillEnter$. Otherwise productIsReady$ is not working correctly. */setTimeout(function(){dispatch(receiveProductCached(product.productData));},0);}return undefined;}var path=getCurrentPathname(state);LoadingProvider.setLoading(path);var requestParams=_extends({},configuration.get(DEFAULT_PRODUCTS_FETCH_PARAMS),{productId:productId});dispatch(requestProduct(productId,forceFetch));var request=new PipelineRequest(SHOPGATE_CATALOG_GET_PRODUCT).setInput(requestParams).dispatch();request.then(function(result){LoadingProvider.unsetLoading(path);dispatch(receiveProduct(productId,result));})["catch"](function(error){LoadingProvider.unsetLoading(path);dispatch(errorProduct(productId,error.code));});return request;};}/** @mixes {MutableFunction} */export default mutable(fetchProduct);