makearmy-app/app/api/options/[collection]/route.ts
2025-09-22 13:49:35 -04:00

45 lines
2 KiB
TypeScript

// app/app/api/options/[collection]/route.ts
import { NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
type MapEntry = { path: string; fields: string; label: (x: any) => string };
const MAP: Record<string, MapEntry> = {
material: { path: "/items/material", fields: "id,name", label: (x) => String(x.name ?? x.id) },
material_coating: { path: "/items/material_coating", fields: "id,name", label: (x) => String(x.name ?? x.id) },
material_color: { path: "/items/material_color", fields: "id,name", label: (x) => String(x.name ?? x.id) },
material_opacity: { path: "/items/material_opacity", fields: "id,opacity", label: (x) => String(x.opacity ?? x.id) },
laser_software: { path: "/items/laser_software", fields: "id,name", label: (x) => String(x.name ?? x.id) },
// laser_source and lens have dedicated routes
};
export async function GET(req: Request, ctx: any) {
try {
const { searchParams } = new URL(req.url);
const key = ctx?.params?.collection as string;
const q = (searchParams.get("q") || "").trim().toLowerCase();
const limit = Number(searchParams.get("limit") || "500");
const cfg = MAP[key];
if (!cfg) {
return NextResponse.json({ error: "unsupported collection" }, { status: 400 });
}
const url = `${cfg.path}?fields=${encodeURIComponent(cfg.fields)}&limit=${limit}`;
const { data } = await directusFetch<{ data: any[] }>(url);
const list = Array.isArray(data) ? data : [];
const mapped = list.map((x) => ({
id: String(x.id),
label: cfg.label(x),
_s: Object.values(x).join(" ").toLowerCase(),
}));
const filtered = q ? mapped.filter((m) => m._s.includes(q)) : mapped;
filtered.sort((a, b) => a.label.localeCompare(b.label));
return NextResponse.json({ data: filtered.map(({ id, label }) => ({ id, label })) });
} catch (e: any) {
return NextResponse.json({ error: e?.message || "Failed to load options" }, { status: 500 });
}
}