fix:search pagination issue

This commit is contained in:
rishalkv
2026-04-24 17:25:47 +05:30
parent 67fe087906
commit 6001a2db64
+22 -36
View File
@@ -4,53 +4,40 @@ import prisma from "../prisma/client.js";
export const getAllNews = async (req, res) => { export const getAllNews = async (req, res) => {
try { try {
const page = parseInt(req.query.page); const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit); const limit = parseInt(req.query.limit) || 10;
const search = req.query.search?.trim() || "";
const includeImages = { const includeImages = {
images: true, images: true,
}; };
if (!page && !limit) { const searchFilter = search
const news = await prisma.newsMedia.findMany({ ? {
include: includeImages, headline: {
orderBy: { createdAt: "desc" }, contains: search,
}); mode: "insensitive",
},
const response = news.map((n) => ({
Id: n.id.toString(),
Headline: n.headline,
Content: n.content,
FirstPara: n.firstPara,
SecondPara: n.secondPara,
Date: n.date,
Author: n.author,
Images: n.images.map((img) => ({
id: img.id,
image: img.url,
})),
}));
return res.status(200).json({
success: true,
data: response,
meta: null,
});
} }
: {};
const currentPage = page || 1; const whereCondition = {
const currentLimit = limit || 10; ...searchFilter,
};
const skip = (currentPage - 1) * currentLimit; const skip = (page - 1) * limit;
const [news, total] = await Promise.all([ const [news, total] = await Promise.all([
prisma.newsMedia.findMany({ prisma.newsMedia.findMany({
where: whereCondition,
include: includeImages, include: includeImages,
orderBy: { createdAt: "desc" }, orderBy: { createdAt: "desc" },
skip, skip,
take: currentLimit, take: limit,
}),
prisma.newsMedia.count({
where: whereCondition,
}), }),
prisma.newsMedia.count(),
]); ]);
const response = news.map((n) => ({ const response = news.map((n) => ({
@@ -72,9 +59,9 @@ export const getAllNews = async (req, res) => {
data: response, data: response,
meta: { meta: {
total, total,
page: currentPage, page,
limit: currentLimit, limit,
totalPages: Math.ceil(total / currentLimit), totalPages: Math.ceil(total / limit),
}, },
}); });
} catch (error) { } catch (error) {
@@ -85,7 +72,6 @@ export const getAllNews = async (req, res) => {
}); });
} }
}; };
// GET NEWS BY ID // GET NEWS BY ID
export const getNewsById = async (req, res) => { export const getNewsById = async (req, res) => {