- Add UserFavorites MongoDB model with ObjectId references - Create authenticated API endpoints for favorites management - Add Heart icon and FavoriteButton components with toggle functionality - Display favorite button below recipe tags for logged-in users - Add Favoriten navigation link (visible only when authenticated) - Create favorites page with grid layout and search functionality - Store favorites by MongoDB ObjectId for data integrity 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import { json, type RequestHandler } from '@sveltejs/kit';
|
|
import { UserFavorites } from '../../../../../models/UserFavorites';
|
|
import { Recipe } from '../../../../../models/Recipe';
|
|
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
|
import type { RecipeModelType } from '../../../../../types/types';
|
|
import { error } from '@sveltejs/kit';
|
|
|
|
export const GET: RequestHandler = async ({ locals }) => {
|
|
const session = await locals.auth();
|
|
|
|
if (!session?.user?.nickname) {
|
|
throw error(401, 'Authentication required');
|
|
}
|
|
|
|
await dbConnect();
|
|
|
|
try {
|
|
const userFavorites = await UserFavorites.findOne({
|
|
username: session.user.nickname
|
|
}).lean();
|
|
|
|
if (!userFavorites?.favorites?.length) {
|
|
await dbDisconnect();
|
|
return json([]);
|
|
}
|
|
|
|
let recipes = await Recipe.find({
|
|
_id: { $in: userFavorites.favorites }
|
|
}).lean() as RecipeModelType[];
|
|
|
|
await dbDisconnect();
|
|
|
|
recipes = JSON.parse(JSON.stringify(recipes));
|
|
|
|
return json(recipes);
|
|
} catch (e) {
|
|
await dbDisconnect();
|
|
throw error(500, 'Failed to fetch favorite recipes');
|
|
}
|
|
}; |