feat: add Employee API routes

POST/GET /api/employees, same thin-route pattern as
src/app/api/requests/route.ts including the auth() 401 check
(middleware.ts excludes /api from page-route gating). POST also
surfaces createEmployee()'s FK-violation translation (nonexistent
managerId) as a 400, not a raw 500.
This commit is contained in:
2026-07-31 14:55:50 +07:00
parent eeaf946712
commit a8964a091a
+50
View File
@@ -0,0 +1,50 @@
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { createEmployee, listEmployees, validateCreateEmployeeInput } from "@/lib/employees";
// 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. Mirrors src/app/api/requests/route.ts's pattern.
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 { name, department, managerId } = body as Record<string, unknown>;
const validation = validateCreateEmployeeInput({ name, department, managerId });
if (!validation.ok) {
return NextResponse.json({ error: validation.error }, { status: 400 });
}
const created = await createEmployee(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 employees = await listEmployees();
return NextResponse.json(employees, { status: 200 });
}