From d2a29416fefe48c9d2040c52a51d4c63f4a697d9 Mon Sep 17 00:00:00 2001 From: Jonasz Bigda Date: Wed, 22 Jul 2020 12:49:37 +0200 Subject: [PATCH] routeSearch --- .gitignore | 3 +- routes/routeSearch.js | 79 +++++++++++++++++++++++++++++++------------ 2 files changed, 60 insertions(+), 22 deletions(-) diff --git a/.gitignore b/.gitignore index 3bafec1..5a5900b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .env -images/ \ No newline at end of file +images/ +node_modules/ \ No newline at end of file diff --git a/routes/routeSearch.js b/routes/routeSearch.js index 00908bd..c21515b 100644 --- a/routes/routeSearch.js +++ b/routes/routeSearch.js @@ -6,32 +6,69 @@ import restaurant from "../models/restaurant.js"; var router = express.Router(); +// SEARCH RESTAURANTS BY NAME OR CITY + +router.get("/", (req, res) => { + if (req.query.string.length > 0) { + const query = sanitizer.sanitize.keepUnicode(decodeURI(req.query.string)); + const regex = new RegExp(query, "i"); + + Restaurant.find( + { + $and: [ + { $or: [{ city: { $regex: regex } }, { name: { $regex: regex } }] }, + { hidden: false }, + ], + }, + "_id name city imgUrl workingHours", + (err, results) => { + if (err) { + res.sendStatus(500); + } else { + res.send(results); + } + } + ); + } else { + res.send({ + results: [], + }); + } +}); + // AUTOCOMPLETE router.get("/autocomplete/", (req, res) => { - var query = sanitizer.sanitize.keepUnicode(decodeURI(req.query.string)); - const regex = new RegExp(query, "i"); - let cities = new Set(); - let restaurants = new Set(); + if (req.query.string.length > 0) { + var query = sanitizer.sanitize.keepUnicode(decodeURI(req.query.string)); + const regex = new RegExp(query, "i"); + let cities = new Set(); + let restaurants = new Set(); - Restaurant.find( - { $or: [{ city: { $regex: regex } }, { name: { $regex: regex } }] }, - "name city", - (err, doc) => { - if (err) { - res.send(404); - } else { - doc.forEach((value) => { - cities.add(value.city); - restaurants.add(value.name); - }); - res.send({ - cities: Array.from(cities), - restaurants: Array.from(restaurants), - }); + Restaurant.find( + { $or: [{ city: { $regex: regex } }, { name: { $regex: regex } }] }, + "name city", + (err, doc) => { + if (err) { + res.send(404); + } else { + doc.forEach((value) => { + cities.add(value.city); + restaurants.add(value.name); + }); + res.send({ + cities: Array.from(cities), + restaurants: Array.from(restaurants), + }); + } } - } - ).limit(10); + ).limit(5); + } else { + res.send({ + cities: [], + restaurants: [], + }); + } }); export default router;