Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

feat(web): migrate challenge bookmark action to tRPC (#1775)

bautistaaae32da38bcb9c
diff --git a/apps/web/src/app/challenge/_components/bookmark.action.ts b/apps/web/src/app/challenge/_components/bookmark.action.ts
deleted file mode 100644
index 389db807..00000000
--- a/apps/web/src/app/challenge/_components/bookmark.action.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-'use server';
-
-import { prisma } from '@repo/db';
-import { revalidateTag } from 'next/cache';
-import { auth } from '~/server/auth';
-import { createCacheKeyForBookmarksTab } from './bookmark.helpers';
-
-export async function addOrRemoveBookmark(
- challengeId: number,
- userId: string,
- shouldBookmark: boolean,
-) {
- const session = await auth();
- if (!session?.user?.id || userId !== session.user.id) return 'unauthorized';
- const bookmarkExists = await prisma.bookmark.findFirst({
- where: {
- challengeId,
- userId,
- },
- });
- if (!bookmarkExists && shouldBookmark) {
- await prisma.bookmark.create({
- data: {
- challengeId,
- userId,
- },
- });
- }
- if (bookmarkExists && !shouldBookmark) {
- await prisma.bookmark.delete({
- where: {
- id: bookmarkExists.id,
- },
- });
- }
-
- revalidateTag(createCacheKeyForBookmarksTab(userId), 'max');
-}
diff --git a/apps/web/src/app/challenge/_components/description/index.tsx b/apps/web/src/app/challenge/_components/description/index.tsx
index 08b84e82..93f78042 100644
--- a/apps/web/src/app/challenge/_components/description/index.tsx
+++ b/apps/web/src/app/challenge/_components/description/index.tsx
@@ -16,14 +16,15 @@ import { Markdown } from '@repo/ui/components/markdown';
import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
import { TypographyH3 } from '@repo/ui/components/typography/h3';
import { Bookmark as BookmarkIcon, Calendar, CheckCircle, Flag, Share } from '@repo/ui/icons';
+import { useMutation } from '@tanstack/react-query';
import clsx from 'clsx';
import { debounce } from 'lodash';
import { useRef, useState } from 'react';
import { type ChallengeRouteData } from '~/app/challenge/[slug]/getChallengeRouteData';
import { ReportDialog } from '~/components/ReportDialog';
import { ShareUrl } from '~/components/share-url';
+import { useTRPC } from '~/trpc/react';
import { getRelativeTimeStrict } from '~/utils/relativeTime';
-import { addOrRemoveBookmark } from '../bookmark.action';
import { UserBadge } from '../comments/enhanced-user-badge';
import { Vote } from '../vote';
import { Suggestions } from './suggestions';
@@ -42,17 +43,41 @@ export interface FormValues {
export function Description({ challenge }: DescriptionProps) {
const [hasBookmarked, setHasBookmarked] = useState(challenge.bookmark.length > 0);
const session = useSession();
+ const trpc = useTRPC();
+ const bookmarkMutation = useMutation(trpc.bookmark.addOrRemove.mutationOptions());
+
+ // Tracks the in-flight bookmark request and the most recently requested state
+ // per challenge, so a newer click can't race an earlier, still-pending request.
+ const bookmarkStateRef = useRef(new Map<number, { running: boolean; desired: boolean | null }>());
const debouncedBookmark = useRef(
- debounce(async (challengeId: number, userId: string, shouldBookmark: boolean) => {
- try {
- await addOrRemoveBookmark(challengeId, userId, shouldBookmark);
- setHasBookmarked(shouldBookmark);
- } catch (e) {
- console.error(e);
- // it errored so reverse the intended changes
- setHasBookmarked(!shouldBookmark);
- }
+ debounce((challengeId: number, shouldBookmark: boolean) => {
+ const state = bookmarkStateRef.current.get(challengeId) ?? { running: false, desired: null };
+ // Always remember the latest intent; if a request is already running for
+ // this challenge, the running loop will pick this value up when it finishes.
+ state.desired = shouldBookmark;
+ bookmarkStateRef.current.set(challengeId, state);
+ if (state.running) return;
+ state.running = true;
+
+ void (async () => {
+ try {
+ while (state.desired !== null) {
+ const next = state.desired;
+ state.desired = null;
+ try {
+ await bookmarkMutation.mutateAsync({ challengeId, shouldBookmark: next });
+ setHasBookmarked(next);
+ } catch (e) {
+ console.error(e);
+ // it errored so reverse the intended changes
+ setHasBookmarked(!next);
+ }
+ }
+ } finally {
+ state.running = false;
+ }
+ })();
}, 500),
).current;
@@ -168,13 +193,7 @@ export function Description({ challenge }: DescriptionProps) {
shouldBookmark = true;
setHasBookmarked(true);
}
- // TODO: Is this guaranteed to exist, or is userId actually optional?
- // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
- debouncedBookmark(challenge.id, session.data?.user?.id!, shouldBookmark)?.catch(
- (e) => {
- console.error(e);
- },
- );
+ debouncedBookmark(challenge.id, shouldBookmark);
}}
>
<BookmarkIcon className="h-4 w-4" />
diff --git a/apps/web/src/server/api/root.ts b/apps/web/src/server/api/root.ts
index ca8640e4..1cd47cfa 100644
--- a/apps/web/src/server/api/root.ts
+++ b/apps/web/src/server/api/root.ts
@@ -1,4 +1,5 @@
import { createCallerFactory, createTRPCRouter } from '~/server/api/trpc';
+import { bookmarkRouter } from './routers/bookmark';
import { notificationRouter } from './routers/notification';
/**
@@ -7,6 +8,7 @@ import { notificationRouter } from './routers/notification';
* All routers added in /api/routers should be manually added here.
*/
export const appRouter = createTRPCRouter({
+ bookmark: bookmarkRouter,
notification: notificationRouter,
});
diff --git a/apps/web/src/server/api/routers/bookmark.ts b/apps/web/src/server/api/routers/bookmark.ts
new file mode 100644
index 00000000..0d98350f
--- /dev/null
+++ b/apps/web/src/server/api/routers/bookmark.ts
@@ -0,0 +1,42 @@
+import { revalidateTag } from 'next/cache';
+import { z } from 'zod';
+
+import { createCacheKeyForBookmarksTab } from '~/app/challenge/_components/bookmark.helpers';
+import { createTRPCRouter, protectedProcedure } from '~/server/api/trpc';
+
+export const bookmarkRouter = createTRPCRouter({
+ /**
+ * Adds or removes a bookmark on a challenge for the current user.
+ *
+ * The bookmarked user is always derived from the session, so a client can only
+ * ever bookmark on its own behalf.
+ */
+ addOrRemove: protectedProcedure
+ .input(
+ z.object({
+ challengeId: z.number(),
+ shouldBookmark: z.boolean(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { challengeId, shouldBookmark } = input;
+ const userId = ctx.session.user.id;
+
+ if (shouldBookmark) {
+ // Idempotent: relies on the @@unique([userId, challengeId]) constraint so
+ // concurrent adds can't create duplicates.
+ await ctx.db.bookmark.upsert({
+ where: { userId_challengeId: { userId, challengeId } },
+ create: { userId, challengeId },
+ update: {},
+ });
+ } else {
+ // Idempotent: won't throw if the row was already removed concurrently.
+ await ctx.db.bookmark.deleteMany({
+ where: { userId, challengeId },
+ });
+ }
+
+ revalidateTag(createCacheKeyForBookmarksTab(userId), 'max');
+ }),
+});
diff --git a/packages/db/schema.prisma b/packages/db/schema.prisma
index 7fd9b5f5..8c7d204a 100644
--- a/packages/db/schema.prisma
+++ b/packages/db/schema.prisma
@@ -274,6 +274,7 @@ model Bookmark {
createdAt DateTime? @default(now())
+ @@unique([userId, challengeId])
@@index([userId])
@@index([challengeId])
}