@shopgate/pwa-common-commerce
Version:
Commerce library for the Shopgate Connect PWA.
12 lines • 2.89 kB
JavaScript
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,PROCESS_SEQUENTIAL}from'@shopgate/pwa-core';import{mutable}from'@shopgate/pwa-common/helpers/redux';import{errorBehavior}from'@shopgate/engage/core';import{SHOPGATE_CART_ADD_COUPONS}from"../constants/Pipelines";import createPipelineErrorList from"../helpers/createPipelineErrorList";import{ECART}from"../constants/PipelineErrors";import addCoupons from"../action-creators/addCouponsToCart";import errorAddCouponsToCart from"../action-creators/errorAddCouponsToCart";import successAddCouponsToCart from"../action-creators/successAddCouponsToCart";import{messagesHaveErrors}from"../helpers";import setCouponFieldError from"../action-creators/setCouponFieldError";import{MESSAGE_TYPE_ERROR}from"../constants";/**
* Adds coupons to the cart. Returns a Promise because a component waits for this action to finish.
* @param {string[]} couponIds The IDs of the coupons that shall be added to the cart.
* @param {boolean} [userInteracted=true] Was the action dispatched due to a user interaction
* @return {Function} A redux thunk.
*/function addCouponsToCart(couponIds){var userInteracted=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return function(dispatch){dispatch(addCoupons(couponIds));var request=new PipelineRequest(SHOPGATE_CART_ADD_COUPONS).setInput({couponCodes:couponIds}).setResponseProcessed(PROCESS_SEQUENTIAL).setRetries(0).setErrorBlacklist(ECART).setResponseBehavior({error:userInteracted?errorBehavior.dispatchAction(function(message){return setCouponFieldError(message);}):errorBehavior.toast()}).dispatch();request.then(function(result){/**
* @deprecated: The property "messages" is not supposed to be part of the pipeline response.
* Specification demands errors to be returned as response object with an "error" property.
* This code snippet needs to be removed after fixing the `@shopgate/legacy-cart` extension.
*/if(result.messages&&messagesHaveErrors(result.messages)){// Simulate a pipeline response error with a proper ECART error.
var errors=result.messages.filter(function(msg){return msg.type===MESSAGE_TYPE_ERROR;});var error=_extends({},errors[0],{code:ECART,message:'',// Irrelevant in this case
errors:errors});dispatch(errorAddCouponsToCart(couponIds,createPipelineErrorList(SHOPGATE_CART_ADD_COUPONS,error)));return;}dispatch(successAddCouponsToCart(couponIds,userInteracted));})["catch"](function(error){dispatch(errorAddCouponsToCart(couponIds,createPipelineErrorList(SHOPGATE_CART_ADD_COUPONS,error)));});return request;};}/** @mixes {MutableFunction} */export default mutable(addCouponsToCart);