From 6fb0c3b68a8d80c5eb9ae740d8d17b496eb0d7b6 Mon Sep 17 00:00:00 2001 From: Alexander Bocken Date: Sat, 3 Jan 2026 16:10:38 +0100 Subject: [PATCH] fix: ensure recipe deletion removes database entries, images, and favorites Fixes critical bug where recipes could not be deleted properly. The delete function had an early return statement that prevented database deletion from executing, leaving orphaned entries. Additionally, deleted recipes were not removed from users' favorites lists. Changes: - Remove premature return statement blocking database deletion - Fix malformed fetch call structure (headers were inside body JSON) - Add UserFavorites cleanup to remove deleted recipes from all users' favorites - Ensure complete cleanup: database entry, image files (hashed and unhashed), and favorites references --- .../edit/[name]/+page.svelte | 7 +++---- src/routes/api/rezepte/delete/+server.ts | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.svelte b/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.svelte index c49c32ed..cbda635c 100644 --- a/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.svelte +++ b/src/routes/[recipeLang=recipeLang]/edit/[name]/+page.svelte @@ -209,16 +209,15 @@ //alert(item.message) return } - return const res = await fetch('/api/rezepte/delete', { method: 'POST', body: JSON.stringify({ old_short_name, + }), headers: { 'content-type': 'application/json', - } - }) - + credentials: 'include', + } }) if(res.ok){ const url = location.href.split('/') diff --git a/src/routes/api/rezepte/delete/+server.ts b/src/routes/api/rezepte/delete/+server.ts index 758892d6..3babe6e9 100644 --- a/src/routes/api/rezepte/delete/+server.ts +++ b/src/routes/api/rezepte/delete/+server.ts @@ -1,5 +1,6 @@ import type { RequestHandler } from '@sveltejs/kit'; import { Recipe } from '../../../../models/Recipe'; +import { UserFavorites } from '../../../../models/UserFavorites'; import { dbConnect } from '../../../../utils/db'; import type {RecipeModelType} from '../../../../types/types'; import { error } from '@sveltejs/kit'; @@ -13,8 +14,23 @@ export const POST: RequestHandler = async ({request, locals}) => { const short_name = message.old_short_name await dbConnect(); + + // Find the recipe to get its ObjectId before deleting + const recipe = await Recipe.findOne({short_name: short_name}); + if (!recipe) { + throw error(404, "Recipe not found"); + } + + // Remove this recipe from all users' favorites + await UserFavorites.updateMany( + { favorites: recipe._id }, + { $pull: { favorites: recipe._id } } + ); + + // Delete the recipe await Recipe.findOneAndDelete({short_name: short_name}); + return new Response(JSON.stringify({msg: "Deleted recipe successfully"}),{ - status: 200, + status: 200, }); }