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 { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body { const schema = z.object({
name: string; name: z.string(),
description: string; description: z.string(),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body: Body = await request.json(); const body = schema.parse(await request.json());
if (!body.name) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
const site = await prisma.site.create({ const site = await prisma.site.create({
data: { data: {
@ -24,6 +21,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ site }, { status: 201 }); return NextResponse.json({ site }, { status: 201 });
} catch (error: any) { } 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 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,19 +1,25 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
const schema = z.object({
siteId: z.string(),
});
export async function DELETE(request: NextRequest) { export async function DELETE(request: NextRequest) {
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
const siteId = searchParams.get("siteId"); const siteId = schema.parse({ siteId: searchParams.get("siteId") });
try { try {
const site = await prisma.site.delete({ const site = await prisma.site.delete({
where: { id: Number(siteId) }, where: { id: Number(siteId.siteId) },
}); });
return NextResponse.json(site); return NextResponse.json(site);
} catch (error) { } catch (error: any) {
console.error(error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: "Failed to delete site" }, { status: 500 }); return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,27 +1,35 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { Network } from "@/app/types"; import { z } from "zod/v4";
interface Body { const schema = z.object({
id: string; id: z.string(),
name: string; name: z.string(),
description: string; description: z.string(),
networks: Network[]; networks: z.array(z.object({
} id: z.string().optional(),
name: z.string().optional(),
ipv4Subnet: z.string().optional(),
ipv6Subnet: z.string().optional(),
gateway: z.string().optional(),
})),
});
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const body: Body = await request.json(); try {
const body = schema.parse(await request.json());
const { id, name, description, networks } = body; const { id, name, description, networks } = body;
try {
const site = await prisma.site.update({ const site = await prisma.site.update({
where: { id: Number(id) }, where: { id: Number(id) },
data: { name, description }, data: { name, description },
}); });
return NextResponse.json(site); return NextResponse.json(site);
} catch (error) { } catch (error: any) {
console.error(error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: "Failed to update site" }, { status: 500 }); return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,18 +1,19 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface QueryParams { const schema = z.object({
siteId: string; siteId: z.string(),
} });
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
const siteId = searchParams.get("siteId"); const siteId = schema.parse({ siteId: searchParams.get("siteId") });
try { try {
const site = await prisma.site.findUnique({ const site = await prisma.site.findUnique({
where: { where: {
id: Number(siteId), id: Number(siteId.siteId),
}, },
include: { include: {
networks: { networks: {
@ -24,8 +25,10 @@ export async function GET(request: NextRequest) {
}); });
return NextResponse.json({ site }); return NextResponse.json({ site });
} catch (error) { } catch (error: any) {
console.error("Error fetching site:", error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: "Failed to fetch site" }, { status: 500 }); return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -2,12 +2,19 @@ import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import Fuse from 'fuse.js'; import Fuse from 'fuse.js';
import { Site } from "@/app/types"; import { Site } from "@/app/types";
import { z } from "zod/v4";
const schema = z.object({
currentPage: z.string().optional(),
itemPerPage: z.string().optional(),
search: z.string().optional(),
});
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl; const { searchParams } = request.nextUrl;
const currentPage = Number(searchParams.get("currentPage")) || 1; const currentPage = Number(schema.parse({ currentPage: searchParams.get("currentPage") }).currentPage) || 1;
const itemPerPage = Number(searchParams.get("itemPerPage")) || 10; const itemPerPage = Number(schema.parse({ itemPerPage: searchParams.get("itemPerPage") }).itemPerPage) || 10;
const search = searchParams.get("search") || ""; const search = schema.parse({ search: searchParams.get("search") }).search || "";
try { try {
if (!search) { if (!search) {
@ -77,7 +84,9 @@ export async function GET(request: NextRequest) {
itemPerPage itemPerPage
}, { status: 200 }); }, { status: 200 });
} catch (error: any) { } catch (error: any) {
console.error("Search error:", error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,17 +1,18 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body { const schema = z.object({
id: string; id: z.string(),
siteId: string; siteId: z.string(),
name: string; name: z.string().min(2),
ipv4Subnet?: string; ipv4Subnet: z.string().optional(),
ipv6Subnet?: string; ipv6Subnet: z.string().optional(),
gateway?: string; gateway: z.string().optional(),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const body: Body = await request.json(); const body = schema.parse(await request.json());
try { try {
const network = await prisma.network.create({ const network = await prisma.network.create({
@ -25,8 +26,10 @@ export async function POST(request: NextRequest) {
}); });
return NextResponse.json({ network }, { status: 201 }); return NextResponse.json({ network }, { status: 201 });
} catch (error) { } catch (error: any) {
console.error("Error creating network:", error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: "Failed to create network" }, { status: 500 }); return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,20 +1,27 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
const schema = z.object({
networkId: z.string(),
});
export async function DELETE(request: NextRequest) { export async function DELETE(request: NextRequest) {
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
const networkId = searchParams.get("networkId"); const network = schema.parse({ networkId: searchParams.get("networkId") });
try { try {
await prisma.network.delete({ await prisma.network.delete({
where: { where: {
id: Number(networkId), id: Number(network.networkId),
}, },
}); });
return NextResponse.json({ message: "Network deleted successfully" }); return NextResponse.json({ message: "Network deleted successfully" });
} catch (error) { } catch (error: any) {
console.error("Error deleting network:", error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: "Failed to delete network" }, { status: 500 }); return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,16 +1,17 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body { const schema = z.object({
id: string; id: z.string(),
name: string; name: z.string().min(2),
ipv4Subnet?: string; ipv4Subnet: z.string().optional(),
ipv6Subnet?: string; ipv6Subnet: z.string().optional(),
gateway?: string; gateway: z.string().optional(),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const body: Body = await request.json(); const body = schema.parse(await request.json());
try { try {
const network = await prisma.network.update({ const network = await prisma.network.update({
@ -26,8 +27,10 @@ export async function POST(request: NextRequest) {
}); });
return NextResponse.json({ network }, { status: 201 }); return NextResponse.json({ network }, { status: 201 });
} catch (error) { } catch (error: any) {
console.error("Error editing network:", error); if(error instanceof z.ZodError) {
return NextResponse.json({ error: "Failed to edit network" }, { status: 500 }); return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
}
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -2,20 +2,17 @@ import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import { z } from "zod/v4";
interface Body { const schema = z.object({
token: string; token: z.string(),
old_password: string; old_password: z.string(),
password: string; password: z.string().min(8, "Password must be at least 8 characters long").max(32, "Password must be at most 32 characters long").regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, "Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character"),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body: Body = await request.json(); const body = schema.parse(await request.json());
if (!body.token || !body.old_password || !body.password) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
if(!process.env.JWT_SECRET) { if(!process.env.JWT_SECRET) {
return NextResponse.json({ error: "No JWT secret found" }, { status: 500 }); return NextResponse.json({ error: "No JWT secret found" }, { status: 500 });
@ -52,6 +49,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ message: "Password updated successfully" }, { status: 200 }); return NextResponse.json({ message: "Password updated successfully" }, { status: 200 });
} catch (error: any) { } 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 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,21 +1,18 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { z } from "zod/v4";
interface Body { const schema = z.object({
token: string; token: z.string(),
username: string; username: z.string().min(3, "Username must be at least 3 characters long").max(32, "Username must be at most 32 characters long"),
name: string; name: z.string().min(3, "Name must be at least 3 characters long").max(32, "Name must be at most 32 characters long"),
email: string; email: z.string().email("Invalid email address"),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body: Body = await request.json(); const body = schema.parse(await request.json());
if (!body.username || !body.name || !body.email) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
if(!process.env.JWT_SECRET) { if(!process.env.JWT_SECRET) {
return NextResponse.json({ error: "No JWT secret found" }, { status: 500 }); return NextResponse.json({ error: "No JWT secret found" }, { status: 500 });
@ -46,6 +43,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ message: "Profile updated successfully" }, { status: 200 }); return NextResponse.json({ message: "Profile updated successfully" }, { status: 200 });
} catch (error: any) { } 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 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,21 +1,18 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body { const schema = z.object({
username: string; username: z.string().min(3, "Username must be at least 3 characters long").max(32, "Username must be at most 32 characters long"),
name: string; name: z.string().min(3, "Name must be at least 3 characters long").max(32, "Name must be at most 32 characters long"),
email: string; email: z.string().email("Invalid email address"),
password: string; password: z.string().min(8, "Password must be at least 8 characters long").max(32, "Password must be at most 32 characters long").regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, "Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character"),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body: Body = await request.json(); const body = schema.parse(await request.json());
if (!body.username || !body.name || !body.email || !body.password) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
const user = await prisma.user.create({ const user = await prisma.user.create({
data: { data: {
@ -29,6 +26,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ user }, { status: 201 }); return NextResponse.json({ user }, { status: 201 });
} catch (error: any) { } 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 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -2,20 +2,17 @@ import { NextRequest, NextResponse } from "next/server";
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body { const schema = z.object({
email: string; email: z.string().email("Invalid email address"),
password: string; password: z.string().min(8, "Password must be at least 8 characters long").max(32, "Password must be at most 32 characters long").regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, "Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character"),
remember?: boolean; remember: z.boolean().optional(),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body: Body = await request.json(); const body = schema.parse(await request.json());
if (!body.email || !body.password) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
where: { where: {
@ -53,6 +50,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ message: "Login successful", token }, { status: 200 }); return NextResponse.json({ message: "Login successful", token }, { status: 200 });
} catch (error: any) { } 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 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

View File

@ -1,18 +1,15 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import prisma from "@/app/prisma"; import prisma from "@/app/prisma";
import { z } from "zod/v4";
interface Body { const schema = z.object({
token: string; token: z.string(),
} });
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body: Body = await request.json(); const body = schema.parse(await request.json());
if (!body.token) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
if(!process.env.JWT_SECRET) { if(!process.env.JWT_SECRET) {
return NextResponse.json({ error: "No JWT secret found" }, { status: 500 }); return NextResponse.json({ error: "No JWT secret found" }, { status: 500 });
@ -33,6 +30,9 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ message: "Valid", username: user.username, name: user.name, email: user.email }, { status: 200 }); return NextResponse.json({ message: "Valid", username: user.username, name: user.name, email: user.email }, { status: 200 });
} catch (error: any) { } 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 }); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
} }
} }

12
package-lock.json generated
View File

@ -20,7 +20,8 @@
"lucide-react": "^0.511.0", "lucide-react": "^0.511.0",
"next": "15.3.2", "next": "15.3.2",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0",
"zod": "^3.25.17"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.1.7", "@tailwindcss/postcss": "^4.1.7",
@ -2315,6 +2316,15 @@
"engines": { "engines": {
"node": ">=18" "node": ">=18"
} }
},
"node_modules/zod": {
"version": "3.25.17",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.17.tgz",
"integrity": "sha512-8hQzQ/kMOIFbwOgPrm9Sf9rtFHpFUMy4HvN0yEB0spw14aYi0uT5xG5CE2DB9cd51GWNsz+DNO7se1kztHMKnw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
} }
} }
} }

View File

@ -21,7 +21,8 @@
"lucide-react": "^0.511.0", "lucide-react": "^0.511.0",
"next": "15.3.2", "next": "15.3.2",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0",
"zod": "^3.25.17"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.1.7", "@tailwindcss/postcss": "^4.1.7",