diff --git a/actions/follow.ts b/actions/follow.ts index fcd1f05..752adaf 100644 --- a/actions/follow.ts +++ b/actions/follow.ts @@ -1,6 +1,6 @@ "use server"; -import { followUser } from "@/lib/follow-service"; +import { followUser, unfollowUser } from "@/lib/follow-service"; import { revalidatePath } from "next/cache"; export const onFollow = async (id: string) => { @@ -18,3 +18,19 @@ export const onFollow = async (id: string) => { throw new Error("Interal Error"); } }; + +export const onUnfollow = async (id: string) => { + try { + const unfollowedUser = await unfollowUser(id); + + revalidatePath("/"); + + if (unfollowedUser) { + revalidatePath(`/${unfollowedUser.following.username}`); + } + + return unfollowedUser; + } catch (error) { + throw new Error("Internal Error"); + } +}; diff --git a/app/(browse)/[username]/_components/actions.tsx b/app/(browse)/[username]/_components/actions.tsx index 25cc407..01ec434 100644 --- a/app/(browse)/[username]/_components/actions.tsx +++ b/app/(browse)/[username]/_components/actions.tsx @@ -1,6 +1,6 @@ "use client"; -import { onFollow } from "@/actions/follow"; +import { onFollow, onUnfollow } from "@/actions/follow"; import { Button } from "@/components/ui/button"; import { useTransition } from "react"; import { toast } from "sonner"; @@ -25,7 +25,7 @@ export const Actions = ({ isFollowing, userId }: ActionsProps) => { const handleUnfollow = () => { startTransition(() => { - onFollow(userId) + onUnfollow(userId) .then((data) => toast.success(`You have unfollowed ${data.following.username}`) ) diff --git a/lib/follow-service.ts b/lib/follow-service.ts index 9a1f97b..a445b5a 100644 --- a/lib/follow-service.ts +++ b/lib/follow-service.ts @@ -69,3 +69,43 @@ export const followUser = async (id: string) => { return follow; }; + +export const unfollowUser = async (id: string) => { + const self = await getSelf(); + + const otherUser = await db.user.findUnique({ + where: { + id, + }, + }); + + if (!otherUser) { + throw new Error("User not found"); + } + + if (otherUser.id === self.id) { + throw new Error("Cannot unfollow yourself"); + } + + const existingFollow = await db.follow.findFirst({ + where: { + followerId: self.id, + followingId: otherUser.id, + }, + }); + + if (!existingFollow) { + throw new Error("Not following"); + } + + const follow = await db.follow.delete({ + where: { + id: existingFollow.id, + }, + include: { + following: true, + }, + }); + + return follow; +};