makearmy-app/app/api/options/[collection]/route.ts

61 lines
2.7 KiB
TypeScript
Raw Normal View History

// app/api/options/[collection]/route.ts
import { NextRequest, NextResponse } from "next/server";
2025-09-22 10:37:53 -04:00
import { directusFetch } from "@/lib/directus";
// Expandable label-field preferences per collection.
// Well try each key in order until we find a value.
const MAP: Record<
string,
{ coll: string; labelFields: string[] }
> = {
material: { coll: "material", labelFields: ["name", "label", "title"] },
material_coating: { coll: "material_coating", labelFields: ["name", "label", "title"] },
material_color: { coll: "material_color", labelFields: ["name", "label", "title"] },
material_opacity: { coll: "material_opacity", labelFields: ["name", "label", "title", "value"] },
laser_software: { coll: "laser_software", labelFields: ["name", "label", "title"] },
// NEW: Galvo scan head aperture list
laser_scan_lens_apt: { coll: "laser_scan_lens_apt", labelFields: ["name", "label", "title", "aperture_mm", "size_mm", "value"] },
// NEW: Beam expander multiplier list
laser_scan_lens_exp: { coll: "laser_scan_lens_exp", labelFields: ["name", "label", "title", "multiplier", "value"] },
2025-09-22 13:47:00 -04:00
};
2025-09-22 10:37:53 -04:00
function pickLabel(it: any, candidates: string[]) {
for (const k of candidates) if (it?.[k] != null && it[k] !== "") return String(it[k]);
// fallback: try some common numeric-ish fields if present
if (it?.value != null) return String(it.value);
return String(it?.name ?? it?.label ?? it?.title ?? it?.id ?? "");
}
2025-09-22 13:47:00 -04:00
export async function GET(req: NextRequest, ctx: any) {
try {
const key = String(ctx?.params?.collection || "");
2025-09-22 13:47:00 -04:00
const cfg = MAP[key];
if (!cfg) return NextResponse.json({ data: [] });
const { searchParams } = new URL(req.url);
const q = (searchParams.get("q") || "").toLowerCase();
2025-09-22 13:47:00 -04:00
// Keep fields=* so we can build a friendly label from whatever exists
const url = `/items/${cfg.coll}?fields=*&limit=500`;
const res = await directusFetch<{ data: any[] }>(url);
const items = res?.data ?? [];
2025-09-22 13:47:00 -04:00
const mapped = items.map((it) => ({
id: String(it.id ?? it.submission_id ?? ""),
2025-09-27 14:30:16 -04:00
name: pickLabel(it, cfg.labelFields),
_search: `${Object.values(it).join(" ")}`.toLowerCase(),
})).filter((m) => !!m.id);
2025-09-22 13:47:00 -04:00
const filtered = q ? mapped.filter((m) => m._search.includes(q)) : mapped;
2025-09-27 14:30:16 -04:00
filtered.sort((a, b) => (a.name ?? "").localeCompare(b.name ?? ""));
return NextResponse.json({ data: filtered.map(({ _search, ...r }) => r) });
} catch (err: any) {
return NextResponse.json(
{ error: err?.message || "options error" },
{ status: 500 }
);
2025-09-22 10:37:53 -04:00
}
}