UNPKG

@shopgate/pwa-tracking

Version:

Tracking library for the Shopgate Connect PWA.

13 lines 2.88 kB
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import'rxjs/add/operator/switchMap';import'rxjs/add/observable/of';import'rxjs/add/observable/defer';import{Observable}from'rxjs/Observable';import{productsAdded$ as originalProductsAdded$}from'@shopgate/engage/cart/streams';import{getProductById,fetchProductsById}from'@shopgate/engage/product';/** * Emits when a product was added to the cart and product data is available */export var productsAdded$=originalProductsAdded$.switchMap(function(input){var getState=input.getState,action=input.action,dispatch=input.dispatch;var _action$products=action.products,products=_action$products===void 0?[]:_action$products;// Collect product ids from the add-to-cart action var productIds=products.map(function(_ref){var productId=_ref.productId;return productId;}).filter(Boolean);// Check if we have product data for all productIds var productDataAvailable=productIds.every(function(productId){return getProductById(getState(),{productId:productId});});if(productDataAvailable){// All product data for the tracking event is available - handover action data to subscribers return Observable.of(input);}/** * Incomplete product data can be caused by an add-to-cart push message. In that case the * product was never fetched before due to visiting PDP. So we need to fetch missing product * data first. * Subscribers will receive the original action when product data comes available. */return Observable.defer(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:result={products:[]};_context.prev=1;_context.next=4;return dispatch(fetchProductsById(productIds));case 4:result=_context.sent;_context.next=9;break;case 7:_context.prev=7;_context.t0=_context["catch"](1);case 9:return _context.abrupt("return",result);case 10:case"end":return _context.stop();}},_callee,null,[[1,7]]);}))).first()// do not proceed when request didn't return any products (no suitable tracking data) .filter(function(data){return Array.isArray(data.products)&&data.products.length>0;})// handover original action to subscribers .switchMap(function(){return Observable.of(input);});});