Cart API
;window.CartService = (function(APIService, CONSTANTS, Cart, errorHandler){
var cart = new Cart();
var loaded = false;
function CartService(){
this.url = CONSTANTS.CART.URL;
this.headers = {
'Content-Type': 'application/json'
};
APIService.apply(this, arguments);
}
Object.assign(CartService.prototype, APIService.prototype, CartService);
Object.defineProperty(CartService.prototype, 'data', {
get: function(){
var req = {
method: 'getFullCart'
};
if(!loaded){
return this.post(req, function(res){
loaded = res.success;
cart = new Cart(res.data);
return cart;
}, function(res){
errorHandler(res.error);
});
}
return cart;
},
set: function(data){
var req = Object.assign({"method": "addToCart"}, data);
// return this.post(req, function(res){
// if (res.success) {
cart = new Cart(data);
return cart;
// }
// });
}
});
CartService.prototype.addToCart = function(product){
var req = Object.assign({"method": "addToCart"}, product);
return this.post(req, function(res){
if (res.success) {
cart.products = new Cart(data);
}
});
}
return CartService;
}(window.APIService, window.API, window.Cart, console.error));
;window.Cart = (function(){
/**
* @typedef Cart
* @property {Number} items
* @property {Number} sum
* @property {Number} oldSum
* @property {Number} weight
* @property {Number} discount
*/
var defaultCart = {
items: 0,
sum: 0,
oldSum: 0,
weight: 0,
discount: 0
};
/**
* @returns {Cart}
* @constructor
*/
function Cart(cart){
Object.assign(this, cart);
}
Object.assign(Cart.prototype, defaultCart);
return Cart;
}());
;window.APIService = (function(_){
function ajax(headers, url, method, data, onsuccess, onerror) {
var request = new XMLHttpRequest();
request.open(method, url, true);
_.forEach(headers, function(v, k){
request.setRequestHeader(k, v);
});
request.onsuccess = onsuccess || function(){};
request.onerror = onerror || function(){};
request.onload = function() {
try {
var data = JSON.parse(request.responseText);
} catch (e){
return this.onerror({
success: false,
error: e.message
});
}
if (request.status >= 200 && request.status < 400) {
this.onsuccess(data);
} else {
this.onerror(data);
}
};
request.send(JSON.stringify(data));
return request;
}
function APIService(options){
Object.assign(this, options);
this.ajax = ajax.bind(this, this.headers, this.url);
this.get = this.ajax.bind(this, 'GET');
this.post = this.ajax.bind(this, 'POST');
}
return APIService;
}(_));