Filter by ascending and descending of price

This commit is contained in:
Sergey Yarkov 2019-11-20 23:09:10 +03:00
parent e275d6e3be
commit d6207e7dde
8 changed files with 89 additions and 36 deletions

View File

@ -20,21 +20,30 @@ function indexRoute(req, res, db) {
function getItemsRoute(req, res, db) { function getItemsRoute(req, res, db) {
const dbo = db.db(dbName); const dbo = db.db(dbName);
const queryOptions = {
auth: 'yYNfW8ynVO18L1TW5qIkILM1WtWgrVZz',
option: 'all'
}
// установка кэша при отдачи json данных // установка кэша при отдачи json данных
//res.setHeader("Cache-Control", "public, max-age=20"); //res.setHeader("Cache-Control", "public, max-age=20");
if (req.query.auth === queryOptions.auth) { if (req.query.auth === 'yYNfW8ynVO18L1TW5qIkILM1WtWgrVZz') {
if (req.query.option === queryOptions.option) { if (req.query.option === 'all' && !req.query.sorting) {
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
res.send(result[0].items); res.send(result[0].items);
}) })
} else if (!req.query.option && req.query.category && req.query.sorting === 'ascending') {
dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err;
const items = result[0].items[req.query.category];
items.sort((a, b) => a.price - b.price) // фильтр по возрастанию по цене
res.send(items);
});
} else if (!req.query.option && req.query.category && req.query.sorting === 'descending') {
dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err;
const items = result[0].items[req.query.category];
items.sort((a, b) => b.price - a.price) // фильтр по убыванию по цене
res.send(items);
});
} else if (!req.query.option && req.query.category) { } else if (!req.query.option && req.query.category) {
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
@ -45,18 +54,18 @@ function getItemsRoute(req, res, db) {
res.send('Товары в этой категории не найдены или такой категории нет') res.send('Товары в этой категории не найдены или такой категории нет')
} }
}) })
} else if (!req.query.option && req.query.sortByAll === 'ascending') { } else if (req.query.option && req.query.sorting === 'ascending') {
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
const items = result[0].items; const items = result[0].items;
Object.values(items).forEach(arr => arr.sort((a, b) => a.price - b.price)) // фильтр по возрастанию Object.values(items).forEach(arr => arr.sort((a, b) => a.price - b.price)) // фильтр по возрастанию по цене
res.send(items); res.send(items);
}); });
} else if (!req.query.option && req.query.sortByAll === 'descending') { } else if (req.query.option && req.query.sorting === 'descending') {
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
const items = result[0].items; const items = result[0].items;
Object.values(items).forEach(arr => arr.sort((a, b) => a.price + b.price)) // фильтр по убыванию Object.values(items).forEach(arr => arr.sort((a, b) => b.price - a.price)) // фильтр по убыванию по цене
res.send(items); res.send(items);
}) })
} else { } else {

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48px" height="48px"><path fill="#7b1fa2" d="M6,10c0-2.209,1.791-4,4-4h28c2.209,0,4,1.791,4,4v28c0,2.209-1.791,4-4,4H10c-2.209,0-4-1.791-4-4 V10z"/><path fill="#fff" d="M36 19L37 13 30.84 13 31.44 10 17 10 17 13 11 13 12 20 11 35 17 33.2 17 38.44 26 36.64 26 32.334 36.967 33.068z"/><path fill="#7b1fa2" d="M19 12L19 36 24 35 24 26 28 26 28 21 24 21 24 17 28 17 29 12z"/></svg>

After

Width:  |  Height:  |  Size: 443 B

File diff suppressed because one or more lines are too long

View File

@ -102,7 +102,7 @@ main.main-section
#loader.progress #loader.progress
.indeterminate(style="width: 40%") .indeterminate(style="width: 40%")
#roster #roster
#pagination.items-pagination #pagination.items-pagination.hide
.divider .divider
ul.pagination ul.pagination
li.disabled li.disabled

View File

@ -4,9 +4,10 @@ import { renderItemsOne } from "../templates/itemsOne.template";
import { renderItems } from "../templates/items.template"; import { renderItems } from "../templates/items.template";
export class CategoryComponent extends Component { export class CategoryComponent extends Component {
constructor(id, {items}) { constructor(id, {items}, {filter}) {
super(id); super(id);
this.items = items; this.items = items;
this.filter = filter;
} }
init() { init() {
@ -41,6 +42,7 @@ async function buttonHandler(e) {
if (e.target.dataset.category && e.target.dataset.category != 'all') { if (e.target.dataset.category && e.target.dataset.category != 'all') {
localStorage.removeItem('sortByAll'); // установка значения для компонента Filter localStorage.removeItem('sortByAll'); // установка значения для компонента Filter
this.filter.clearChecked();
this.items.onShow(); this.items.onShow();
btnActiveLink(e); btnActiveLink(e);
@ -53,6 +55,7 @@ async function buttonHandler(e) {
} else if (e.target.dataset.category === 'all') { } else if (e.target.dataset.category === 'all') {
localStorage.setItem('sortByAll', 'true'); // установка значения для компонента Filter localStorage.setItem('sortByAll', 'true'); // установка значения для компонента Filter
this.filter.clearChecked();
this.items.onShow(); this.items.onShow();
btnActiveLink(e); btnActiveLink(e);
@ -69,6 +72,7 @@ async function buttonHandler(e) {
function btnActiveLink(e) { function btnActiveLink(e) {
Array.from(e.target.parentNode.parentNode.querySelectorAll('#catLi')).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');
localStorage.setItem('currentCategory', e.target.dataset.category.toLowerCase());
} }
// Окраска li по нажатию на breadcrumb // Окраска li по нажатию на breadcrumb
@ -76,4 +80,5 @@ function breadcrumbActiveLink(category) {
const links = this.$el.querySelectorAll('#catLi'); 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 => li.dataset.category.toLowerCase() === category ? li.classList.add('active') : false); Array.from(links).forEach(li => li.dataset.category.toLowerCase() === category ? li.classList.add('active') : false);
Array.from(links).forEach(li => li.dataset.category.toLowerCase() === category ? localStorage.setItem('currentCategory', li.dataset.category.toLowerCase()) : false);
} }

View File

@ -1,8 +1,12 @@
import { Component } from "../core/component"; import { Component } from "../core/component";
import { apiService } from "../services/api.service";
import { renderItems } from "../templates/items.template";
import { renderItemsOne } from "../templates/itemsOne.template";
export class FilterComponent extends Component { export class FilterComponent extends Component {
constructor(id) { constructor(id, {items}) {
super(id); super(id);
this.items = items;
} }
init() { init() {
@ -11,22 +15,45 @@ export class FilterComponent extends Component {
this.$el.addEventListener('click', sortByOneHandler.bind(this)); this.$el.addEventListener('click', sortByOneHandler.bind(this));
} }
} }
clearChecked() {
if (this.$el) {
const options = this.$el.querySelectorAll('.filter-options form input');
Array.from(options).forEach(option => option.checked = false);
}
}
} }
function sortByAllHandler(e) { async function sortByAllHandler(e) {
if (localStorage.getItem('sortByAll')) { if (localStorage.getItem('sortByAll')) {
if (e.target.id) { if (e.target.id) {
const sortBy = e.target.id; const sorting = e.target.id;
console.log(sortBy, 'By all');
this.items.onShow();
const fData = await apiService.getItems(sorting),
categories = Object.keys(fData),
html = renderItems(categories, fData);
this.items.onHide();
document.querySelector('#roster').insertAdjacentHTML('afterbegin', html);
} }
} }
} }
function sortByOneHandler(e) { async function sortByOneHandler(e) {
if (!localStorage.getItem('sortByAll')) { if (!localStorage.getItem('sortByAll')) {
if (e.target.id) { if (e.target.id) {
const sortBy = e.target.id; const sorting = e.target.id;
console.log(sortBy, 'By one');
this.items.onShow();
const category = localStorage.getItem('currentCategory'),
fData = await apiService.getItemsOne(category, sorting),
html = renderItemsOne(category, fData);
this.items.onHide();
document.querySelector('#roster').insertAdjacentHTML('afterbegin', html);
} }
} }
} }

View File

@ -12,6 +12,6 @@ const loader = new LoaderComponent('loader');
const information = new InformationComponent('information'); 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 filter = new FilterComponent('filter', {items});
const filter = new FilterComponent('filter'); const category = new CategoryComponent('category', {items}, {filter});
const breadcumb = new BreadcrumbComponent('breadcrumb'); const breadcumb = new BreadcrumbComponent('breadcrumb');

View File

@ -6,19 +6,30 @@ class ApiService {
this.url = baseUrl; this.url = baseUrl;
} }
async getItems() { async getItems(sorting) {
try { try {
if (sorting) {
const request = `${this.url}store-api?auth=${API_TOKEN}&option=all&sorting=${sorting}`;
return useRequest(request);
} else {
const request = `${this.url}store-api?auth=${API_TOKEN}&option=all`; const request = `${this.url}store-api?auth=${API_TOKEN}&option=all`;
return useRequest(request); return useRequest(request);
}
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
} }
async getItemsOne(category) { async getItemsOne(category, sorting) {
try { try {
if (sorting) {
const request = `${this.url}store-api?auth=${API_TOKEN}&category=${category}&sorting=${sorting}`;
return useRequest(request);
} else {
const request = `${this.url}store-api?auth=${API_TOKEN}&category=${category}`; const request = `${this.url}store-api?auth=${API_TOKEN}&category=${category}`;
return useRequest(request); return useRequest(request);
}
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }