Skip to content

Commit

Permalink
added api routes , added zod validation for titel
Browse files Browse the repository at this point in the history
which should contain atleast 1 string
  • Loading branch information
abhishekHegde2000 committed Nov 23, 2023
1 parent 41dd75a commit 9064f8d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/app/api/notes/route.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
}
8 changes: 8 additions & 0 deletions src/lib/validation/note.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { z } from "zod";

export const createNoteSchema = z.object({
title: z.string().min(1, { message: "Title is required" }),
content: z.string().optional(),
});

export type CreateNoteSchema = z.infer<typeof createNoteSchema>;

0 comments on commit 9064f8d

Please sign in to comment.