Skip to content

Commit

Permalink
feat: Added search ablity
Browse files Browse the repository at this point in the history
  • Loading branch information
hossainchisty committed Aug 27, 2023
1 parent 004d059 commit 84595e4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
44 changes: 42 additions & 2 deletions controllers/postController.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const getPostByID = asyncHandler(async (req, res) => {
const post = await Post.findByIdAndUpdate(
id,
{ $inc: { views: 1 } }, // Increment views by 1
{ new: true }, // Return the updated document
{ new: true } // Return the updated document
)
.populate("author", ["full_name"])
.lean();
Expand Down Expand Up @@ -172,7 +172,7 @@ const updatePost = asyncHandler(async (req, res) => {

await Post.updateOne(
{ _id: id },
{ title, content, cover: newPath ? newPath : post.cover },
{ title, content, cover: newPath ? newPath : post.cover }
);

res.status(200).json({
Expand Down Expand Up @@ -238,11 +238,51 @@ const deletePost = asyncHandler(async (req, res) => {
}
});

/**
* @desc Search posts by title
* @route /api/v1/posts/search
* @method GET
* @access Public
*/

const searchPost = asyncHandler(async (req, res) => {
const { title } = req.query;

try {
const posts = await Post.find({
title: { $regex: new RegExp(title, "i") },
});

if (posts.length === 0) {
return res.status(404).json({
status: 404,
message: "No posts found",
});
}

res.status(200).json({
status: 200,
data: {
posts,
},
});
} catch (error) {
console.error(error);
res.status(500).json({
status: 500,
error: "Internal Server Error",
message: "An error occurred while searching for posts.",
});
}
});


module.exports = {
getPosts,
getPostByID,
getPostsList,
addPost,
updatePost,
deletePost,
searchPost,
};
3 changes: 3 additions & 0 deletions routes/postRouters.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const {
addPost,
updatePost,
deletePost,
searchPost,
} = require("../controllers/postController");

const storage = multer.diskStorage({
Expand All @@ -26,6 +27,8 @@ const uploadMiddleware = multer({ storage: storage }).single("image");

// Get all posts
router.get("/list", getPostsList);
// Search for posts with the given title
router.get("/search", searchPost);

router
.route("/")
Expand Down

0 comments on commit 84595e4

Please sign in to comment.