From 0d9144cf0d17cadfaacc3628ef8cc285fc9e054f Mon Sep 17 00:00:00 2001 From: Thatskat <109633947+Thatskat@users.noreply.github.com> Date: Sat, 1 Jul 2023 16:06:33 +1000 Subject: [PATCH] completed search function --- index.js | 9 ++++++++- quotesController.js | 23 ++++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index e0c3e58..748c922 100644 --- a/index.js +++ b/index.js @@ -21,7 +21,10 @@ const limit = rateLimit({ }); // GET RANDOM FUNCTION FROM ./QUOTESCONTROLLER -const { getRandom } = require("./quotesController"); +const { getRandom, searchQuotes } = require("./quotesController"); + +// IMPORT QUOTES ARRAY +const quotes = require('./quotes'); // IMPLEMENT MIDDLEWARE app.use(helmet()); @@ -38,6 +41,10 @@ app.get("/v1/quotes/:num?", function (req, res, next) { res.send(getRandom(req.params.num || 1)); }); +app.get("/v1/quotes/search/:term", function (req, res,) { + res.send(searchQuotes(quotes, req.params.term)); +}) + // USE ERROR MIDDLEWARE app.use(error) diff --git a/quotesController.js b/quotesController.js index ee61760..9917c06 100644 --- a/quotesController.js +++ b/quotesController.js @@ -16,10 +16,27 @@ function getRandom(quoteNumber) { return response; } -function searchQuotes(searchTerm) { - const regEx = new RegExp(searchTerm, "i"); +function filterIt(arr, searchTerm) { + return arr.filter(function (obj) { + return Object.keys(obj).some(function (key) { + return obj[key].includes(searchTerm); + }); + }); +} + +function searchQuotes(arr, searchTerm) { + let regex = new RegExp(searchTerm, "i"); + regex = regex.toString().replace(/^\/|\/[a-z]*$/gi, ""); + + let lowercaseArr = arr.map(function (i) { + let lowercaseObjects = {}; + Object.entries(i).forEach(function ([key, value]) { + lowercaseObjects[key] = value.toLowerCase(); + }); + return lowercaseObjects; + }); - return quotes.filter(quote && quote.match(regEx)); + return filterIt(lowercaseArr, regex); } module.exports.getRandom = getRandom;