related itens

import wixData from 'wix-data';

import wixLocation from 'wix-location';

 

$w.onReady(function () {

loadRelatedProducts();

});

 

async function loadRelatedProducts() {

let product = await $w('#productPage1').getProduct();

let relatedProductResults = await Promise.all([

relatedProductsByTable(product),

]);

 

if (relatedProductResults[0].length > 0)

showRelatedProducts(relatedProductResults[0]);

else

showRelatedProducts(relatedProductResults[1]);

}

async function relatedProductsByTable(product) {

let productId = product._id;

 

// find related products by relation table

let relatedByTable = await Promise.all([

wixData.query('relatedProducts')

.eq('productA', productId)

.include('productB')

.include('productC')

.include('productD')

.include('productE')

.find(),

wixData.query('relatedProducts')

.eq('productB', productId)

.eq('productC', productId)

.eq('productD', productId)

.eq('productE', productId)

.include('productA')

.find()

]);

 

let relatedProducts = [

...relatedByTable[0].items.map(_ => _.productE),

...relatedByTable[0].items.map(_ => _.productD),

...relatedByTable[0].items.map(_ => _.productC),

...relatedByTable[0].items.map(_ => _.productB),

...relatedByTable[1].items.map(_ => _.productA)

];

return relatedProducts;

}

function showRelatedProducts(relatedProducts) {

if (relatedProducts.length > 0) {

relatedProducts.splice(4, relatedProducts.length);

$w('#relatedItemsRepeater').onItemReady(relatedItemReady);

$w("#relatedItemsRepeater").data = relatedProducts;

$w("#relatedItems").expand();

} else {

$w("#relatedItems").collapse();

}

}

function relatedItemReady($w, product) {

$w("#productImage").src = product.mainMedia;

$w("#productName").text = product.name;

$w("#productPrice").text = product.formattedPrice;

$w('#productImage').onClick(() => {

wixLocation.to(product.productPageUrl);

});

}