Skip to content

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

create page upload functionality (#219)

ggrandid924110bf3da
diff --git a/global.d.ts b/global.d.ts
index d8024e92..371e5834 100644
--- a/global.d.ts
+++ b/global.d.ts
@@ -1 +1,5 @@
-declare module '*.md'
+declare module '*.md' {
+ const text: string;
+ export default text;
+}
+
diff --git a/src/app/create/create-challenge-store.ts b/src/app/create/create-challenge-store.ts
index 37ea9e4c..535428b9 100644
--- a/src/app/create/create-challenge-store.ts
+++ b/src/app/create/create-challenge-store.ts
@@ -1,22 +1,19 @@
-import type { Difficulty } from '@prisma/client';
+import type { Prisma } from '@prisma/client';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
-interface CreateState {
- data:
- | {
- name: string;
- difficulty: Difficulty;
- shortDescription: string;
- description: string;
- prompt: string;
- }
- | undefined;
- setData: (data: NonNullable<CreateState['data']>) => void;
+export type CreateChallengeInputData = Pick<
+ Prisma.ChallengeCreateInput,
+ 'name' | 'difficulty' | 'shortDescription' | 'description' | 'prompt'
+>;
+
+export type CreateChallengeState = {
+ data: CreateChallengeInputData | undefined;
+ setData: (data: CreateChallengeInputData) => void;
clear: () => void;
-}
+};
-export const useCreateChallengeStore = create<CreateState>()(
+export const useCreateChallengeStore = create<CreateChallengeState>()(
persist(
(set, _get) => ({
data: undefined,
diff --git a/src/app/create/create-validator.ts b/src/app/create/create-validator.ts
new file mode 100644
index 00000000..487c6b45
--- /dev/null
+++ b/src/app/create/create-validator.ts
@@ -0,0 +1,23 @@
+import { z } from 'zod';
+import { type CreateChallengeState } from './create-challenge-store';
+
+type MapToZod<T> = {
+ [K in keyof T]: z.ZodType<T[K]>;
+};
+
+// TODO: Select better `.min(...).max(...)`
+export const createChallengeValidator = z.object<
+ MapToZod<NonNullable<CreateChallengeState['data']>>
+>({
+ name: z
+ .string()
+ .min(3, 'The name must be longer than 3 characters')
+ .max(30, 'The name must be shorter than 30 characters'),
+ prompt: z.string().max(65536),
+ difficulty: z.enum(['BEGINNER', 'EASY', 'MEDIUM', 'HARD', 'EXTREME']),
+ description: z.string().min(20, 'The description must be longer than 20 characters').max(65536),
+ shortDescription: z
+ .string()
+ .min(10, 'The short description must be longer than 10 characters')
+ .max(191, 'The short description must be shorter than 191 characters'),
+});
diff --git a/src/app/create/create.action.ts b/src/app/create/create.action.ts
new file mode 100644
index 00000000..da9e3e8f
--- /dev/null
+++ b/src/app/create/create.action.ts
@@ -0,0 +1,26 @@
+'use server';
+
+import { prisma } from '~/server/db';
+import { createChallengeValidator } from './create-validator';
+import { getServerAuthSession } from '~/server/auth';
+import { type CreateChallengeInputData } from './create-challenge-store';
+
+export async function uploadChallenge(data: CreateChallengeInputData) {
+ const parsedData = createChallengeValidator.parse(data);
+
+ const session = await getServerAuthSession();
+
+ if (!session) {
+ throw new Error('Unauthorized');
+ }
+
+ return prisma.challenge.create({
+ data: {
+ ...parsedData,
+ userId: session.user.id,
+ },
+ select: {
+ id: true,
+ },
+ });
+}
diff --git a/src/app/create/page.tsx b/src/app/create/page.tsx
index b792c683..a973ce0f 100644
--- a/src/app/create/page.tsx
+++ b/src/app/create/page.tsx
@@ -11,17 +11,15 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';
import { useToast } from '~/components/ui/use-toast';
import { ToastAction } from '@radix-ui/react-toast';
import { useRouter } from 'next/navigation';
-// @ts-ignore
import DEFAULT_DESCRIPTION from './default-description.md';
-// @ts-ignore
import DEFAULT_CHALLENGE_TEMPLATE from './default-challenge.md';
import { type Difficulty } from '@prisma/client';
import ExploreCardInputs from '~/components/create/explore-card-inputs';
import { useTheme } from 'next-themes';
-
import { RichMarkdownEditor } from '~/components/ui/rich-markdown-editor';
+import { createChallengeValidator } from './create-validator';
export default function CreateChallenge() {
const createChallengeStore = useCreateChallengeStore();
@@ -44,39 +42,7 @@ export default function CreateChallenge() {
const { toast } = useToast();
function onSubmit(prompt: string) {
- if (name.length < 3) {
- return toast({
- variant: 'destructive',
- title: 'The title length should be longer than 3 character',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
- }
-
- if (shortDescription.length < 10) {
- return toast({
- variant: 'destructive',
- title: 'The short description should be longer than 10 character',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
- }
-
- if (description.length < 20) {
- return toast({
- variant: 'destructive',
- title: 'The description should be longer than 20 character',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
- }
-
- if (difficulty === undefined) {
- return toast({
- variant: 'destructive',
- title: 'Please select a difficulty',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
- }
-
- createChallengeStore.setData({
+ const parseResult = createChallengeValidator.safeParse({
name,
description,
shortDescription,
@@ -84,6 +50,20 @@ export default function CreateChallenge() {
prompt,
});
+ if (!parseResult.success) {
+ for (const error of parseResult.error.errors) {
+ toast({
+ title: error.message,
+ variant: 'destructive',
+ action: <ToastAction altText="dismiss">Dismiss</ToastAction>,
+ });
+ }
+
+ return;
+ }
+
+ createChallengeStore.setData(parseResult.data);
+
router.push('/create/preview');
}
diff --git a/src/app/create/preview/page.tsx b/src/app/create/preview/page.tsx
index 0a1b9f12..edf4bcc6 100644
--- a/src/app/create/preview/page.tsx
+++ b/src/app/create/preview/page.tsx
@@ -8,22 +8,35 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';
import { Markdown } from '~/components/ui/markdown';
import ExploreCard from '~/components/explore/explore-card';
import { Button } from '~/components/ui/button';
+import { uploadChallenge } from '../create.action';
+import { useState } from 'react';
export default function PreviewCreatedChallenge() {
const createChallengeStore = useCreateChallengeStore();
-
const router = useRouter();
+ const [isRedirecting, setIsRedirecting] = useState(false);
if (createChallengeStore.data === undefined) {
- return router.replace('/create');
+ if (!isRedirecting) {
+ router.replace('/create');
+ }
+
+ // TODO: show some ui when isRedirecting
+ return;
}
- function publishChallenge() {
+ async function publishChallenge() {
console.log(createChallengeStore.data);
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const { id } = await uploadChallenge(createChallengeStore.data!);
+
+ // TODO: add guard in case the upload fails
createChallengeStore.clear();
- // router.push('/explore');
+ router.push(`/challenge/${id}`);
+
+ setIsRedirecting(true);
}
return (
@@ -84,8 +97,7 @@ export default function PreviewCreatedChallenge() {
<Button
size="sm"
className="cursor-pointer whitespace-nowrap bg-red-600 duration-300 hover:bg-red-500 dark:bg-red-400 dark:hover:bg-red-300"
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- onClick={() => router.push('/create')}
+ onClick={() => router.push('/create/')}
>
Continue Editing
</Button>
diff --git a/src/components/explore/explore-card.tsx b/src/components/explore/explore-card.tsx
index ea28f0c7..ce15da2f 100644
--- a/src/components/explore/explore-card.tsx
+++ b/src/components/explore/explore-card.tsx
@@ -17,9 +17,9 @@ import { Markdown } from '../ui/markdown';
import { getRelativeTime } from '~/utils/relativeTime';
import { type ExploreChallengeData } from './';
-interface Props {
+interface ExploreCardProps {
challenge: Pick<
- Awaited<ExploreChallengeData>[0],
+ ExploreChallengeData[0],
'difficulty' | 'name' | 'shortDescription' | '_count' | 'updatedAt'
>;
}
@@ -64,7 +64,7 @@ const COLORS_BY_DIFFICULTY = {
EXTREME: 'dark:group-hover:text-orange-300 group-hover:text-orange-600',
};
-const ExploreCard = ({ challenge }: Props) => {
+const ExploreCard = ({ challenge }: ExploreCardProps) => {
return (
<Card
className={`group relative overflow-hidden duration-300
diff --git a/tsconfig.json b/tsconfig.json
index 72c96c70..3f1aea75 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,11 +1,7 @@
{
"compilerOptions": {
"target": "es2017",
- "lib": [
- "dom",
- "dom.iterable",
- "esnext"
- ],
+ "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"checkJs": true,
"skipLibCheck": true,
@@ -22,9 +18,7 @@
"noUncheckedIndexedAccess": true,
"baseUrl": ".",
"paths": {
- "~/*": [
- "./src/*"
- ]
+ "~/*": ["./src/*"]
},
"plugins": [
{
@@ -48,8 +42,5 @@
"scripts/dl-monaco.mjs",
"./prisma/*.ts"
],
- "exclude": [
- "node_modules",
- "*.d.ts"
- ]
+ "exclude": ["node_modules"]
}