Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nasriyasoftware
Last active October 10, 2021 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasriyasoftware/34c5fac1d5fff52f0a7dc1f5f90705aa to your computer and use it in GitHub Desktop.
Save nasriyasoftware/34c5fac1d5fff52f0a7dc1f5f90705aa to your computer and use it in GitHub Desktop.
Tutorial: Conditional Data Filtering
/* ====================================================================================================
========================================== Frontend Code ===========================================
====================================================================================================
*/
import wixData from 'wix-data';
import { getCollections, search, test } from 'backend/store.jsw';
$w.onReady(() => {
$w('#searchBarDataset').onInput(() => filterDataset());
$w('#sortDataset').onChange(() => filterDataset());
// Data binding Section
getCollections().then(async(collections) => {
$w('#collections, #collectionsDataset').options = collections;
$w('#collections, #collectionsDataset').selectedIndex = 0;
await searchProducts();
})
$w('#rep').onItemReady(($product, product) => {
if (product.mainMedia) { $product('#productImage').src = product.mainMedia }
$product('#productImage').alt = product.name;
$product('#productImage').tooltip = product.name;
$product('#productImage').target = '_blank';
$product('#productImage').link = product.productPageUrl;
$product('#productImage').fitMode = 'fit';
if (product.name.length > 50) {
$product('#name').text = `${product.name.substr(0, 50)}...`;
} else {
$product('#name').text = product.name;
}
if (product.discountedPrice < product.price) {
$product('#price').text = `${product.formattedDiscountedPrice} instead of ${product.formattedPrice}`;
} else {
$product('#price').text = product.formattedPrice
}
if (product.inStock) {
if (product.trackInventory) {
$product('#inStock').text = `${product.quantityInStock} items in stock!`
} else {
$product('#inStock').text = 'In Stock';
}
} else { $product('#inStock').text = 'Out of Stock!' }
if (product.sku) { $product('#sku').text = product.sku } else {
if (product.manageVariants) { $product('#sku').text = 'Vary!' }
}
})
$w('#searchBar').onInput(() => searchProducts());
$w('#collections, #sort, #onlyInStock').onChange(() => searchProducts())
})
async function searchProducts() {
$w('#rep').data = [];
if (!$w('#message').collapsed) { $w('#message').collapse() }
let request = {
search: $w('#searchBar').value || '',
collection: $w('#collections').value || 'All Products',
sort: $w('#sort').value,
onlyInStock: $w('#onlyInStock').checked
}
await search(request).then((results) => {
if (results.length > 0) {
$w('#rep').data = results;
} else {
$w('#message').text = 'No matching results found!';
$w('#message').expand();
}
}).catch(err => {
console.error(err);
$w('#message').text = `An Error Occurred! - Error message: ${err}`;
$w('#message').expand();
})
}
function filterDataset() {
let filter = wixData.filter();
let sort = wixData.sort();
let searchValue = $w('#searchBarDataset').value;
let sortValue = $w('#sortDataset').value;
if (searchValue.length > 0) { filter = filter.contains('name', searchValue).or(filter.eq('sku', searchValue)) }
switch (sortValue) {
case 'a-z':
// Sort the products by their name: A - Z
sort = sort.ascending('name');
break;
case 'z-a':
// Sort the products by their name: Z - A
sort = sort.descending('name');
break;
case 'priceAse':
sort = sort.ascending('price');
break;
case 'priceDse':
sort = sort.descending('price');
break;
}
$w('#ds').setFilter(filter).then(() => $w('#ds').setSort(sort));
}
/* ====================================================================================================
========================================== Backend Code ============================================
====================================================================================================
*/
// Backend module: store.jsw
import wixData from 'wix-data';
export function search(request) {
let query = wixData.query('Stores/Products')
if (request.collection !== 'All Products') { query = query.hasSome('collections', request.collection); }
if (request.search.length > 0) { query = query.contains('name', request.search).or(query.eq('sku', request.search)) }
switch (request.sort) {
case 'a-z':
// Sort the products by their name: A - Z
query = query.ascending('name');
break;
case 'z-a':
// Sort the products by their name: Z - A
query = query.descending('name');
break;
case 'priceAse':
query = query.ascending('price');
break;
case 'priceDse':
query = query.descending('price');
break;
}
return query.find().then((results) => {
if (results.length > 0) {
if (request.onlyInStock) {
let items = [];
results.items.forEach(product => {
if (product.inStock) { items.push(product) }
})
if (items.length > 0) {
return Promise.resolve(items);
} else {
return Promise.resolve([]);
}
} else {
return Promise.resolve(results.items);
}
} else {
return Promise.resolve([])
}
}).catch(err => {
return Promise.reject(err);
})
}
export function getCollections() {
return wixData.query('Stores/Collections').limit(100).find().then((results) => {
let collections = [];
results.items.forEach(collection => {
collections.push({ label: collection.name, value: collection.name })
})
return collections;
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment