From cdcc546bd74a3d64f26fcc2aed773deb9fb98129 Mon Sep 17 00:00:00 2001 From: StefanWout Date: Thu, 7 Nov 2024 10:12:48 +0000 Subject: [PATCH] attempt at completing the delete api call --- src/app/api/portfolio/[portfolioId]/route.ts | 39 +++++----- .../settings/PortfolioSettings.tsx | 74 +++++++++++-------- 2 files changed, 66 insertions(+), 47 deletions(-) diff --git a/src/app/api/portfolio/[portfolioId]/route.ts b/src/app/api/portfolio/[portfolioId]/route.ts index f4f7400..d551c91 100644 --- a/src/app/api/portfolio/[portfolioId]/route.ts +++ b/src/app/api/portfolio/[portfolioId]/route.ts @@ -1,6 +1,6 @@ import { db } from "@/app/db/db"; import { NextRequest, NextResponse } from "next/server"; -import { portfolio } from "@/app/db/schema/portfolio"; +import { portfolio, portfolioUsers } from "@/app/db/schema/portfolio"; import { and, eq, inArray } from "drizzle-orm"; import { user } from "@/app/db/schema/users"; @@ -27,18 +27,20 @@ export async function PUT(request: NextRequest) { } export async function DELETE(request: NextRequest) { - const body = await request.json(); - console.log("WE BE DELETIN'"); - - const portfolioId = body.portfolioId; - const userId = body.userId; - + console.log("Incoming DELETE request:", request.method); try { - // Verify the user owns this portfolio before deleting + // Parse the request body + const body = await request.json(); + console.log("DELETE Request Received", body); + + const portfolioId = body.portfolioId; + const userId = body.userId; + + // First verify the portfolio exists and belongs to this user const existingPortfolio = await db.query.portfolio.findFirst({ where: and( - eq(portfolio.id, portfolioId), - eq(user.id, userId) + eq(portfolioUsers.portfolioId, portfolioId), + eq(portfolioUsers.userId, userId) ) }); @@ -50,19 +52,20 @@ export async function DELETE(request: NextRequest) { } // Delete the portfolio - await db.delete(portfolio).where(eq(portfolio.id, portfolioId)); + await db + .delete(portfolio) + .where(eq(portfolio.id, portfolioId)); - // Optionally, delete related records if needed - // await db.delete(someRelatedTable).where(eq(someRelatedTable.portfolioId, portfolioId)); + // Return success response + return new NextResponse( + JSON.stringify({ message: "Portfolio successfully deleted" }), + { status: 200 } + ); - // Return successful response - return new NextResponse(JSON.stringify({ message: "Portfolio deleted successfully" }), { - status: 200, - }); } catch (error) { console.error("Error deleting portfolio:", error); return new NextResponse( - JSON.stringify({ error: "Failed to delete portfolio" }), + JSON.stringify({ error: "Your API has Failed to delete the portfolio" }), { status: 500 } ); } diff --git a/src/app/portfolio/[slug]/(portfolio)/settings/PortfolioSettings.tsx b/src/app/portfolio/[slug]/(portfolio)/settings/PortfolioSettings.tsx index 942d015..ae6a3d3 100644 --- a/src/app/portfolio/[slug]/(portfolio)/settings/PortfolioSettings.tsx +++ b/src/app/portfolio/[slug]/(portfolio)/settings/PortfolioSettings.tsx @@ -128,6 +128,34 @@ const updateSettings = async ({ return response.json(); }; +async function deletePortfolio({ userId, portfolioId }: { + userId: bigint; + portfolioId: string; +}) { + try { + console.log("Attempting to DELETE portfolio by calling API:", { userId, portfolioId }); + const response = await fetch(`/api/portfolio/${portfolioId}`, { + method: "DELETE", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + userId: userId.toString(), + portfolioId: portfolioId, + }), + }); + + if (!response.ok) { + throw new Error("deletePortfolio has been called into action but utterly failed to do the API handoff"); + } + + return await response.json(); + } catch (error) { + console.error("Error after failing to the try to get a response:", error); + throw error; + } +} + export default function PortfolioSettings({ portfolioId, portfolioSettingsData, @@ -150,6 +178,17 @@ export default function PortfolioSettings({ }, }); + const { mutate: mutateDelete } = useMutation(deletePortfolio, { + onSuccess: () => { + setIsDeleteModalOpen(false); + console.log("Succesfully Deleted") + router.push('/home'); + }, + onError: (error) => { + console.error("Because the API hand off failed, we're right back here at the mutation station", error); + }, + }); + const [portfolioName, setPortfolioName] = useState( portfolioSettingsData.name ); @@ -185,39 +224,16 @@ export default function PortfolioSettings({ setIsDeleteModalOpen(true); } - async function handleDeleteConfirmation(portfolioId: number, userId: bigint) - { if (deleteConfirmationByName === portfolioName) - console.log('userId:', userId); - console.log('portfolioId:', portfolioId); - console.log('typeof userId:', typeof userId); - try { - const response = await fetch(`/api/portfolio/${portfolioId}`, { - method: "DELETE", - headers: {"Content-Type": "application/json", - }, - body: JSON.stringify({ - userId: typeof userId === 'bigint' ? userId.toString() : userId, - portfolioId: portfolioId - }) + function handleDeleteConfirmation() { + if (deleteConfirmationByName === portfolioSettingsData.name) { + mutateDelete({ + userId, + portfolioId, }); - - if (!response.ok) { - throw new Error('Failed to delete portfolio'); - } - else { - setIsDeleteModalOpen(false); - return await response.json(); - } - - } - - catch (error) { - console.error("The portfolio taunts you and tells you to try harder", error); - throw error; + console.log("succesfully called the mututate function") } } - // RENAMING FUNCTIONS // Change NAME functionality - changing state