Open fazilsnippet opened 1 month ago
const toggleSubscription = asyncHandler(async (req, res) => {
try {
// Get channelId from parameters
const { channelId } = req.params;
// TODO: toggle subscription
if (!channelId) {
return res.status(400).json(new ApiError(400, "channelId required"));
}
// Check is the channelId is mongoose valid ID
if (!mongoose.Types.ObjectId.isValid(channelId)) {
return res.status(400).json(new ApiError(400, "Invalid channelId"));
}
// Use middleware where set the user in req using req.user = user, and before it find the user if logged in it will return true. // Its code is written in another file.
if (!req.user || !req.user?._id) {
return res.status(401).json(new ApiError(401, "User is Unauthorized"));
}
// Here is another validation check, whether user or channel owner exist. const channelExists = await User.exists({ _id: channelId }); if (!channelExists) { return res.status(404).json(new ApiError(404, "Channel not found")); } // find the current user using req.user._id which we have already discussed. const toggleSubscribe = await Subscription.findOne({ subscriber: req.user._id, channel: channelId, }); // If not subscribing the channel if (!toggleSubscribe) { const subscribed = await Subscription.create({ subscriber: req.user._id, channel: channelId, }); return res .status(201) .json(new ApiResponse(201, subscribed, "Subscribed")); } // If already subscribing the channel else { await Subscription.findOneAndDelete({ subscriber: req.user._id, channel: channelId, }); return res .status(200) .json(new ApiResponse(200, null, "Unsubscribed successfully")); } } catch (error) { console.error(error); return res .status(500) .json(new ApiError(500, "Internal Sever Error while subscribing")); } });
Thank you. I appreciate your efforts ☺️
How to unsubscribe the channel?