makearmy-app/app/api/options/laser_source/route.ts
2025-09-28 11:44:34 -04:00

42 lines
1.6 KiB
TypeScript

// app/api/options/laser_source/route.ts
export const dynamic = "force-dynamic";
import { NextRequest, NextResponse } from "next/server";
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
export async function GET(req: NextRequest) {
try {
const userAt = req.cookies.get("ma_at")?.value;
if (!userAt) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
const url = new URL(`${BASE}/items/laser_source`);
// IMPORTANT: schema uses submission_id as the FK target
url.searchParams.set("fields", "submission_id,make,model,nm");
url.searchParams.set("sort", "make,model");
const res = await fetch(String(url), {
headers: { Accept: "application/json", Authorization: `Bearer ${userAt}` },
cache: "no-store",
});
const text = await res.text().catch(() => "");
const json = text ? JSON.parse(text) : {};
if (!res.ok) {
return NextResponse.json({ error: `Directus ${res.status}: ${text || res.statusText}` }, { status: res.status });
}
const rows: Array<{ submission_id: string | number; make?: string; model?: string; nm?: string | number }> =
json?.data ?? [];
const data = rows
.map((r) => {
const parts = [r.make, r.model, r.nm ? `${r.nm}nm` : null].filter(Boolean);
return { id: r.submission_id, label: parts.join(" ") };
})
.filter((x) => x.label);
return NextResponse.json({ data });
} catch (e: any) {
return NextResponse.json({ error: e?.message || "Failed to load laser sources" }, { status: 500 });
}
}