Skip to content

Commit

Permalink
feat: Added post views counters
Browse files Browse the repository at this point in the history
  • Loading branch information
hossainchisty committed Aug 26, 2023
1 parent bd809b2 commit f7b5775
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
37 changes: 26 additions & 11 deletions controllers/postController.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,37 @@ const getPostsList = asyncHandler(async (req, res) => {

const getPostByID = asyncHandler(async (req, res) => {
const { id } = req.params;
const post = await Post.findById(id).populate("author", ["full_name"]).lean();

if (!post) {
return res.status(404).json({
status: 404,
error: "Not Found",
message: "Post not found.",
try {
const post = await Post.findByIdAndUpdate(
id,
{ $inc: { views: 1 } }, // Increment views by 1
{ new: true } // Return the updated document
).populate("author", ["full_name"]).lean();

if (!post) {
return res.status(404).json({
status: 404,
error: "Not Found",
message: "Post not found.",
});
}

return res.status(200).json({
status: 200,
data: post,
});
} catch (error) {
return res.status(500).json({
status: 500,
error: "Internal Server Error",
message: "An error occurred while fetching the post.",
});
}

return res.status(200).json({
status: 200,
data: post,
});
});



/**
* @desc Create a new post for the authenticated user
* @route /api/v1/posts
Expand Down
3 changes: 2 additions & 1 deletion models/postModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ const postSchema = mongoose.Schema(
type: String,
required: true,
},
views: { type: BigInt },
isDraft: { type: Boolean, default: false, index: true },
notifications: { type: Boolean, default: true },
},
{ timestamps: true },
{ versionKey: false },
{ versionKey: false }
);

module.exports = mongoose.model("Post", postSchema);

0 comments on commit f7b5775

Please sign in to comment.