diff --git a/app/api/servers/route.ts b/app/api/servers/route.ts new file mode 100644 index 0000000..7dddb43 --- /dev/null +++ b/app/api/servers/route.ts @@ -0,0 +1,42 @@ +import { v4 as uuidv4 } from "uuid"; +import { NextResponse } from "next/server"; +import { MemberRole } from "@prisma/client"; + +import { currentProfile } from "@/lib/current-profile"; +import { db } from "@/lib/db"; + + +export async function POST(req: Request) { + try { + const { name, imageUrl } = await req.json(); + const profile = await currentProfile(); + + if (!profile) { + return new NextResponse("Unauthorized", { status: 401 }); + } + + const server = await db.server.create({ + data: { + profileId: profile.id, + name, + imageUrl, + inviteCode: uuidv4(), + channels: { + create: [ + { name: "general", profileId: profile.id } + ], + }, + members: { + create: [ + { profileId: profile.id, role: MemberRole.ADMIN } + ] + } + } + }) + + return NextResponse.json({ server }); + } catch (error) { + console.log("[SERVER POST]", error); + return new NextResponse("Internal Error", { status: 500 }); + } +} \ No newline at end of file diff --git a/components/modals/initial-modal.tsx b/components/modals/initial-modal.tsx index 1de2efc..4c84b42 100644 --- a/components/modals/initial-modal.tsx +++ b/components/modals/initial-modal.tsx @@ -1,5 +1,6 @@ "use client"; +import axios from "axios"; import * as z from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; @@ -24,6 +25,7 @@ import{ import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { FileUpload } from "@/components/file-upload"; +import { useRouter } from "next/navigation"; const formSchema = z.object({ name: z.string().min(1, { @@ -37,6 +39,8 @@ const formSchema = z.object({ export const InitialModal = () => { const [isMounted, setIsMounted] = useState(false); + const router = useRouter(); + useEffect(() => { setIsMounted(true); }, []); @@ -52,7 +56,15 @@ export const InitialModal = () => { const isLoading = form.formState.isSubmitting; const onSubmit = async (values: z.infer) => { - console.log(values); + try { + await axios.post("/api/servers", values); + + form.reset(); + router.refresh(); + window.location.reload(); + } catch (error) { + console.error(error); + } } if (!isMounted) { diff --git a/lib/current-profile.ts b/lib/current-profile.ts new file mode 100644 index 0000000..bd5830d --- /dev/null +++ b/lib/current-profile.ts @@ -0,0 +1,19 @@ +import { auth } from "@clerk/nextjs"; + +import { db } from "@/lib/db"; + +export const currentProfile = async () => { + const { userId } = auth(); + + if (!userId) { + return null; + } + + const profile = await db.profile.findUnique({ + where: { + userId + }, + }); + + return profile; +} \ No newline at end of file