0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-25 01:02:47 +00:00
Files
homebrewery/server/archive.api.js
Víctor Losada Hernández fe449abb47 trying to figure out pagination
2024-02-10 16:41:39 +01:00

52 lines
1.7 KiB
JavaScript

const HomebrewModel = require('./homebrew.model.js').model;
const router = require('express').Router();
const asyncHandler = require('express-async-handler');
const archive = {
archiveApi: router,
/* Searches for matching title, also attempts to partial match */
findBrews: async (req, res, next) => {
try {
const page = parseInt(req.params.page) || 1;
console.log('try:',page);
const pageSize = 10; // Set a default page size
const skip = (page - 1) * pageSize;
const title = {
title: { $regex: decodeURIComponent(req.params.title), $options: 'i' },
published: true
};
const projection = {
editId: 0,
googleId: 0,
text: 0,
textBin: 0,
};
const brews = await HomebrewModel.find(title, projection)
.skip(skip)
.limit(pageSize)
.maxTimeMS(5000)
.exec();
if (!brews || brews.length === 0) {
// No published documents found with the given title
return res.status(404).json({ error: 'Published documents not found' });
}
const totalDocuments = await HomebrewModel.countDocuments(title);
const totalPages = Math.ceil(totalDocuments / pageSize);
return res.json({ brews, page, totalPages});
} catch (error) {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
}
};
router.get('/archive/:title/:page', asyncHandler(archive.findBrews));
module.exports = router;