From c0b5fbec562c615adf2f1b5171b29abfc1bd253b Mon Sep 17 00:00:00 2001 From: Sergey Yarkov Date: Fri, 6 Dec 2019 18:35:57 +0300 Subject: [PATCH] checking on empty categories --- config/routes/routes.js | 42 ++++++++---- dist/public/js/bundle.js | 4 +- dist/views/index.pug | 2 +- src/components/information.component.js | 4 +- src/templates/items.template.js | 88 ++++++++++++++----------- 5 files changed, 86 insertions(+), 54 deletions(-) diff --git a/config/routes/routes.js b/config/routes/routes.js index a3bd065..e991c29 100644 --- a/config/routes/routes.js +++ b/config/routes/routes.js @@ -23,24 +23,34 @@ function getItemsRoute(req, res, dbo) { if (req.query.token === 'yYNfW8ynVO18L1TW5qIkILM1WtWgrVZz') { if (req.query.items === 'all' && !req.query.category && !req.query.sorting) { dbo.collection('items').find().toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Товаров в магазине пока что нет.'}); }); } else if (req.query.items === 'all' && req.query.sorting && !req.query.category) { if (req.query.sorting === 'ascending') { dbo.collection('items').find().sort({price: 1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.sorting === 'descending') { dbo.collection('items').find().sort({price: -1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.sorting === 'newer') { dbo.collection('items').find().sort({date: -1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.sorting === 'older') { dbo.collection('items').find().sort({date: 1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else { res.send('Введите параметр по убыванию или возрастанию.'); @@ -49,31 +59,41 @@ function getItemsRoute(req, res, dbo) { dbo.collection('items').find({category: req.query.category}).toArray((err, result) => { result.length > 0 ? res.send(result) - : res.send('Такой категории не существует или там нет товаров.'); + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.items === 'all' && req.query.category && req.query.sorting) { if (req.query.sorting === 'ascending') { dbo.collection('items').find({category: req.query.category}).sort({price: 1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.sorting === 'descending') { dbo.collection('items').find({category: req.query.category}).sort({price: -1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.sorting === 'newer') { dbo.collection('items').find({category: req.query.category}).sort({date: -1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else if (req.query.sorting === 'older') { dbo.collection('items').find({category: req.query.category}).sort({date: 1}).toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'Такой категории не существует или там нет товаров.'}); }); } else { res.send('Введите параметр по убыванию или возрастанию.'); } } else if (req.query.categories === 'all') { dbo.collection('categories').find().toArray((err, result) => { - res.send(result); + result.length > 0 + ? res.send(result) + : res.send({error: 'На сайте нету категорий'}); }); } else if (req.query.category) { dbo.collection('categories').find({title: req.query.category}).toArray((err, result) => { diff --git a/dist/public/js/bundle.js b/dist/public/js/bundle.js index 0e899ab..9da11c5 100644 --- a/dist/public/js/bundle.js +++ b/dist/public/js/bundle.js @@ -3930,7 +3930,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) * /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"InformationComponent\", function() { return InformationComponent; });\n/* harmony import */ var _core_component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/component */ \"./src/core/component.js\");\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\n\nvar InformationComponent =\n/*#__PURE__*/\nfunction (_Component) {\n _inherits(InformationComponent, _Component);\n\n function InformationComponent(id) {\n _classCallCheck(this, InformationComponent);\n\n return _possibleConstructorReturn(this, _getPrototypeOf(InformationComponent).call(this, id));\n }\n\n _createClass(InformationComponent, [{\n key: \"init\",\n value: function init() {\n if (this.$el) {\n if (localStorage.getItem('visited')) {\n this.hide();\n }\n\n var btn = this.$el.querySelector('#information-close');\n btn.addEventListener('click', buttonHandler.bind(this));\n }\n }\n }]);\n\n return InformationComponent;\n}(_core_component__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\nfunction buttonHandler() {\n localStorage.setItem('visited', JSON.stringify(true));\n this.hide();\n}\n\n//# sourceURL=webpack:///./src/components/information.component.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"InformationComponent\", function() { return InformationComponent; });\n/* harmony import */ var _core_component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/component */ \"./src/core/component.js\");\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\n\nvar InformationComponent =\n/*#__PURE__*/\nfunction (_Component) {\n _inherits(InformationComponent, _Component);\n\n function InformationComponent(id) {\n _classCallCheck(this, InformationComponent);\n\n return _possibleConstructorReturn(this, _getPrototypeOf(InformationComponent).call(this, id));\n }\n\n _createClass(InformationComponent, [{\n key: \"init\",\n value: function init() {\n if (this.$el) {\n if (!localStorage.getItem('visited')) {\n this.show();\n }\n\n var btn = this.$el.querySelector('#information-close');\n btn.addEventListener('click', buttonHandler.bind(this));\n }\n }\n }]);\n\n return InformationComponent;\n}(_core_component__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\nfunction buttonHandler() {\n localStorage.setItem('visited', JSON.stringify(true));\n this.hide();\n}\n\n//# sourceURL=webpack:///./src/components/information.component.js?"); /***/ }), @@ -4050,7 +4050,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) * /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"renderItems\", function() { return renderItems; });\nfunction renderItems(categories, items) {\n var arrayCategories = categories;\n var arrayItems = items;\n var html = '';\n arrayCategories.forEach(function (category) {\n html += \"
\\n

\".concat(category.title, \"

\\n
\");\n arrayItems.forEach(function (item) {\n if (item.category.toLowerCase() === category.title.toLowerCase()) {\n html += \"\\n
\\n
\\n
\\n \\\"#\\\"\\n
\\n \\n
\\n
\\n
\\n \").concat(diffDates(new Date(), new Date(item.date)), \"\\n
\\n
\\n \").concat(item.count, \" \\u0448\\u0442.\\n
\\n
\\n \\u0426\\u0435\\u043D\\u0430 \\u0437\\u0430 1 \\u0448\\u0442.\\n
\\n
\\n \").concat(item.price.toFixed(2), \"\\u20BD\\n
\\n
\\n \\n \\n
\\n
\\n
\");\n }\n });\n });\n return html;\n}\n\nfunction diffDates(firstDate, secondDate) {\n var diff = Math.floor((firstDate - secondDate) / (60 * 60 * 24 * 1000));\n\n if (diff <= 0) {\n return 'добавлено сегодня';\n }\n\n return diff + ' дней назад';\n}\n\n//# sourceURL=webpack:///./src/templates/items.template.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"renderItems\", function() { return renderItems; });\nfunction renderItems(categories, items) {\n var arrayCategories = categories;\n var arrayItems = items;\n var html = '';\n\n try {\n arrayCategories.forEach(function (category) {\n html += \"
\\n

\".concat(category.title, \"

\\n
\");\n category.itemsInCategory = 0; // счетчит для отслеживания категорий где нету айтемов\n\n try {\n arrayItems.forEach(function (item) {\n if (item.category.toLowerCase() === category.title.toLowerCase()) {\n category.itemsInCategory += 1;\n html += \"\\n
\\n
\\n
\\n \\\"#\\\"\\n
\\n \\n
\\n
\\n
\\n \").concat(diffDates(new Date(), new Date(item.date)), \"\\n
\\n
\\n \").concat(item.count, \" \\u0448\\u0442.\\n
\\n
\\n \\u0426\\u0435\\u043D\\u0430 \\u0437\\u0430 1 \\u0448\\u0442.\\n
\\n
\\n \").concat(item.price.toFixed(2), \"\\u20BD\\n
\\n
\\n \\n \\n
\\n
\\n
\");\n }\n });\n category.itemsInCategory === 0 ? html += '
В этой категории товаров пока что нету.
' : false;\n } catch (_unused) {\n html += '
В этой категории товаров пока что нету.
';\n }\n });\n } catch (_unused2) {\n html += '
Добавьте хотя бы одну категорию.
';\n }\n\n return html;\n}\n\nfunction diffDates(firstDate, secondDate) {\n var diff = Math.floor((firstDate - secondDate) / (60 * 60 * 24 * 1000));\n\n if (diff <= 0) {\n return 'добавлено сегодня';\n }\n\n return diff + ' дней назад';\n}\n\n//# sourceURL=webpack:///./src/templates/items.template.js?"); /***/ }), diff --git a/dist/views/index.pug b/dist/views/index.pug index 421be21..a1beaa2 100644 --- a/dist/views/index.pug +++ b/dist/views/index.pug @@ -10,7 +10,7 @@ main.main-section .row // Information Block .col.s12 - #information.information + #information.information.hide .information-content.block-content .information-title h2.small-title Важная информация: diff --git a/src/components/information.component.js b/src/components/information.component.js index 4078af2..34bd1cd 100644 --- a/src/components/information.component.js +++ b/src/components/information.component.js @@ -7,8 +7,8 @@ export class InformationComponent extends Component { init() { if (this.$el) { - if (localStorage.getItem('visited')) { - this.hide(); + if (!localStorage.getItem('visited')) { + this.show(); } const btn = this.$el.querySelector('#information-close'); btn.addEventListener('click', buttonHandler.bind(this)); diff --git a/src/templates/items.template.js b/src/templates/items.template.js index 6187b68..04bc8d7 100644 --- a/src/templates/items.template.js +++ b/src/templates/items.template.js @@ -3,46 +3,58 @@ export function renderItems(categories, items) { const arrayItems = items; let html = ''; - - arrayCategories.forEach(category => { - html += `
-

${category.title}

-
`; - arrayItems.forEach(item => { - if (item.category.toLowerCase() === category.title.toLowerCase()) { - html += ` -
-
-
- # -
- -
-
-
- ${diffDates(new Date(), new Date(item.date))} -
-
- ${item.count} шт. -
-
- Цена за 1 шт. -
-
- ${item.price.toFixed(2)}₽ -
-
- - -
-
+ try { + arrayCategories.forEach(category => { + html += `
+

${category.title}

`; + category.itemsInCategory = 0; // счетчит для отслеживания категорий где нету айтемов + try { + arrayItems.forEach(item => { + if (item.category.toLowerCase() === category.title.toLowerCase()) { + category.itemsInCategory += 1; + html += ` +
+
+
+ # +
+ +
+
+
+ ${diffDates(new Date(), new Date(item.date))} +
+
+ ${item.count} шт. +
+
+ Цена за 1 шт. +
+
+ ${item.price.toFixed(2)}₽ +
+
+ + +
+
+
`; + } + }) + category.itemsInCategory === 0 + ? html += '
В этой категории товаров пока что нету.
' + : false; + } catch { + html += '
В этой категории товаров пока что нету.
'; } - }) - }); + }); + } catch { + html += '
Добавьте хотя бы одну категорию.
'; + } return html; }