POST/GET /api/assignments mirror the existing entity route pattern (auth-gated, thin handler delegating to src/lib/assignments.ts). PATCH /api/assignments/[id] is the first dynamic-segment route in the codebase, per the stakeholder-confirmed convention (docs/asset-license-management.md) of update routes being PATCH /api/<entity>/[id] rather than an action-based sub-route.
52 lines
1.7 KiB
TypeScript
52 lines
1.7 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { auth } from "@/auth";
|
|
import {
|
|
createAssignment,
|
|
listAssignments,
|
|
validateCreateAssignmentInput,
|
|
} from "@/lib/assignments";
|
|
|
|
// Mirrors src/app/api/licenses/route.ts's pattern — middleware.ts excludes
|
|
// /api from route protection, so this checks the session itself. Flat
|
|
// permission model (CLAUDE.md): only "logged in or not", no role 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 { employeeId, assetItemId, licenseId } = body as Record<string, unknown>;
|
|
const validation = validateCreateAssignmentInput({ employeeId, assetItemId, licenseId });
|
|
|
|
if (!validation.ok) {
|
|
return NextResponse.json({ error: validation.error }, { status: 400 });
|
|
}
|
|
|
|
const created = await createAssignment(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 assignments = await listAssignments();
|
|
return NextResponse.json(assignments, { status: 200 });
|
|
}
|