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

60 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// app/api/options/[collection]/route.ts
import { NextRequest, NextResponse } from "next/server";
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"] },
};
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 ?? "");
}
export async function GET(req: NextRequest, ctx: any) {
try {
const key = String(ctx?.params?.collection || "");
const cfg = MAP[key];
if (!cfg) return NextResponse.json({ data: [] });
const { searchParams } = new URL(req.url);
const q = (searchParams.get("q") || "").toLowerCase();
// 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 ?? [];
const mapped = items.map((it) => ({
id: String(it.id ?? it.submission_id ?? ""),
name: pickLabel(it, cfg.labelFields),
_search: `${Object.values(it).join(" ")}`.toLowerCase(),
})).filter((m) => !!m.id);
const filtered = q ? mapped.filter((m) => m._search.includes(q)) : mapped;
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 }
);
}
}