If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To enable liking posts in our app, we need to define the necessary actions and routes. Here's how we can do that:
likesController.js
file in the controllers
directory.likesController.js
file:likePost
: This action will be used to like a post. It will create a new like record in the database and associate it with the post and the user who liked it.unlikePost
: This action will be used to unlike a post. It will find the like record for the post and the user who liked it, and then delete it from the database.routes.js
file:POST /likes/:postId/like
: This route will call the likePost
action when a user likes a post.DELETE /likes/:postId/unlike
: This route will call the unlikePost
action when a user unlikes a post.Here's an example implementation of the likesController.js
file:
javascriptCopy code
const Post = require('../models/post');
const Like = require('../models/like');
module.exports.likePost = async function (req, res) {
try {
let post = await Post.findById(req.params.postId);
// Check if the post already has a like from the current user
let existingLike = await Like.findOne({
user: req.user._id,
post: req.params.postId,
});
if (!existingLike) {
// Create a new like record
let newLike = await Like.create({
user: req.user._id,
post: req.params.postId,
});
post.likes.push(newLike);
post.save();
}
return res.json(200, {
message: 'Post liked',
});
} catch (err) {
console.log('Error in liking post', err);
return res.json(500, {
message: 'Internal Server Error',
});
}
};
module.exports.unlikePost = async function (req, res) {
try {
let post = await Post.findById(req.params.postId);
// Find the like record for the post and the current user
let existingLike = await Like.findOne({
user: req.user._id,
post: req.params.postId,
});
if (existingLike) {
// Remove the like record
existingLike.remove();
// Remove the like from the post's likes array
post.likes.pull(existingLike._id);
post.save();
}
return res.json(200, {
message: 'Post unliked',
});
} catch (err) {
console.log('Error in unliking post', err);
return res.json(500, {
message: 'Internal Server Error',
});
}
};
And here's an example implementation of the routes.js
file:
javascriptCopy code
const express = require('express');
const router = express.Router();
const passport = require('passport');
const likesController = require('../controllers/likesController');
router.post(
'/likes/:postId/like',
passport.authenticate('jwt', { session: false }),
likesController.likePost
);
router.delete(
'/likes/:postId/unlike',
passport.authenticate('jwt', { session: false }),
likesController.unlikePost
);
module.exports = router;
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.