0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-28 22:12:39 +00:00

limit the search

This commit is contained in:
Víctor Losada Hernández
2024-01-24 21:15:00 +01:00
parent c50042c1e7
commit 0c167d803c

View File

@@ -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;
module.exports = router;