From 9515782f9a9dc2a009f4a4ee6f8e04fa76652cad Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yusuf=20Akg=C3=BCl?= <s86116@bht-berlin.de>
Date: Wed, 31 May 2023 15:37:10 +0200
Subject: [PATCH] fix following

---
 .../(user)/{ => [userid]}/followers/page.tsx  |  0
 .../{ => [userid]}/notifications/page.tsx     |  0
 components/following-button.tsx               | 68 ++++++++++---------
 components/following-users.tsx                | 54 ++++++++-------
 prisma/schema.prisma                          | 23 ++++---
 5 files changed, 78 insertions(+), 67 deletions(-)
 rename app/(content)/(user)/{ => [userid]}/followers/page.tsx (100%)
 rename app/(content)/(user)/{ => [userid]}/notifications/page.tsx (100%)

diff --git a/app/(content)/(user)/followers/page.tsx b/app/(content)/(user)/[userid]/followers/page.tsx
similarity index 100%
rename from app/(content)/(user)/followers/page.tsx
rename to app/(content)/(user)/[userid]/followers/page.tsx
diff --git a/app/(content)/(user)/notifications/page.tsx b/app/(content)/(user)/[userid]/notifications/page.tsx
similarity index 100%
rename from app/(content)/(user)/notifications/page.tsx
rename to app/(content)/(user)/[userid]/notifications/page.tsx
diff --git a/components/following-button.tsx b/components/following-button.tsx
index 8ad5ce1..71b56e7 100644
--- a/components/following-button.tsx
+++ b/components/following-button.tsx
@@ -1,48 +1,52 @@
-import { useState } from 'react';
 import { PrismaClient } from '@prisma/client';
+import { useState } from 'react';
+import { Button } from './ui/button';
 
 const prisma = new PrismaClient();
 
-export default function FollowButton({ userId, followerId }) {
+async function getFollower(userId: number, followerId: number) {
+  const follower = await prisma.follows.findFirst({
+    where: {
+      followerId: followerId,
+      followingId: userId,
+    },
+  });
+
+  return follower;
+}
+
+export default function FollowButton({ userId, followerId }: { userId: number; followerId: number }) {
   const [isFollowing, setIsFollowing] = useState(false);
 
   const handleFollow = async () => {
-    try {
-      // Überprüfen, ob der Benutzer bereits folgt
-      const isAlreadyFollowing = await prisma.followers.findFirst({
+    const follower = await getFollower(userId, followerId);
+
+    if (follower) {
+      // User is already following, so unfollow
+      await prisma.follows.delete({
         where: {
-          userId: followerId,
-          followerId: userId,
+          followerId_followingId: {
+            followerId: followerId,
+            followingId: userId,
+          },
         },
       });
-
-      if (isAlreadyFollowing) {
-        // Benutzer ist bereits ein Follower, daher folgen aufheben
-        await prisma.followers.delete({
-          where: {
-            userId: followerId,
-            followerId: userId,
-          },
-        });
-        setIsFollowing(false);
-      } else {
-        // Benutzer folgt noch nicht, daher folgen
-        await prisma.followers.create({
-          data: {
-            userId: followerId,
-            followerId: userId,
-          },
-        });
-        setIsFollowing(true);
-      }
-    } catch (error) {
-      console.error('Error following/unfollowing user:', error);
+      setIsFollowing(false);
+    } else {
+      // User is not following, so follow
+      await prisma.follows.create({
+        data: {
+          followerId: followerId,
+          followingId: userId,
+        },
+      });
+      setIsFollowing(true);
     }
   };
 
   return (
-    <button onClick={handleFollow}>
+    <Button onClick={handleFollow}>
       {isFollowing ? 'Unfollow' : 'Follow'}
-    </button>
+    </Button>
   );
-}
+}
\ No newline at end of file
diff --git a/components/following-users.tsx b/components/following-users.tsx
index cfc5c07..9c7d3c3 100644
--- a/components/following-users.tsx
+++ b/components/following-users.tsx
@@ -1,40 +1,44 @@
-"use-client"
-
-import { useRouter } from 'next/router';
-import { useEffect, useState } from 'react';
 import { PrismaClient } from '@prisma/client';
+import { useEffect, useState } from 'react';
 
 const prisma = new PrismaClient();
 
-export default function Followers() {
-  const router = useRouter();
-  const { userId } = router.query;
-  const [followers, setFollowers] = useState([]);
+interface Follower {
+  id: number;
+  name: string;
+  email: string | null;
+}
+
+export default function FollowersList({ userId }: { userId: number }) {
+  const [followers, setFollowers] = useState<Follower[]>([]);
 
-  //Zeigt die User an die Follower sind.
   useEffect(() => {
-    if (userId) {
-      prisma.user.findUnique({
-        where: { id: Number(userId) },
-        include: { followers: true },
-      })
-      .then((user) => {
-        setFollowers(user.followers);
-      })
-      .catch((error) => {
-        console.error('Error retrieving followers:', error);
+    async function fetchFollowers() {
+      const followersList = await prisma.follows.findMany({
+        where: {
+          followingId: userId,
+        },
+        include: {
+          follower: true,
+        },
       });
+
+      const filteredFollowers = followersList.map((follow) => {
+        const { id, name, email } = follow.follower;
+        return { id, name: name ?? "", email };
+      });
+
+      setFollowers(filteredFollowers);
     }
+
+    fetchFollowers();
   }, [userId]);
 
   return (
-    <div>
-      <h1>Followers</h1>
+    <ul>
       {followers.map((follower) => (
-        <div key={follower.id}>
-          <p>{follower.userName}</p>
-        </div>
+        <li key={follower.id}>{follower.name} ({follower.email})</li>
       ))}
-    </div>
+    </ul>
   );
 }
\ No newline at end of file
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 2e93abf..46c6b99 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -22,8 +22,19 @@ model User {
   Post    Post[]
   Comment Comment[]
   Like    Like[]
-  followers User[]   @relation("Followers", references: [id])
-  following User[]   @relation("Following", references: [id])
+
+  followers Follows[] @relation("follower")
+  following Follows[] @relation("following")
+}
+
+model Follows {
+  follower    User     @relation("following", fields: [followerId], references: [id])
+  followerId  Int
+  following   User     @relation("follower", fields: [followingId], references: [id])
+  followingId Int
+  createdAt   DateTime @default(now())
+
+  @@id([followerId, followingId])
 }
 
 model Post {
@@ -59,11 +70,3 @@ model Comment {
   post      Post     @relation(fields: [postId], references: [id], onDelete: Cascade)
   user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
 }
-
-model Follower {
-  id        Int    @id @default(autoincrement())
-  follower  User   @relation("Followers", fields: [followerId], references: [id])
-  followerId Int
-  following User   @relation("Following", fields: [followingId], references: [id])
-  followingId Int
-}
\ No newline at end of file
-- 
GitLab