add feature to delete recipes when logged in
This commit is contained in:
@@ -177,15 +177,62 @@ router.put('/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Delete recipe
|
||||
router.delete('/:id', async (req, res) => {
|
||||
// Delete recipe (protected route)
|
||||
router.delete('/:id', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const recipe = await Recipe.findByIdAndDelete(req.params.id);
|
||||
const recipeId = req.params.id;
|
||||
|
||||
// Find the recipe first to check ownership
|
||||
const recipe = await Recipe.findById(recipeId);
|
||||
if (!recipe) {
|
||||
return res.status(404).json({ error: 'Recipe not found' });
|
||||
}
|
||||
res.json({ message: 'Recipe deleted successfully' });
|
||||
|
||||
// Check if user owns the recipe (only recipe creator can delete)
|
||||
if (recipe.createdBy.toString() !== req.userId) {
|
||||
return res.status(403).json({ error: 'You can only delete recipes you created' });
|
||||
}
|
||||
|
||||
// Delete the recipe
|
||||
await Recipe.findByIdAndDelete(recipeId);
|
||||
|
||||
// Remove recipe from all user selections
|
||||
const UserSelection = require('../models/UserSelection');
|
||||
await UserSelection.updateMany(
|
||||
{ 'selectedRecipes.recipeId': recipeId },
|
||||
{
|
||||
$pull: {
|
||||
selectedRecipes: { recipeId: recipeId }
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Also clean up aggregated ingredients that reference this recipe
|
||||
await UserSelection.updateMany(
|
||||
{ 'aggregatedIngredients.recipes.recipeId': recipeId },
|
||||
{
|
||||
$pull: {
|
||||
'aggregatedIngredients.$[].recipes': { recipeId: recipeId }
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Remove empty aggregated ingredients (those with no recipes left)
|
||||
await UserSelection.updateMany(
|
||||
{},
|
||||
{
|
||||
$pull: {
|
||||
aggregatedIngredients: { recipes: { $size: 0 } }
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: 'Recipe deleted successfully and removed from all user menus',
|
||||
deletedRecipeId: recipeId
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error deleting recipe:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user