Skip to content

Commit

Permalink
add ability to unfollow
Browse files Browse the repository at this point in the history
  • Loading branch information
Zaid-maker committed Dec 17, 2023
1 parent 17f4d5c commit ff9bbe1
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 3 deletions.
18 changes: 17 additions & 1 deletion actions/follow.ts
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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");
}
};
4 changes: 2 additions & 2 deletions app/(browse)/[username]/_components/actions.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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}`)
)
Expand Down
40 changes: 40 additions & 0 deletions lib/follow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

0 comments on commit ff9bbe1

Please sign in to comment.