diff --git a/src/lib/components/FavoriteButton.svelte b/src/lib/components/FavoriteButton.svelte index ce3831d..2d63227 100644 --- a/src/lib/components/FavoriteButton.svelte +++ b/src/lib/components/FavoriteButton.svelte @@ -1,33 +1,42 @@ @@ -55,12 +64,17 @@ {#if isLoggedIn} - +
{/if} \ No newline at end of file diff --git a/src/routes/rezepte/[name]/+page.server.ts b/src/routes/rezepte/[name]/+page.server.ts index 0b4cd3c..6280387 100644 --- a/src/routes/rezepte/[name]/+page.server.ts +++ b/src/routes/rezepte/[name]/+page.server.ts @@ -1,6 +1,50 @@ -import { redirect } from '@sveltejs/kit'; +import { redirect, error } from '@sveltejs/kit'; export const actions = { + toggleFavorite: async ({ request, locals, url, fetch }) => { + const session = await locals.auth(); + + if (!session?.user?.nickname) { + throw error(401, 'Authentication required'); + } + + const formData = await request.formData(); + const recipeId = formData.get('recipeId') as string; + const isFavorite = formData.get('isFavorite') === 'true'; + + if (!recipeId) { + throw error(400, 'Recipe ID required'); + } + + try { + // Use the existing API endpoint + const method = isFavorite ? 'DELETE' : 'POST'; + const response = await fetch('/api/rezepte/favorites', { + method, + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ recipeId }), + }); + + if (!response.ok) { + const errorData = await response.text(); + console.error('API error:', response.status, errorData); + throw error(response.status, `Failed to toggle favorite: ${errorData}`); + } + + // Redirect back to the same page to refresh the state + throw redirect(303, url.pathname); + } catch (e) { + // If it's a redirect, let it through + if (e && typeof e === 'object' && 'status' in e && e.status === 303) { + throw e; + } + console.error('Favorite toggle error:', e); + throw error(500, 'Failed to toggle favorite'); + } + }, + swapYeast: async ({ request, url }) => { const formData = await request.formData(); const yeastId = parseInt(formData.get('yeastId') as string);