-
Notifications
You must be signed in to change notification settings - Fork 0
feat(user): add follow/unfollow on profile pages #81
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| vi.mock("next/cache", () => ({ updateTag: vi.fn() })); | ||
| vi.mock("@/lib/auth/session", () => ({ | ||
| requireSession: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/db", () => ({ | ||
| prisma: { | ||
| user: { findUnique: vi.fn() }, | ||
| follow: { | ||
| upsert: vi.fn(), | ||
| deleteMany: vi.fn(), | ||
| }, | ||
| }, | ||
| })); | ||
|
|
||
| import { updateTag } from "next/cache"; | ||
| import { requireSession } from "@/lib/auth/session"; | ||
| import { prisma } from "@/lib/db"; | ||
| import { followUser, unfollowUser } from "../user-follows"; | ||
|
|
||
| const mockSession = vi.mocked(requireSession); | ||
| const mockUserFindUnique = vi.mocked(prisma.user.findUnique); | ||
| const mockUpsert = vi.mocked(prisma.follow.upsert); | ||
| const mockDeleteMany = vi.mocked(prisma.follow.deleteMany); | ||
| const mockUpdateTag = vi.mocked(updateTag); | ||
|
|
||
| const FOLLOWER_ID = "user-follower"; | ||
| const PROFILE_ID = "user-profile"; | ||
| const FOLLOWERS_TAG = `user:${PROFILE_ID}:followers`; | ||
| const FOLLOWING_TAG = `user:${FOLLOWER_ID}:following`; | ||
|
|
||
| function session(userId: string) { | ||
| return { | ||
| userId, | ||
| email: `${userId}@test.com`, | ||
| username: userId, | ||
| dateOfBirth: new Date("1990-01-01"), | ||
| }; | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe("followUser", () => { | ||
| it("upserts a follow row keyed by (followerId, followingId) for a valid target", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockUserFindUnique.mockResolvedValue({ id: PROFILE_ID } as never); | ||
| mockUpsert.mockResolvedValue({} as never); | ||
|
|
||
| await followUser(PROFILE_ID); | ||
|
|
||
| expect(mockUpsert).toHaveBeenCalledWith({ | ||
| where: { | ||
| followerId_followingId: { | ||
| followerId: FOLLOWER_ID, | ||
| followingId: PROFILE_ID, | ||
| }, | ||
| }, | ||
| create: { followerId: FOLLOWER_ID, followingId: PROFILE_ID }, | ||
| update: {}, | ||
| }); | ||
| }); | ||
|
|
||
| it("invalidates the target's followers tag and the viewer's following tag", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockUserFindUnique.mockResolvedValue({ id: PROFILE_ID } as never); | ||
| mockUpsert.mockResolvedValue({} as never); | ||
|
|
||
| await followUser(PROFILE_ID); | ||
|
|
||
| expect(mockUpdateTag).toHaveBeenCalledWith(FOLLOWERS_TAG); | ||
| expect(mockUpdateTag).toHaveBeenCalledWith(FOLLOWING_TAG); | ||
| }); | ||
|
|
||
| it("is idempotent — a second call upserts again without error", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockUserFindUnique.mockResolvedValue({ id: PROFILE_ID } as never); | ||
| mockUpsert.mockResolvedValue({} as never); | ||
|
|
||
| await followUser(PROFILE_ID); | ||
| await followUser(PROFILE_ID); | ||
|
|
||
| expect(mockUpsert).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| it("rejects self-follow before any DB call", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
|
|
||
| await expect(followUser(FOLLOWER_ID)).rejects.toThrow( | ||
| "Cannot follow yourself", | ||
| ); | ||
| expect(mockUserFindUnique).not.toHaveBeenCalled(); | ||
| expect(mockUpsert).not.toHaveBeenCalled(); | ||
| expect(mockUpdateTag).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("rejects when the target user does not exist", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockUserFindUnique.mockResolvedValue(null); | ||
|
|
||
| await expect(followUser(PROFILE_ID)).rejects.toThrow("User not found"); | ||
| expect(mockUpsert).not.toHaveBeenCalled(); | ||
| expect(mockUpdateTag).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("unfollowUser", () => { | ||
| it("calls deleteMany with the correct (followerId, followingId)", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockDeleteMany.mockResolvedValue({ count: 1 } as never); | ||
|
|
||
| await unfollowUser(PROFILE_ID); | ||
|
|
||
| expect(mockDeleteMany).toHaveBeenCalledWith({ | ||
| where: { followerId: FOLLOWER_ID, followingId: PROFILE_ID }, | ||
| }); | ||
| }); | ||
|
|
||
| it("invalidates both tags", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockDeleteMany.mockResolvedValue({ count: 1 } as never); | ||
|
|
||
| await unfollowUser(PROFILE_ID); | ||
|
|
||
| expect(mockUpdateTag).toHaveBeenCalledWith(FOLLOWERS_TAG); | ||
| expect(mockUpdateTag).toHaveBeenCalledWith(FOLLOWING_TAG); | ||
| }); | ||
|
|
||
| it("is idempotent — deleteMany returning count: 0 does not throw", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
| mockDeleteMany.mockResolvedValue({ count: 0 } as never); | ||
|
|
||
| await expect(unfollowUser(PROFILE_ID)).resolves.toBeUndefined(); | ||
| expect(mockUpdateTag).toHaveBeenCalledWith(FOLLOWERS_TAG); | ||
| expect(mockUpdateTag).toHaveBeenCalledWith(FOLLOWING_TAG); | ||
| }); | ||
|
|
||
| it("rejects self-unfollow before any DB call", async () => { | ||
| mockSession.mockResolvedValue(session(FOLLOWER_ID)); | ||
|
|
||
| await expect(unfollowUser(FOLLOWER_ID)).rejects.toThrow( | ||
| "Cannot unfollow yourself", | ||
| ); | ||
| expect(mockDeleteMany).not.toHaveBeenCalled(); | ||
| expect(mockUpdateTag).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| "use server"; | ||
|
|
||
| import { prisma } from "@/lib/db"; | ||
| import { requireSession } from "@/lib/auth/session"; | ||
| import { withActionLogging } from "@/lib/telemetry"; | ||
| import { userFollowersTag, userFollowingTag, invalidateTags } from "@/lib/deck/cache-tags"; | ||
|
|
||
| export const followUser = withActionLogging( | ||
| "user.follow", | ||
| async (targetUserId: string): Promise<void> => { | ||
| const session = await requireSession(); | ||
|
|
||
| if (session.userId === targetUserId) { | ||
| throw new Error("Cannot follow yourself"); | ||
| } | ||
|
|
||
| const target = await prisma.user.findUnique({ | ||
| where: { id: targetUserId }, | ||
| select: { id: true }, | ||
| }); | ||
|
|
||
| if (!target) { | ||
| throw new Error("User not found"); | ||
| } | ||
|
|
||
| await prisma.follow.upsert({ | ||
| where: { | ||
| followerId_followingId: { | ||
| followerId: session.userId, | ||
| followingId: targetUserId, | ||
| }, | ||
| }, | ||
| create: { followerId: session.userId, followingId: targetUserId }, | ||
| update: {}, | ||
| }); | ||
|
|
||
| invalidateTags([ | ||
| userFollowersTag(targetUserId), | ||
| userFollowingTag(session.userId), | ||
| ]); | ||
| }, | ||
| ); | ||
|
|
||
| export const unfollowUser = withActionLogging( | ||
| "user.unfollow", | ||
| async (targetUserId: string): Promise<void> => { | ||
| const session = await requireSession(); | ||
|
|
||
| if (session.userId === targetUserId) { | ||
| throw new Error("Cannot unfollow yourself"); | ||
| } | ||
|
|
||
| await prisma.follow.deleteMany({ | ||
| where: { followerId: session.userId, followingId: targetUserId }, | ||
| }); | ||
|
|
||
| invalidateTags([ | ||
| userFollowersTag(targetUserId), | ||
| userFollowingTag(session.userId), | ||
| ]); | ||
| }, | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| "use client"; | ||
|
|
||
| import { useOptimistic, useTransition } from "react"; | ||
| import { UserCheck, UserPlus } from "lucide-react"; | ||
| import { Button } from "@/components/ui/button"; | ||
| import { followUser, unfollowUser } from "@/app/_actions/user-follows"; | ||
|
|
||
| interface FollowButtonProps { | ||
| targetUserId: string; | ||
| initialIsFollowing: boolean; | ||
| followerCount: number; | ||
| } | ||
|
|
||
| interface FollowState { | ||
| isFollowing: boolean; | ||
| count: number; | ||
| } | ||
|
|
||
| export function FollowButton({ | ||
| targetUserId, | ||
| initialIsFollowing, | ||
| followerCount, | ||
| }: FollowButtonProps) { | ||
| const [isPending, startTransition] = useTransition(); | ||
| const [optimistic, setOptimistic] = useOptimistic<FollowState, boolean>( | ||
| { isFollowing: initialIsFollowing, count: followerCount }, | ||
| (state, next) => { | ||
| if (state.isFollowing === next) return state; | ||
| return { | ||
| isFollowing: next, | ||
| count: state.count + (next ? 1 : -1), | ||
| }; | ||
| }, | ||
| ); | ||
|
|
||
| function handleClick() { | ||
| const next = !optimistic.isFollowing; | ||
| startTransition(async () => { | ||
| setOptimistic(next); | ||
| try { | ||
| if (next) { | ||
| await followUser(targetUserId); | ||
| } else { | ||
| await unfollowUser(targetUserId); | ||
| } | ||
| } catch { | ||
| // useOptimistic rewinds on transition rejection; server state wins. | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| const Icon = optimistic.isFollowing ? UserCheck : UserPlus; | ||
| const label = optimistic.isFollowing ? "Unfollow" : "Follow"; | ||
|
|
||
| return ( | ||
| <div className="flex items-center gap-3"> | ||
| <span className="text-sm text-muted-foreground"> | ||
| <strong className="text-foreground">{optimistic.count}</strong>{" "} | ||
| {optimistic.count === 1 ? "follower" : "followers"} | ||
| </span> | ||
| <Button | ||
| type="button" | ||
| variant={optimistic.isFollowing ? "secondary" : "default"} | ||
| size="sm" | ||
| onClick={handleClick} | ||
| disabled={isPending} | ||
| aria-pressed={optimistic.isFollowing} | ||
| aria-label={optimistic.isFollowing ? "Unfollow user" : "Follow user"} | ||
| > | ||
| <Icon className="size-3.5" aria-hidden /> | ||
| {label} | ||
| </Button> | ||
| </div> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.