add feature to edit recipes

This commit is contained in:
2025-08-10 14:38:04 +01:00
parent 85138a6575
commit 7c0907a109
7 changed files with 592 additions and 30 deletions

View File

@@ -160,19 +160,27 @@ router.post('/', authenticateToken, async (req, res) => {
}
});
// Update recipe
router.put('/:id', async (req, res) => {
// Update recipe (protected route)
router.put('/:id', authenticateToken, async (req, res) => {
try {
const recipe = await Recipe.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
);
if (!recipe) {
const recipeId = req.params.id;
// Find the recipe first to preserve original creator
const existingRecipe = await Recipe.findById(recipeId);
if (!existingRecipe) {
return res.status(404).json({ error: 'Recipe not found' });
}
res.json(recipe);
// Update the recipe while preserving the createdBy field
const updatedRecipe = await Recipe.findByIdAndUpdate(
recipeId,
{ ...req.body, createdBy: existingRecipe.createdBy }, // Preserve original creator
{ new: true, runValidators: true }
);
res.json(updatedRecipe);
} catch (error) {
console.error('Error updating recipe:', error);
res.status(400).json({ error: error.message });
}
});
@@ -182,17 +190,12 @@ router.delete('/:id', authenticateToken, async (req, res) => {
try {
const recipeId = req.params.id;
// Find the recipe first to check ownership
// Find the recipe first to verify it exists
const recipe = await Recipe.findById(recipeId);
if (!recipe) {
return res.status(404).json({ error: 'Recipe not found' });
}
// 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);