From 9fc8a4b7c0c07a63d8cc39e630f96566bbe2c0b5 Mon Sep 17 00:00:00 2001
From: "DESKTOP-9FO96TP\\hehexd" <davidjakszta@outlook.de>
Date: Tue, 6 Jun 2023 19:51:52 +0200
Subject: [PATCH] commentCount works, Like a bit broken

---
 app/(content)/(home)/home/[postid]/page.tsx |  2 +
 app/(content)/(home)/home/page.tsx          |  3 +-
 app/api/likes/likeService.ts                | 79 +++++++++++++++++----
 app/api/likes/route.ts                      | 22 +++++-
 components/comment-button.tsx               |  2 +-
 components/like-button.tsx                  | 45 +++++++++++-
 6 files changed, 133 insertions(+), 20 deletions(-)

diff --git a/app/(content)/(home)/home/[postid]/page.tsx b/app/(content)/(home)/home/[postid]/page.tsx
index 95fe4db..f27b88f 100644
--- a/app/(content)/(home)/home/[postid]/page.tsx
+++ b/app/(content)/(home)/home/[postid]/page.tsx
@@ -26,6 +26,7 @@ export default async function PostDetail({ params }: { params: { postid: string
             },
             include: {
                 user: true,
+                Like: true
             },
         })
 
@@ -36,6 +37,7 @@ export default async function PostDetail({ params }: { params: { postid: string
             include: {
                 user: true,
                 Comment: true,
+                Like: true,
             },
         })
 
diff --git a/app/(content)/(home)/home/page.tsx b/app/(content)/(home)/home/page.tsx
index e749ae1..d3989d4 100644
--- a/app/(content)/(home)/home/page.tsx
+++ b/app/(content)/(home)/home/page.tsx
@@ -18,7 +18,8 @@ export default async function HomePage() {
       },
       include: {
         user: true,
-        Comment: true
+        Comment: true,
+        Like: true
       },
     })
 
diff --git a/app/api/likes/likeService.ts b/app/api/likes/likeService.ts
index 4353945..18f9807 100644
--- a/app/api/likes/likeService.ts
+++ b/app/api/likes/likeService.ts
@@ -14,35 +14,36 @@ export async function putLike(like: likeType): Promise<likeType | undefined> {
     try {
         const actualLike = await db.like.findFirst({
             where: {
-                id: like.id,
+                // id: like.id,
                 postId: like.postId,
                 userId: like.userId
             }
         })
-
+        console.log("found like: ", actualLike?.id)
         if (actualLike == null) {
-            console.log("like is null")
+            console.log("like is null", "postid:", like.postId, "so create it")
             throw Error("Message was not liked by this user")
         }
-
+        console.log("delete like", like.postId, "likeid: ", actualLike?.id)
         await db.like.delete({
             where: {
                 id: actualLike.id
             }
         })
 
-        const msg = await db.post.update({
-            where: {
-                id: like.postId
-            },
-            data: {
-                likeCount: { increment: -1 }
-            }
-        })
+        /*         const msg = await db.post.update({
+                    where: {
+                        id: like.postId
+                    },
+                    data: {
+                        likeCount: { increment: -1 }
+                    }
+                }) */
 
         return undefined;
 
     } catch {
+
         const createdLike = await db.like.create({
             data: {
                 postId: like.postId,
@@ -58,7 +59,59 @@ export async function putLike(like: likeType): Promise<likeType | undefined> {
                 likeCount: { increment: 1 }
             }
         })
+    }
+}
+
+export async function putLikeComment(like: likeType) {
+    // check if like exists by this user and for this post
+    // if exists delete
+    // if not create
+    try {
+        const actualLike = await db.like.findFirst({
+            where: {
+                // id: like.id,
+                postId: like.postId,
+                commentId: like.commentId,
+                userId: like.userId
+            }
+        })
+        console.log("found like: ", actualLike?.id)
+        if (actualLike == null) {
+            console.log("like is null", like.commentId, "so create it")
+            const createdLike = await db.like.create({
+                data: {
+                    postId: like.postId,
+                    userId: like.userId,
+                    commentId: like.commentId
+                }
+            })
+        } else {
+            console.log("delete like", like.commentId, "postid:", like.postId, "likeid: ", actualLike?.id)
+            await db.like.delete({
+                where: {
+                    id: actualLike.id
+                }
+            })
+        }
+
+        /*         const msg = await db.comment.update({
+                    where: {
+                        id: like.postId
+                    },
+                    data: {
+                        likeCount: { increment: -1 }
+                    }
+                }) */
+
+    } catch {
 
-        return createdLike
+        /*         const updatedMessage = await db.comment.update({
+                    where: {
+                        id: like.postId
+                    },
+                    data: {
+                        likeCount: { increment: 1 }
+                    }
+                }) */
     }
 }
\ No newline at end of file
diff --git a/app/api/likes/route.ts b/app/api/likes/route.ts
index cb35639..35619aa 100644
--- a/app/api/likes/route.ts
+++ b/app/api/likes/route.ts
@@ -1,15 +1,33 @@
 import { Prisma } from "@prisma/client";
 import { NextRequest, NextResponse } from "next/server";
-import { putLike } from "./likeService";
+import { putLike, putLikeComment } from "./likeService";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "@/lib/auth";
+import { revalidatePath } from "next/cache";
 
 type like = Prisma.LikeUncheckedCreateInput
 
 export async function PUT(req: NextRequest) {
+	const session = await getServerSession(authOptions);
+
+	if (!session) {
+		return NextResponse.json({ status: 401 });
+	}
+
+	const userId = session.user.id
+
 	const data: like = await req.json()
+	data.userId = userId;
 
 	console.log("router data: " + data, "status:")
 	try {
-		const msg = await putLike(data)
+		if (data.commentId == undefined) {
+			const msg = await putLike(data)
+		} else {
+			putLikeComment(data)
+		}
+		const path = req.nextUrl.searchParams.get('path') || '/';
+		revalidatePath(path);
 		return NextResponse.json({ status: 200, message: 'Like handled' })
 
 	} catch (error) {
diff --git a/components/comment-button.tsx b/components/comment-button.tsx
index f124f72..7a72cde 100644
--- a/components/comment-button.tsx
+++ b/components/comment-button.tsx
@@ -11,7 +11,7 @@ export default function CommentButton(props: { data: any }) {
 
     const postid = props.data.id
     const replyCount = props.data.Comment.length
-
+    //const replyCount = props.data.likeCount
     return (
         <div>
             <Link href={`/home/${postid}`}>
diff --git a/components/like-button.tsx b/components/like-button.tsx
index 1cbc47a..31c36cf 100644
--- a/components/like-button.tsx
+++ b/components/like-button.tsx
@@ -8,16 +8,33 @@ import { Button } from "./ui/button";
 
 type likeType = Prisma.LikeUncheckedCreateInput
 type postType = Prisma.PostUncheckedCreateInput
+type commentType = Prisma.CommentUncheckedCreateInput
+//type commentWithLikes = Prisma.CommentGetPayload<typeof commentWithPosts>
 
 export default function LikeButton(props: { data: any }) {
   const router = useRouter();
+  const likeCount = props.data.Like.length
+  /* const likeCount = props.data.likeCount */
+  const likeArray = props.data.Like
+  /*   const likeCount = countLikes(likeArray, props.data); */
+
+
+
+
 
   async function postLike(e: any) {
     e.preventDefault()
     const postLikeData = props.data;
     const likeData = {} as likeType
+
+    if (postLikeData.postId == undefined) {
+      likeData.postId = postLikeData.id!
+    } else {
+      likeData.postId = postLikeData.postId
+      likeData.commentId = postLikeData.id
+    }
     likeData.userId = postLikeData.userId
-    likeData.postId = postLikeData.id!
+    console.log(likeData.commentId)
 
     const response = await fetch('http://localhost:3000/api/likes', {
       method: 'PUT',
@@ -36,10 +53,32 @@ export default function LikeButton(props: { data: any }) {
     <div>
       <form onSubmit={postLike}>
         <Button type="submit" variant="ghost" size="lg" className="float-right" >
-          {props.data.likeCount}
+          {likeCount}
           <Icons.heart className="h-3 w-3" />
         </Button>
       </form>
     </div>
   )
-}
\ No newline at end of file
+}
+
+function countLikes(likeArray: any, msg: any): number {
+  let likeCount = 0;
+
+  if (msg.postId == undefined) {
+    likeArray.forEach(function (like: any) {
+      if (like.postId == undefined) {
+        likeCount++;
+      }
+    })
+  } else {
+    likeArray.forEach(function (like: any) {
+      if (like.postId != undefined) {
+        likeCount++;
+      }
+    })
+  }
+
+
+  return likeCount;
+}
+
-- 
GitLab