Skip to content

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

chore: cleanup actions + cache (#864)

bautistaaa6c8d13bc899b
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
index 990c4676..d585fbc8 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
@@ -1,20 +1,17 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { useSession } from '@repo/auth/react';
+import { Button } from '@repo/ui/components/button';
+import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
+import { Input } from '@repo/ui/components/input';
+import { useToast } from '@repo/ui/components/use-toast';
import { useTheme } from 'next-themes';
-import { useRouter } from 'next/navigation';
+import { revalidateTag } from 'next/cache';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
-import { postSolution } from './_actions';
import { RichMarkdownEditor } from '~/components/rich-markdown-editor';
+import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';
import type { ChallengeSolution } from '../getSolutionRouteData';
-import { Button } from '@repo/ui/components/button';
-import { useToast } from '@repo/ui/components/use-toast';
-import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
-import { Input } from '@repo/ui/components/input';
-import {
- createNoProfanitySchema,
- createNoProfanitySchemaWithValidate,
-} from '~/utils/antiProfanityZod';
+import { createCacheKeyForSolutions, postSolution } from './_actions';
const getDefaultMarkdown = (solution: string) => `
## Thoughts
@@ -48,7 +45,6 @@ interface Props {
export function SolutionEditor({ dismiss, challenge }: Props) {
const session = useSession();
- const router = useRouter();
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -71,9 +67,6 @@ export function SolutionEditor({ dismiss, challenge }: Props) {
variant: 'success',
title: 'Your solution has been posted!',
});
-
- // refresh the router so we see latest data
- router.refresh();
} catch (error) {
toast({
variant: 'destructive',
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts
index 5c47bc4a..0995d494 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts
+++ b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts
@@ -1,17 +1,27 @@
'use server';
+import { getServerAuthSession } from '@repo/auth/server';
import { prisma } from '@repo/db';
import { revalidateTag } from 'next/cache';
+import { z } from 'zod';
+
+const submissionSchema = z.object({
+ challengeId: z.number(),
+ code: z.string(),
+ isSuccessful: z.boolean(),
+});
+
+export async function saveSubmission(challengeId: number, code: string, isSuccessful: boolean) {
+ submissionSchema.parse({ challengeId, code, isSuccessful });
+
+ const session = await getServerAuthSession();
+ if (!session) {
+ throw new Error('User not authenticated');
+ }
-export async function saveSubmission(
- challengeId: number,
- userId: string,
- code: string,
- isSuccessful: boolean,
-) {
await prisma.submission.create({
data: {
challengeId,
- userId,
+ userId: session.user.id,
code,
isSuccessful,
},
diff --git a/apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx b/apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx
index 5abecb9e..32b0bd4b 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx
@@ -29,7 +29,7 @@ export function Wrapper({ challenge }: { challenge: ChallengeRouteData }) {
success: !isSuccessful,
});
- return saveSubmission(challenge.id, session?.user.id!, code, isSuccessful);
+ return saveSubmission(challenge.id, code, isSuccessful);
}}
submissionDisabled={!session?.user}
settingsElement={<SettingsElements />}
diff --git a/apps/web/src/app/[locale]/challenge/increment.action.ts b/apps/web/src/app/[locale]/challenge/increment.action.ts
index c0d57298..2f9dc276 100644
--- a/apps/web/src/app/[locale]/challenge/increment.action.ts
+++ b/apps/web/src/app/[locale]/challenge/increment.action.ts
@@ -9,6 +9,11 @@ export async function incrementOrDecrementUpvote(
shouldIncrement: boolean,
) {
const session = await getServerAuthSession();
+
+ if (!session) {
+ throw new Error('User not authenticated');
+ }
+
const voteExists = await prisma.vote.findFirst({
where: {
rootType,
@@ -16,7 +21,7 @@ export async function incrementOrDecrementUpvote(
commentId: rootType === 'COMMENT' ? id : undefined,
sharedSolutionId: rootType === 'SHAREDSOLUTION' ? id : undefined,
submissionId: rootType === 'SUBMISSION' ? id : undefined,
- userId: session?.user.id,
+ userId: session?.user.id ?? '',
},
});
@@ -28,7 +33,7 @@ export async function incrementOrDecrementUpvote(
commentId: rootType === 'COMMENT' ? id : undefined,
sharedSolutionId: rootType === 'SHAREDSOLUTION' ? id : undefined,
submissionId: rootType === 'SUBMISSION' ? id : undefined,
- userId: session?.user.id,
+ userId: session.user.id,
},
});
}
diff --git a/apps/web/src/app/[locale]/explore/_components/explore-section.tsx b/apps/web/src/app/[locale]/explore/_components/explore-section.tsx
index 67502c6a..abb4c4c5 100644
--- a/apps/web/src/app/[locale]/explore/_components/explore-section.tsx
+++ b/apps/web/src/app/[locale]/explore/_components/explore-section.tsx
@@ -1,13 +1,12 @@
import type { Difficulty, Tags } from '@repo/db/types';
import Link from 'next/link';
+import { Carousel } from '~/components/carousel';
import { ExploreCard } from './explore-card';
-import type { ExploreChallengeData } from './explore.action';
+import { getChallengesByTagOrDifficulty } from './explore.action';
import { ViewMoreButton } from './view-more-button';
-import { Carousel } from '~/components/carousel';
interface SectionProps {
title: string;
- fetcher: (tagOrDifficulty: string, take: number) => ExploreChallengeData;
/**
* This is used by UI to apply the right colors. You still need to manually specify the
* `redirectRoute` for view-more button to work.
@@ -50,8 +49,8 @@ export const COLORS_BY_TAGS = {
EXTREME: 'dark:bg-purple-300 bg-purple-600/50',
} as const;
-export async function ExploreSection({ title, fetcher, tag, redirectRoute }: SectionProps) {
- const challenges = await fetcher(tag.trim().toUpperCase(), 6);
+export async function ExploreSection({ title, tag, redirectRoute }: SectionProps) {
+ const challenges = await getChallengesByTagOrDifficulty(tag.trim().toUpperCase(), 6);
return (
<div>
<div className="container flex items-center justify-between gap-3 px-4 pt-5">
diff --git a/apps/web/src/app/[locale]/explore/_components/index.tsx b/apps/web/src/app/[locale]/explore/_components/index.tsx
index 104cd515..39b463e0 100644
--- a/apps/web/src/app/[locale]/explore/_components/index.tsx
+++ b/apps/web/src/app/[locale]/explore/_components/index.tsx
@@ -31,60 +31,33 @@ export async function Explore() {
</p>
</div>
<Suspense fallback={<ExploreSectionSkeleton />}>
- <ExploreSection
- title="πŸ’• Most Popular"
- fetcher={getChallengesByTagOrDifficulty}
- tag="POPULAR"
- redirectRoute="/explore/popular"
- />
+ <ExploreSection title="πŸ’• Most Popular" tag="POPULAR" redirectRoute="/explore/popular" />
</Suspense>
<Suspense fallback={<ExploreSectionSkeleton />}>
- <ExploreSection
- title="πŸ”₯ Newest"
- fetcher={getChallengesByTagOrDifficulty}
- tag="NEWEST"
- redirectRoute="/explore/newest"
- />
+ <ExploreSection title="πŸ”₯ Newest" tag="NEWEST" redirectRoute="/explore/newest" />
</Suspense>
<Suspense fallback={<ExploreSectionSkeleton />}>
<ExploreSection
title="Great for Beginners"
- fetcher={getChallengesByTagOrDifficulty}
tag="BEGINNER"
redirectRoute="/explore/beginner"
/>
</Suspense>
<Suspense fallback={<ExploreSectionSkeleton />}>
- <ExploreSection
- title="Great for Learners"
- fetcher={getChallengesByTagOrDifficulty}
- tag="EASY"
- redirectRoute="/explore/easy"
- />
+ <ExploreSection title="Great for Learners" tag="EASY" redirectRoute="/explore/easy" />
</Suspense>
<Suspense fallback={<ExploreSectionSkeleton />}>
<ExploreSection
title="Great for Enthusiasts"
- fetcher={getChallengesByTagOrDifficulty}
tag="MEDIUM"
redirectRoute="/explore/medium"
/>
</Suspense>
<Suspense fallback={<ExploreSectionSkeleton />}>
- <ExploreSection
- title="Great for Experts"
- fetcher={getChallengesByTagOrDifficulty}
- tag="HARD"
- redirectRoute="/explore/hard"
- />
+ <ExploreSection title="Great for Experts" tag="HARD" redirectRoute="/explore/hard" />
</Suspense>
<Suspense fallback={<ExploreSectionSkeleton />}>
- <ExploreSection
- title="Great for Masters"
- fetcher={getChallengesByTagOrDifficulty}
- tag="EXTREME"
- redirectRoute="/explore/extreme"
- />
+ <ExploreSection title="Great for Masters" tag="EXTREME" redirectRoute="/explore/extreme" />
</Suspense>
<Footsies />
</div>
diff --git a/apps/web/src/app/[locale]/tracks/[slug]/page.tsx b/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
index 431acb49..507791c6 100644
--- a/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
+++ b/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
@@ -1,6 +1,7 @@
import { getServerAuthSession } from '@repo/auth/server';
import { redirect } from 'next/navigation';
import { isBetaUser } from '~/utils/server/is-beta-user';
+import { withUnstableCache } from '~/utils/withUnstableCache';
import { TrackDetail } from '../_components/track-details';
import { getTrackDetails } from '../_components/track.action';
@@ -25,7 +26,12 @@ export default async function Page({ params }: Props) {
}
export async function generateMetadata({ params: { slug } }: Props) {
- const track = await getTrackDetails(parseInt(slug));
+ const track = await withUnstableCache({
+ fn: getTrackDetails,
+ args: [parseInt(slug)],
+ keys: [`track-${slug}-detail`],
+ tags: [`track-${slug}-detail`],
+ });
if (!track) {
return {
diff --git a/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx b/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx
index 8099ca51..7d7ff1ce 100644
--- a/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx
@@ -2,7 +2,6 @@
import { Button } from '@repo/ui/components/button';
import { toast } from '@repo/ui/components/use-toast';
-import { useRouter } from 'next/navigation';
import type { enrollUserInTrack, unenrollUserFromTrack } from './track.action';
interface EnrollButtonProps {
@@ -12,14 +11,12 @@ interface EnrollButtonProps {
}
export function ActionButton({ action, text, trackId }: EnrollButtonProps) {
- const router = useRouter();
return (
<Button
variant="secondary"
onClick={async () => {
try {
await action(trackId);
- router.refresh();
toast({
title: 'Success',
variant: 'success',
diff --git a/apps/web/src/app/[locale]/tracks/_components/index.tsx b/apps/web/src/app/[locale]/tracks/_components/index.tsx
index 53f6eb3c..91e92575 100644
--- a/apps/web/src/app/[locale]/tracks/_components/index.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/index.tsx
@@ -24,7 +24,7 @@ export async function Tracks() {
tracks, offering a dynamic learning path for developers to enhance their skills.
</p>
</div>
- {session ? <EnrolledTrackSection /> : null}
+ <EnrolledTrackSection />
<TrackGrid />
</div>
);
diff --git a/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx b/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx
index 651d4a82..183ffafb 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx
@@ -1,4 +1,4 @@
-import { getServerAuthSession } from '@repo/auth/server';
+import { getServerAuthSession, type Session } from '@repo/auth/server';
import { prisma } from '@repo/db';
import Link from 'next/link';
import { Carousel } from '~/components/carousel';
@@ -6,7 +6,9 @@ import { PersonalTrackCard } from './personal-track-card';
import { Card } from '@repo/ui/components/card';
import type { HTMLAttributes } from 'react';
import clsx from 'clsx';
+import { withUnstableCache } from '~/utils/withUnstableCache';
+export const createEnrolledTrackCacheKey = (userId: string) => `user-${userId}-enrolled-tracks`;
const SkeletonTrack = ({ className, ...rest }: HTMLAttributes<HTMLDivElement>) => (
<Card
className={clsx(
@@ -25,11 +27,22 @@ const SkeletonTrack = ({ className, ...rest }: HTMLAttributes<HTMLDivElement>) =
);
export async function EnrolledTrackSection() {
- const tracks = await getUserEnrolledTracks();
+ const session = await getServerAuthSession();
+
+ if (!session) {
+ return null;
+ }
+
+ const tracks = await withUnstableCache({
+ fn: getUserEnrolledTracks,
+ args: [session],
+ keys: [createEnrolledTrackCacheKey(session.user.id)],
+ tags: [createEnrolledTrackCacheKey(session.user.id)],
+ });
return (
<div>
- {tracks.length ? (
+ {tracks.length > 0 ? (
<>
<div className="container flex items-center justify-between gap-3 px-4 pt-5">
<h2 className="relative text-3xl font-bold tracking-tight">
@@ -82,13 +95,12 @@ export type EnrolledTracks = Awaited<ReturnType<typeof getUserEnrolledTracks>>;
/**
* Fetches user enrolled tracks based on current session.
*/
-async function getUserEnrolledTracks() {
- const session = await getServerAuthSession();
+async function getUserEnrolledTracks(session: Session) {
return prisma.track.findMany({
where: {
enrolledUsers: {
some: {
- id: session?.user.id,
+ id: session.user.id,
},
},
},
@@ -99,7 +111,7 @@ async function getUserEnrolledTracks() {
include: {
submission: {
where: {
- userId: session?.user.id,
+ userId: session.user.id,
},
},
},
diff --git a/apps/web/src/app/[locale]/tracks/_components/track-grid.tsx b/apps/web/src/app/[locale]/tracks/_components/track-grid.tsx
index 7723e605..81a50ad0 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track-grid.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/track-grid.tsx
@@ -1,9 +1,15 @@
import { getServerAuthSession } from '@repo/auth/server';
import { prisma } from '@repo/db';
+import { withUnstableCache } from '~/utils/withUnstableCache';
import { TrackCard } from './track-card';
export async function TrackGrid() {
- const tracks = await getTracks();
+ const tracks = await withUnstableCache({
+ fn: getTracks,
+ args: [],
+ keys: ['tracks'],
+ tags: ['tracks'],
+ });
return (
<div className="container flex items-center justify-between gap-3">
<section className="grid w-full grid-flow-row grid-cols-1 gap-10 lg:grid-cols-2 xl:grid-cols-3">
diff --git a/apps/web/src/app/[locale]/tracks/_components/track.action.ts b/apps/web/src/app/[locale]/tracks/_components/track.action.ts
index 4faa0db8..85fb19fc 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track.action.ts
+++ b/apps/web/src/app/[locale]/tracks/_components/track.action.ts
@@ -2,7 +2,9 @@
import { getServerAuthSession } from '@repo/auth/server';
import { prisma } from '@repo/db';
+import { revalidateTag } from 'next/cache';
import { cache } from 'react';
+import { createEnrolledTrackCacheKey } from './track-enrolled-section';
/**
* Enrolls the session user in the track given a track id.
@@ -10,7 +12,11 @@ import { cache } from 'react';
*/
export async function enrollUserInTrack(id: number) {
const session = await getServerAuthSession();
- return prisma.track.update({
+ if (!session) {
+ throw new Error('User is not logged in');
+ }
+
+ await prisma.track.update({
where: {
id,
},
@@ -22,6 +28,10 @@ export async function enrollUserInTrack(id: number) {
},
},
});
+
+ revalidateTag(`track-${id}-detail`);
+ revalidateTag('tracks');
+ revalidateTag(createEnrolledTrackCacheKey(session.user.id));
}
/**
@@ -30,7 +40,11 @@ export async function enrollUserInTrack(id: number) {
*/
export async function unenrollUserFromTrack(id: number) {
const session = await getServerAuthSession();
- return prisma.track.update({
+ if (!session) {
+ throw new Error('User is not logged in');
+ }
+
+ await prisma.track.update({
where: {
id,
},
@@ -42,6 +56,10 @@ export async function unenrollUserFromTrack(id: number) {
},
},
});
+
+ revalidateTag(`track-${id}-detail`);
+ revalidateTag('tracks');
+ revalidateTag(createEnrolledTrackCacheKey(session.user.id));
}
/**
@@ -74,7 +92,7 @@ export const getTrackDetails = cache(async (id: number) => {
},
enrolledUsers: {
where: {
- id: session?.user.id,
+ id: session?.user.id ?? '',
},
select: {
id: true,
diff --git a/packages/monaco/src/index.tsx b/packages/monaco/src/index.tsx
index 595de4a3..ea86e8b6 100644
--- a/packages/monaco/src/index.tsx
+++ b/packages/monaco/src/index.tsx
@@ -74,8 +74,15 @@ export function CodePanel(props: CodePanelProps) {
const handleSubmit = async () => {
const hasErrors = tsErrors?.some((e) => e.length) ?? false;
- await props.saveSubmission(code ?? '', !hasErrors);
- router.refresh();
+ try {
+ await props.saveSubmission(code ?? '', !hasErrors);
+ } catch {
+ return toast({
+ variant: 'destructive',
+ title: 'Something went wrong while submitting your code.',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ }
if (hasErrors) {
toast({