diff --git a/backend/src/controllers/newsMedia.controller.js b/backend/src/controllers/newsMedia.controller.js index 473da8f..4bf935f 100644 --- a/backend/src/controllers/newsMedia.controller.js +++ b/backend/src/controllers/newsMedia.controller.js @@ -4,53 +4,40 @@ import prisma from "../prisma/client.js"; export const getAllNews = async (req, res) => { try { - const page = parseInt(req.query.page); - const limit = parseInt(req.query.limit); + const page = parseInt(req.query.page) || 1; + const limit = parseInt(req.query.limit) || 10; + const search = req.query.search?.trim() || ""; const includeImages = { images: true, }; - if (!page && !limit) { - const news = await prisma.newsMedia.findMany({ - include: includeImages, - orderBy: { createdAt: "desc" }, - }); + const searchFilter = search + ? { + headline: { + 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, - })), - })); + const whereCondition = { + ...searchFilter, + }; - return res.status(200).json({ - success: true, - data: response, - meta: null, - }); - } - - const currentPage = page || 1; - const currentLimit = limit || 10; - - const skip = (currentPage - 1) * currentLimit; + const skip = (page - 1) * limit; const [news, total] = await Promise.all([ prisma.newsMedia.findMany({ + where: whereCondition, include: includeImages, orderBy: { createdAt: "desc" }, skip, - take: currentLimit, + take: limit, + }), + prisma.newsMedia.count({ + where: whereCondition, }), - prisma.newsMedia.count(), ]); const response = news.map((n) => ({ @@ -72,9 +59,9 @@ export const getAllNews = async (req, res) => { data: response, meta: { total, - page: currentPage, - limit: currentLimit, - totalPages: Math.ceil(total / currentLimit), + page, + limit, + totalPages: Math.ceil(total / limit), }, }); } catch (error) { @@ -85,7 +72,6 @@ export const getAllNews = async (req, res) => { }); } }; - // GET NEWS BY ID export const getNewsById = async (req, res) => {