makearmy-app/app/api/options/[collection]/route.ts
2025-09-22 11:47:22 -04:00

58 lines
2 KiB
TypeScript

// app/api/options/[collection]/route.ts
import { NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
// Generic collections handled by this route.
// (laser_source has its own route so it's NOT included here)
const MAP: Record<
string,
{ path: string; fields: string; label: (x: any) => string }
> = {
material: { path: "/items/material", fields: "id,name", label: (x) => x.name },
material_coating: { path: "/items/material_coating", fields: "id,name", label: (x) => x.name },
material_color: { path: "/items/material_color", fields: "id,name", label: (x) => x.name },
material_opacity: { path: "/items/material_opacity", fields: "id,opacity", label: (x) => String(x.opacity) },
laser_software: { path: "/items/laser_software", fields: "id,name", label: (x) => x.name },
};
export async function GET(
req: Request,
{ params }: { params: { collection: string } }
) {
const { searchParams } = new URL(req.url);
const q = searchParams.get("q")?.trim() || "";
const limit = Number(searchParams.get("limit") || "400");
const key = params.collection;
const cfg = MAP[key];
if (!cfg) {
// Unknown collection → empty list (prevents 4xx spam in logs)
return NextResponse.json({ data: [] });
}
// Build query (use a dummy base so URL can append params cleanly)
const url = new URL("http://x" + cfg.path);
url.searchParams.set("fields", cfg.fields);
url.searchParams.set("limit", String(limit));
if (q) url.searchParams.set("search", q);
try {
const { data } = await directusFetch<{ data: any[] }>(
url.pathname + "?" + url.searchParams.toString()
);
const out = (data || [])
.map((it) => ({
id: String(it.id),
label: cfg.label(it) ?? String(it.id),
}))
.sort((a, b) => a.label.localeCompare(b.label));
return NextResponse.json({ data: out });
} catch (e: any) {
return NextResponse.json(
{ error: e?.message || "Directus fetch failed" },
{ status: 500 }
);
}
}