Zod for API Routes

This commit is contained in:
headlesdev
2025-05-21 23:32:21 +02:00
parent e7d56fa496
commit 065ff7190a
15 changed files with 169 additions and 119 deletions

View File

@@ -1,18 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body {
name: string;
description: string;
}
const schema = z.object({
name: z.string(),
description: z.string(),
});
export async function POST(request: NextRequest) {
try {
const body: Body = await request.json();
if (!body.name) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
const body = schema.parse(await request.json());
const site = await prisma.site.create({
data: {
@@ -24,6 +21,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ site }, { status: 201 });
} catch (error: any) {
if(error instanceof z.ZodError) {
return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}