From 0c167d803c180c5953a0206c063b39ba8ffad0fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Wed, 24 Jan 2024 21:15:00 +0100 Subject: [PATCH] limit the search --- server/archive.api.js | 43 ++++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/server/archive.api.js b/server/archive.api.js index 6302e3041..73ec2f170 100644 --- a/server/archive.api.js +++ b/server/archive.api.js @@ -2,29 +2,38 @@ const HomebrewModel = require('./homebrew.model.js').model; const router = require('express').Router(); const asyncHandler = require('express-async-handler'); - const archive = { - archiveApi : router, + archiveApi: router, /* Searches for matching title, also attempts to partial match */ - findBrews : async (req, res, next) => { + findBrews: async (req, res, next) => { try { - const brews = await HomebrewModel.find({ - title: { $regex: req.params.query, $options: 'i' }, - published: true - }).exec(); - - if (!brews || brews.length === 0) { - // No published documents found with the given title - return res.status(404).json({ error: 'Published documents not found' }); - } - return res.json(brews); + const limit = 3; + const brews = await HomebrewModel.find({ + title: { $regex: req.params.query, $options: 'i' }, + published: true + }) + .limit(limit) + .exec(); + + if (!brews || brews.length === 0) { + // No published documents found with the given title + return res.status(404).json({ error: 'Published documents not found' }); + } + + let message = ''; + if (brews.length === limit) { + // If the limit has been reached, include a message in the response + message = `You've reached the limit of ${limit} documents, you can try being more specific in your search.`; + } + + return res.json({ brews, message }); } catch (error) { - console.error(error); - return res.status(500).json({ error: 'Internal Server Error' }); + console.error(error); + return res.status(500).json({ error: 'Internal Server Error' }); } } } + router.get('/archive/:query', asyncHandler(archive.findBrews)); - -module.exports = router; \ No newline at end of file +module.exports = router;