Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions app/api/meals/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getSession } from "@/lib/auth";

export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getSession();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const { id } = await params;
const mealId = parseInt(id);
if (isNaN(mealId)) {
return NextResponse.json({ error: "Invalid meal ID" }, { status: 400 });
}

try {
const meal = await prisma.meal.findUnique({
where: { id: mealId },
});

if (!meal) {
return NextResponse.json({ error: "Meal not found" }, { status: 404 });
}

if (meal.userId !== session.user.id) {
return NextResponse.json(
{ error: "You can only delete your own meals" },
{ status: 403 }
);
}

await prisma.meal.delete({
where: { id: mealId },
});

return NextResponse.json({ ok: true }, { status: 200 });
} catch (error) {
console.error("Error deleting meal:", error);
return NextResponse.json(
{ error: "Failed to delete meal" },
{ status: 500 }
);
}
}
56 changes: 56 additions & 0 deletions app/api/meals/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getSession } from "@/lib/auth";
import { MealType } from "@/app/generated/prisma/enums";

export async function POST(request: Request) {
const session = await getSession();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const body = (await request.json().catch(() => null)) as
| {
name: string;
description?: string;
ingredients: Record<string, number>;
recipe?: string[];
suggestedMealType: MealType[];
tagIds: number[];
}
| null;

if (!body || !body.name || !body.ingredients || !body.suggestedMealType) {
return NextResponse.json(
{ error: "Missing required fields: name, ingredients, suggestedMealType" },
{ status: 400 }
);
}

try {
const meal = await prisma.meal.create({
data: {
name: body.name,
description: body.description || null,
ingredients: body.ingredients,
recipe: body.recipe || null,
suggestedMealType: body.suggestedMealType,
userId: session.user.id,
tags: {
connect: body.tagIds.map((id) => ({ id })),
},
},
include: {
tags: true,
},
});

return NextResponse.json({ ok: true, meal }, { status: 201 });
} catch (error) {
console.error("Error creating meal:", error);
return NextResponse.json(
{ error: "Failed to create meal" },
{ status: 500 }
);
}
}
71 changes: 71 additions & 0 deletions app/meals/DeleteMealButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

interface Props {
mealId: number;
mealName: string;
}

export default function DeleteMealButton({ mealId, mealName }: Props) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);

const handleDelete = async () => {
setLoading(true);
try {
const res = await fetch(`/api/meals/${mealId}`, {
method: "DELETE",
});

if (res.ok) {
router.refresh();
} else {
const data = await res.json();
alert(data.error || "Nie udało się usunąć posiłku");
}
} catch (err) {
console.error("Error deleting meal:", err);
alert("Wystąpił błąd podczas usuwania posiłku");
} finally {
setLoading(false);
setShowConfirm(false);
}
};

if (!showConfirm) {
return (
<button
type="button"
onClick={() => setShowConfirm(true)}
className="text-[10px] uppercase tracking-wide bg-red-900/40 text-red-200 px-2 py-1 rounded-full border border-red-700/60 hover:bg-red-900/60 transition-colors ml-2"
title="Usuń posiłek"
>
Usuń
</button>
);
}

return (
<div className="flex gap-1 ml-2">
<button
type="button"
onClick={handleDelete}
disabled={loading}
className="text-[10px] uppercase tracking-wide bg-red-600 text-white px-2 py-1 rounded-full border border-red-500 hover:bg-red-700 transition-colors disabled:opacity-50"
>
{loading ? "..." : "Tak"}
</button>
<button
type="button"
onClick={() => setShowConfirm(false)}
disabled={loading}
className="text-[10px] uppercase tracking-wide bg-zinc-700 text-zinc-300 px-2 py-1 rounded-full border border-zinc-600 hover:bg-zinc-600 transition-colors disabled:opacity-50"
>
Nie
</button>
</div>
);
}
Loading