diff --git a/src/app/api/notes/route.ts b/src/app/api/notes/route.ts new file mode 100644 index 0000000..06cbee3 --- /dev/null +++ b/src/app/api/notes/route.ts @@ -0,0 +1,37 @@ +import prisma from "@/lib/db/prisma"; +import { createNoteSchema } from "@/lib/validation/note"; +import { auth } from "@clerk/nextjs"; + +export async function POST(req: Request) { + try { + const body = await req.json(); + + const parseResult = createNoteSchema.safeParse(body); + + if (!parseResult.success) { + console.error(parseResult.error); + return Response.json({ error: "Invalid input" }, { status: 400 }); + } + + const { title, content } = parseResult.data; + + const { userId } = auth(); + + if (!userId) { + return Response.json({ error: "Unauthorized" }, { status: 401 }); + } + + const note = await prisma.note.create({ + data: { + title, + content, + userId, + }, + }); + + return Response.json({ note }, { status: 201 }); + } catch (error) { + console.error(error); + return Response.json({ error: "Internal server error" }, { status: 500 }); + } +} diff --git a/src/components/AddNoteDialog.tsx b/src/components/AddNoteDialog.tsx new file mode 100644 index 0000000..cf3a4ad --- /dev/null +++ b/src/components/AddNoteDialog.tsx @@ -0,0 +1,103 @@ +import { CreateNoteSchema, createNoteSchema } from "@/lib/validation/note"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useRouter } from "next/navigation"; +import { useForm } from "react-hook-form"; +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "./ui/dialog"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "./ui/form"; +import { Input } from "./ui/input"; +import LoadingButton from "./ui/loading-button"; +import { Textarea } from "./ui/textarea"; + +interface AddNoteDialogProps { + open: boolean; + setOpen: (open: boolean) => void; +} + +export default function AddNoteDialog({ open, setOpen }: AddNoteDialogProps) { + const router = useRouter(); + + const form = useForm({ + resolver: zodResolver(createNoteSchema), + defaultValues: { + title: "", + content: "", + }, + }); + + async function onSubmit(input: CreateNoteSchema) { + try { + const response = await fetch("/api/notes", { + method: "POST", + body: JSON.stringify(input), + }); + if (!response.ok) throw Error("Status code: " + response.status); + form.reset(); + router.refresh(); + setOpen(false); + } catch (error) { + console.error(error); + alert("Something went wrong. Please try again."); + } + } + + return ( + + + + Add Note + +
+ + ( + + Note title + + + + + + )} + /> + ( + + Note content + +