From 8edc8548777210f3713c961c6c38209b32af00af Mon Sep 17 00:00:00 2001 From: Ben PC Date: Wed, 30 Mar 2022 14:28:07 +0200 Subject: [PATCH] Filters & Merge --- index.js | 36 +++++++++++++++++++++++++--- mysql_handler.js | 4 ++-- views/search.ejs | 62 +++++++++++++++++++++++++++++++++--------------- 3 files changed, 78 insertions(+), 24 deletions(-) diff --git a/index.js b/index.js index 21938af..42bf073 100644 --- a/index.js +++ b/index.js @@ -210,15 +210,45 @@ app.post("/review/create/:productId", authenticatedHandler,(req, res) => { }); // Search Page -app.get("/search/:query",authNoRedirectHandler,(req, res) => { +app.get("/search/:query/",authNoRedirectHandler,(req, res) => { let query = req.params.query; let dict = { title: "Suche", search: query, - user: req.user, + user: req.user, + sort: req.query.sort ? req.query.sort : 0, + Cat: req.query.cat ? req.query.cat : 0 } - mysql_handler.con.query("SELECT *, (SELECT url FROM product_images i WHERE i.product_id = p.id LIMIT 1) as img, (SELECT AVG(rating) FROM reviews r WHERE r.productId = p.id) as rating FROM products p WHERE name LIKE ?;",["%"+query+"%"],function(err, result){ + mysql_handler.con.query("SELECT * FROM categories;",function(err, result) { + if(err) throw err; + + dict.categories = JSON.parse(JSON.stringify(result)); + }); + + var catQuery = ""; + var cat = req.query.cat; + if (typeof cat !== 'undefined' && cat != 0) { + catQuery = " AND categoryId = "+cat; + } + + var sortQuery = ""; + var sort = req.query.sort; + if (typeof sort !== 'undefined') { + if (sort == 1) { + sortQuery = " ORDER BY price ASC"; + } else if (sort == 2) { + sortQuery = " ORDER BY price DESC"; + } else if (sort == 3) { + sortQuery = " ORDER BY (SELECT SUM(quantity) FROM order_products o WHERE o.productId = p.id) DESC"; + } else if (sort == 4) { + sortQuery = " ORDER BY name ASC"; + } else if (sort == 5) { + sortQuery = " ORDER BY name DESC"; + } + } + + mysql_handler.con.query("SELECT *, (SELECT url FROM product_images i WHERE i.product_id = p.id LIMIT 1) as img, (SELECT AVG(rating) FROM reviews r WHERE r.productId = p.id) as rating FROM products p WHERE name LIKE ? "+catQuery+" "+sortQuery+";",["%"+query+"%"],function(err, result){ if(err) throw err; dict.products = JSON.parse(JSON.stringify(result)); diff --git a/mysql_handler.js b/mysql_handler.js index 1063cd6..c7cdcb9 100644 --- a/mysql_handler.js +++ b/mysql_handler.js @@ -12,8 +12,8 @@ con.query("SELECT * FROM users", function(err, result){ let con = mysql.createConnection({ // TODO: change to config file host: "localhost", - user: "onlineshop", - password: "TestUser321", // TODO: DO NOT STORE PASSWORDS IN THE CODE + user: "root", + password: "", // TODO: DO NOT STORE PASSWORDS IN THE CODE database: "onlineshop" }); diff --git a/views/search.ejs b/views/search.ejs index 344a7c8..0ebe8c7 100644 --- a/views/search.ejs +++ b/views/search.ejs @@ -7,9 +7,23 @@
<%- include('partials/header'); %>
-