- createRequestSchema now requires employee_id to be a UUID-format string (was a free-text non-empty check), matching the new FK to Employee in schema.prisma. - createRequest() now returns a CreateRequestResult discriminated union and catches Prisma P2003 (FK violation), returning a friendly ok:false error instead of a raw 500 when employee_id does not reference an existing Employee. POST /api/requests branches on created.ok and returns 400 in that case. - tests/requests.test.ts: every test that used to POST a fake string employee_id (emp-1, emp-2) now creates a real Employee first via createTestEmployee() and uses its id, since employee_id is now a real FK. Added coverage for a syntactically invalid UUID and for a well-formed but non-existent UUID (expects the friendly 400 from the P2003 catch, not a raw 500) - the exact case this retrofit was meant to protect against.
51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { auth } from "@/auth";
|
|
import { createRequest, listRequests, validateCreateRequestInput } from "@/lib/requests";
|
|
|
|
// middleware.ts's config.matcher deliberately excludes /api from route
|
|
// protection (see its comment) — API routes verify the session themselves,
|
|
// here, rather than relying on middleware alone. Permission model is flat
|
|
// (CLAUDE.md): this only checks "logged in or not", no role/permission
|
|
// check.
|
|
export async function POST(request: Request): Promise<NextResponse> {
|
|
const session = await auth();
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
let body: unknown;
|
|
try {
|
|
body = await request.json();
|
|
} catch {
|
|
return NextResponse.json({ error: "Request body must be valid JSON" }, { status: 400 });
|
|
}
|
|
|
|
if (typeof body !== "object" || body === null) {
|
|
return NextResponse.json({ error: "Request body must be a JSON object" }, { status: 400 });
|
|
}
|
|
|
|
const { employee_id, type, reason } = body as Record<string, unknown>;
|
|
const validation = validateCreateRequestInput({ employee_id, type, reason });
|
|
|
|
if (!validation.ok) {
|
|
return NextResponse.json({ error: validation.error }, { status: 400 });
|
|
}
|
|
|
|
const created = await createRequest(validation.value);
|
|
if (!created.ok) {
|
|
return NextResponse.json({ error: created.error }, { status: 400 });
|
|
}
|
|
|
|
return NextResponse.json(created.value, { status: 201 });
|
|
}
|
|
|
|
export async function GET(): Promise<NextResponse> {
|
|
const session = await auth();
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const requests = await listRequests();
|
|
return NextResponse.json(requests, { status: 200 });
|
|
}
|