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,16 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body {
id: string;
name: string;
ipv4Subnet?: string;
ipv6Subnet?: string;
gateway?: string;
}
const schema = z.object({
id: z.string(),
name: z.string().min(2),
ipv4Subnet: z.string().optional(),
ipv6Subnet: z.string().optional(),
gateway: z.string().optional(),
});
export async function POST(request: NextRequest) {
const body: Body = await request.json();
const body = schema.parse(await request.json());
try {
const network = await prisma.network.update({
@@ -26,8 +27,10 @@ export async function POST(request: NextRequest) {
});
return NextResponse.json({ network }, { status: 201 });
} catch (error) {
console.error("Error editing network:", error);
return NextResponse.json({ error: "Failed to edit network" }, { status: 500 });
} 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 });
}
}