0;
},
getCacheStorage(cacheKey) {
const storage = JSON.parse(hyva.getBrowserStorage().getItem(localStorageNamespace)) || {};
return storage[cacheKey] || null;
},
saveCacheStorage(products) {
let storage = JSON.parse(hyva.getBrowserStorage().getItem(localStorageNamespace)) || {};
storage = this.enforceLocalStorageLimits(storage);
storage[this.getCacheKey()] = {
'product_list': products,
'added_at': new Date().getTime()
};
hyva.getBrowserStorage().setItem(localStorageNamespace, JSON.stringify(storage));
},
getProductsFromCache() {
const products = this.getCacheStorage(this.getCacheKey());
if (products !== null && this.validateCacheLifetime(products)) {
return products.product_list;
}
return null;
},
loadProductsFromServer() {
if (this.isLoading) {
return;
}
this.isLoading = true;
return fetch(this.ajaxData.url + '?' + this.buildQueryString(this.ajaxData.originalRequest), {
'headers': {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
'method': 'GET'
})
.then(response => response.json())
.then(data => {
if (!data.status) {
this.saveCacheStorage([]);
return;
}
this.products = Object.values(data.productList);
this.saveCacheStorage(data.productList);
window.dispatchEvent(new CustomEvent('also-bough-products-loaded'));
})
.catch(function (error) {
typeof window.dispatchMessages !== 'undefined' && window.dispatchMessages(
[{
type: 'error',
text: error
}], 5000
);
}).finally(() => this.isLoading = false);
},
validateCacheLifetime(products) {
return new Date().getTime() - products.added_at < this.ajaxData.cache_lifetime * 1000;
},
getCacheKey() {
const originalRequest = this.ajaxData.originalRequest;
return originalRequest.action + '_' + originalRequest.entity_id;
},
buildQueryString(params) {
const queryStringArray = [];
for (const key in params) {
if (params.hasOwnProperty(key)) {
const value = params[key];
if (Array.isArray(value)) {
value.forEach((item, index) => {
queryStringArray.push(this.buildQueryString({ [key + '[' + index + ']']: item }));
});
} else if (typeof value === 'object' && value !== null) {
queryStringArray.push(this.buildQueryString(value));
} else {
queryStringArray.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
}
}
return queryStringArray.join('&');
},
enforceLocalStorageLimits(storage) {
if (Object.keys(storage).length >= localStorageLimit) {
const newStorage = Object.entries(storage);
newStorage.sort((a, b) => new Date(b[1].added_at) - new Date(a[1].added_at));
return Object.fromEntries(newStorage.slice(0, localStorageLimit - 1))
}
return storage;
}
}
}
Customers who bought this item also bought