feat(api): wire zod input validation, migrate /api/events POST as pattern

zod has been a phantom dependency (in package.json, used in 0 files).
Every POST/PATCH route hand-rolled `if (!body.name?.trim()) return 400`
checks instead of validating at the boundary, contrary to CLAUDE.md's
"Validate inputs at system boundaries" rule.

Add a readJsonBody<T>(req, schema) helper in lib/api/route-helpers.ts
that mirrors the readIdParam shape — returns parsed+typed data or a
400 NextResponse the caller passes through. Includes a friendlyZodMessage
translation so zod's default "Invalid input: expected string, received
undefined" for missing fields becomes "<field> is required".

Migrate /api/events POST as the first user. Schema is colocated with
the handler. Other routes follow the same pattern in subsequent commits.

Note: dev-server HMR can be sticky for route-helper imports — the
prod build picks the new helper up correctly. Verified with tsc 0
and prod build succeeded; smoke 18/18.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-04-26 11:09:42 +02:00
1 parent 8d22c160e4
commit 2fd258339a
2 files changed
+64 -22

No files matched your search

+21 -21
View File
@@ -4,6 +4,19 @@ import { events } from "@/db/schema";
import { DEFAULT_USER_ID } from "@/lib/constants";
import { EVENT_STATUS } from "@/lib/constants/statuses";
import { getEvents } from "@/db/queries/events";
import { readJsonBody, z } from "@/lib/api/route-helpers";
// readJsonBody auto-translates zod's "invalid_type for missing field"
// into "<field> is required", so plain .min(1) covers both the missing
// and empty/whitespace cases.
const CreateEventBody = z.object({
name: z.string().trim().min(1, "name is required"),
type: z.string().trim().min(1, "type is required"),
description: z.string().trim().optional(),
url: z.string().trim().optional(),
deadline: z.string().optional(),
category: z.string().trim().optional(),
});
export async function GET() {
const items = await getEvents();
@@ -11,33 +24,20 @@ export async function GET() {
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { name, type, description, url, deadline, category } = body as {
name?: string;
type?: string;
description?: string;
url?: string;
deadline?: string;
category?: string;
};
if (!name?.trim()) {
return NextResponse.json({ error: "name is required" }, { status: 400 });
}
if (!type?.trim()) {
return NextResponse.json({ error: "type is required" }, { status: 400 });
}
const dataOrResp = await readJsonBody(req, CreateEventBody);
if (dataOrResp instanceof NextResponse) return dataOrResp;
const { name, type, description, url, deadline, category } = dataOrResp;
const [created] = await db
.insert(events)
.values({
userId: DEFAULT_USER_ID,
name: name.trim(),
type: type.trim().toLowerCase(),
description: description?.trim() || null,
url: url?.trim() || null,
name,
type: type.toLowerCase(),
description: description || null,
url: url || null,
deadline: deadline ? new Date(deadline) : null,
category: category?.trim().toLowerCase() || null,
category: category?.toLowerCase() || null,
status: EVENT_STATUS.ACTIVE,
source: "cockpit-ui",
})
+43 -1
View File
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { z, type ZodSchema } from "zod";
import { isValidUuid } from "@/lib/utils";
/**
@@ -21,3 +22,44 @@ export async function readIdParam(
}
return id;
}
/**
* Read + validate a JSON request body against a zod schema. Caller gets
* back either the parsed (and typed) data, or a 400 NextResponse with a
* single human-readable error message — same callsite shape as
* readIdParam so handlers branch the same way.
*
* const dataOrResp = await readJsonBody(req, CreateEventBody);
* if (dataOrResp instanceof NextResponse) return dataOrResp;
* const { name, type } = dataOrResp;
*/
export async function readJsonBody<T>(
req: NextRequest,
schema: ZodSchema<T>,
): Promise<T | NextResponse> {
const raw = await req.json().catch(() => null) as unknown;
if (raw === null) {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const parsed = schema.safeParse(raw);
if (!parsed.success) {
return NextResponse.json({ error: friendlyZodMessage(parsed.error) }, { status: 400 });
}
return parsed.data;
}
/** Pick a human-readable message from the first zod issue, with a
* special case for "field is missing" (zod's default there reads as
* "Invalid input: expected string, received undefined"). */
function friendlyZodMessage(error: z.ZodError): string {
const issue = error.issues[0];
if (!issue) return "Invalid input";
if (issue.code === "invalid_type" && issue.path.length > 0) {
return `${issue.path.join(".")} is required`;
}
return issue.message;
}
// Re-export zod so route files don't have to import from "zod" + this
// helper file — keeps the validation surface in one place.
export { z };