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

56 lines
2.1 KiB
TypeScript

// app/api/options/[collection]/route.ts
import { NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
/**
* Generic option lists resolved by collection name.
* NOTE: laser_source and lens have their own dedicated routes.
*/
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, ctx: any) {
const { searchParams } = new URL(req.url);
const q = searchParams.get("q")?.trim() || "";
const limit = Number(searchParams.get("limit") || "400");
// Use a loose type for the 2nd arg to avoid Next 15's strict route signature check
const key = String(ctx?.params?.collection ?? "");
const cfg = MAP[key];
if (!cfg) {
// Unknown collection → return an empty list (avoids noisy 4xx)
return NextResponse.json({ data: [] });
}
// Build Directus URL (dummy base to use URL.searchParams ergonomically)
const u = new URL("http://x" + cfg.path);
u.searchParams.set("fields", cfg.fields);
u.searchParams.set("limit", String(limit));
if (q) u.searchParams.set("search", q);
try {
const { data } = await directusFetch<{ data: any[] }>(
u.pathname + "?" + u.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 }
);
}
}