filter respone api

This commit is contained in:
Sergey Yarkov 2019-11-19 23:20:05 +03:00
parent 7cd582f168
commit e275d6e3be
10 changed files with 103 additions and 31 deletions

View File

@ -45,6 +45,20 @@ function getItemsRoute(req, res, db) {
res.send('Товары в этой категории не найдены или такой категории нет') res.send('Товары в этой категории не найдены или такой категории нет')
} }
}) })
} else if (!req.query.option && req.query.sortByAll === 'ascending') {
dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err;
const items = result[0].items;
Object.values(items).forEach(arr => arr.sort((a, b) => a.price - b.price)) // фильтр по возрастанию
res.send(items);
});
} else if (!req.query.option && req.query.sortByAll === 'descending') {
dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err;
const items = result[0].items;
Object.values(items).forEach(arr => arr.sort((a, b) => a.price + b.price)) // фильтр по убыванию
res.send(items);
})
} else { } else {
res.send('Запрос неверный'); res.send('Запрос неверный');
} }

File diff suppressed because one or more lines are too long

View File

@ -63,10 +63,10 @@ main.main-section
.category-items .category-items
ul ul
li li
a.active(href='#' data-category='all') Все товары: a#catLi.active(href='#' data-category='all') Все товары:
each val in categories each val in categories
li li
a(href='#' data-category=val) #{val} a#catLi(href='#' data-category=val) #{val}
// Category Block END // Category Block END
// Filter Block // Filter Block
@ -78,7 +78,7 @@ main.main-section
h2.small-title Фильтровать товары: h2.small-title Фильтровать товары:
.filter-options .filter-options
form(action='#') form(action='#')
label label(data-sortBy='ascending')
input#ascending.with-gap(type='radio' name='filter') input#ascending.with-gap(type='radio' name='filter')
span Подешевле span Подешевле
label label

View File

@ -32,7 +32,7 @@ main.main-section
span #{count} шт span #{count} шт
p Цена за 1шт. p Цена за 1шт.
.product-info__price .product-info__price
span #{price} span #{price}₽
.product-info__right .product-info__right
.product-right__title .product-right__title
span Описание: span Описание:

View File

@ -14,14 +14,18 @@ export class CategoryComponent extends Component {
this.$el.addEventListener('click', buttonHandler.bind(this)); this.$el.addEventListener('click', buttonHandler.bind(this));
if (localStorage.getItem('category')) { if (localStorage.getItem('category')) {
const category = localStorage.getItem('category'); localStorage.removeItem('sortByAll', 'true'); // установка значения для компонента Filter
const bounded = breadcrumbActiveLink.bind(this);
const category = localStorage.getItem('category'),
bounded = breadcrumbActiveLink.bind(this);
document.querySelector('#loader').classList.add('hide'); document.querySelector('#loader').classList.add('hide');
bounded(category); bounded(category); // <- ф-я окраски li по нажатию на breadcrumb
// отображем данные если был нажат breadcrumb // отображем данные если был нажат breadcrumb
(async function(){ (async function(){
const fData = await apiService.getItemsOne(category); const fData = await apiService.getItemsOne(category),
const html = renderItemsOne(category, fData); html = renderItemsOne(category, fData);
document.querySelector('#roster').insertAdjacentHTML('afterbegin', html); document.querySelector('#roster').insertAdjacentHTML('afterbegin', html);
}()) }())
@ -35,38 +39,41 @@ export class CategoryComponent extends Component {
async function buttonHandler(e) { async function buttonHandler(e) {
e.preventDefault(); e.preventDefault();
if (e.target.dataset.category && e.target.dataset.category != 'all') { if (e.target.dataset.category && e.target.dataset.category != 'all') {
localStorage.removeItem('sortByAll'); // установка значения для компонента Filter
this.items.onShow(); this.items.onShow();
btnActiveLink(e); btnActiveLink(e);
const category = e.target.dataset.category.toLowerCase(); const category = e.target.dataset.category.toLowerCase(),
const fData = await apiService.getItemsOne(category); fData = await apiService.getItemsOne(category),
const html = renderItemsOne(category, fData); html = renderItemsOne(category, fData);
this.items.onHide(); this.items.onHide();
document.querySelector('#roster').insertAdjacentHTML('afterbegin', html); document.querySelector('#roster').insertAdjacentHTML('afterbegin', html);
} else if (e.target.dataset.category === 'all') { } else if (e.target.dataset.category === 'all') {
localStorage.setItem('sortByAll', 'true'); // установка значения для компонента Filter
this.items.onShow(); this.items.onShow();
btnActiveLink(e); btnActiveLink(e);
const fData = await apiService.getItems(), const fData = await apiService.getItems(),
categories = Object.keys(fData); categories = Object.keys(fData),
html = renderItems(categories, fData);
const html = renderItems(categories, fData);
this.items.onHide(); this.items.onHide();
document.querySelector('#roster').insertAdjacentHTML('afterbegin', html); document.querySelector('#roster').insertAdjacentHTML('afterbegin', html);
} }
} }
// Окраска li по нажатию
function btnActiveLink(e) { function btnActiveLink(e) {
Array.from(e.target.parentNode.parentNode.querySelectorAll('li a')).forEach(li => li.classList.remove('active')); Array.from(e.target.parentNode.parentNode.querySelectorAll('#catLi')).forEach(li => li.classList.remove('active'));
e.target.classList.add('active'); e.target.classList.add('active');
} }
// Окраска li по нажатию на breadcrumb
function breadcrumbActiveLink(category) { function breadcrumbActiveLink(category) {
const links = this.$el.querySelectorAll('.category-items ul li a'); const links = this.$el.querySelectorAll('#catLi');
Array.from(links).forEach(li => li.classList.remove('active')); Array.from(links).forEach(li => li.classList.remove('active'));
Array.from(links).forEach(li => { Array.from(links).forEach(li => li.dataset.category.toLowerCase() === category ? li.classList.add('active') : false);
if (li.dataset.category.toLowerCase() === category) {
li.classList.add('active');
}
});
} }

View File

@ -0,0 +1,32 @@
import { Component } from "../core/component";
export class FilterComponent extends Component {
constructor(id) {
super(id);
}
init() {
if (this.$el) {
this.$el.addEventListener('click', sortByAllHandler.bind(this));
this.$el.addEventListener('click', sortByOneHandler.bind(this));
}
}
}
function sortByAllHandler(e) {
if (localStorage.getItem('sortByAll')) {
if (e.target.id) {
const sortBy = e.target.id;
console.log(sortBy, 'By all');
}
}
}
function sortByOneHandler(e) {
if (!localStorage.getItem('sortByAll')) {
if (e.target.id) {
const sortBy = e.target.id;
console.log(sortBy, 'By one');
}
}
}

View File

@ -9,18 +9,23 @@ export class ItemsComponent extends Component {
} }
async init() { async init() {
if (this.$el) { if (this.$el) {
localStorage.setItem('sortByAll', 'true'); // установка значения для компонента Filter
if (!localStorage.getItem('category')) { if (!localStorage.getItem('category')) {
const roster = this.$el.querySelector('#roster'); // Список с товарами
// Получаем все товары и вывоим их если нету ключа category в ls
const fData = await apiService.getItems(), const fData = await apiService.getItems(),
categories = Object.keys(fData); categories = Object.keys(fData);
if (categories.length) { if (categories.length) {
const html = renderItems(categories, fData); const html = renderItems(categories, fData);
this.$el.querySelector('#roster').insertAdjacentHTML('afterbegin', html); roster.insertAdjacentHTML('afterbegin', html);
} else { } else {
this.$el.querySelector('#roster').innerHTML = 'Товаров на сайте пока что нету'; roster.innerHTML = 'Товаров на сайте пока что нету';
} }
// Убираем крутящийся лоадер
this.loader.hide(); this.loader.hide();
} }
} }

View File

@ -5,6 +5,7 @@ import { LoaderComponent } from "./components/loader.component.js";
import { ItemsComponent } from "./components/items.component.js"; import { ItemsComponent } from "./components/items.component.js";
import { CategoryComponent } from "./components/category.component.js"; import { CategoryComponent } from "./components/category.component.js";
import { BreadcrumbComponent } from "./components/breadcrumb.component.js"; import { BreadcrumbComponent } from "./components/breadcrumb.component.js";
import { FilterComponent } from "./components/filter.component.js";
const header = new HeaderComponent('header'); const header = new HeaderComponent('header');
const loader = new LoaderComponent('loader'); const loader = new LoaderComponent('loader');
@ -12,4 +13,5 @@ const information = new InformationComponent('information');
const cart = new CartComponent('cart'); const cart = new CartComponent('cart');
const items = new ItemsComponent('items', {loader}); const items = new ItemsComponent('items', {loader});
const category = new CategoryComponent('category', {items}); const category = new CategoryComponent('category', {items});
const filter = new FilterComponent('filter');
const breadcumb = new BreadcrumbComponent('breadcrumb'); const breadcumb = new BreadcrumbComponent('breadcrumb');

View File

@ -26,7 +26,7 @@ export function renderItems(categories, items) {
<span>Цена за 1 шт.</span> <span>Цена за 1 шт.</span>
</div> </div>
<div class="list-price"> <div class="list-price">
<span>${item.price}</span> <span>${item.price}₽</span>
</div> </div>
<div class="list-buttons"> <div class="list-buttons">
<button class="btn-small waves-effect waves-light">Купить</button> <button class="btn-small waves-effect waves-light">Купить</button>

View File

@ -25,7 +25,7 @@ export function renderItemsOne(category, items) {
<span>Цена за 1 шт.</span> <span>Цена за 1 шт.</span>
</div> </div>
<div class="list-price"> <div class="list-price">
<span>${item.price}</span> <span>${item.price}₽</span>
</div> </div>
<div class="list-buttons"> <div class="list-buttons">
<button class="btn-small waves-effect waves-light">Купить</button> <button class="btn-small waves-effect waves-light">Купить</button>