makearmy-app/app/api/options/laser_source/route.ts

43 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-09-27 14:30:16 -04:00
// app/api/options/laser_source/route.ts
export const dynamic = "force-dynamic";
2025-09-22 13:47:00 -04:00
2025-09-27 14:30:16 -04:00
import { NextRequest, NextResponse } from "next/server";
2025-09-28 11:15:37 -04:00
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
2025-09-27 14:30:16 -04:00
export async function GET(req: NextRequest) {
2025-09-22 13:47:00 -04:00
try {
2025-09-28 11:44:34 -04:00
const userAt = req.cookies.get("ma_at")?.value;
if (!userAt) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
2025-09-28 11:15:37 -04:00
const url = new URL(`${BASE}/items/laser_source`);
2025-09-28 11:44:34 -04:00
// IMPORTANT: schema uses submission_id as the FK target
url.searchParams.set("fields", "submission_id,make,model,nm");
2025-09-28 11:15:37 -04:00
url.searchParams.set("sort", "make,model");
const res = await fetch(String(url), {
2025-09-28 11:44:34 -04:00
headers: { Accept: "application/json", Authorization: `Bearer ${userAt}` },
2025-09-28 11:15:37 -04:00
cache: "no-store",
});
const text = await res.text().catch(() => "");
2025-09-28 11:44:34 -04:00
const json = text ? JSON.parse(text) : {};
2025-09-28 11:15:37 -04:00
if (!res.ok) {
2025-09-28 11:44:34 -04:00
return NextResponse.json({ error: `Directus ${res.status}: ${text || res.statusText}` }, { status: res.status });
2025-09-22 13:47:00 -04:00
}
2025-09-28 11:44:34 -04:00
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);
2025-09-27 14:30:16 -04:00
return NextResponse.json({ data });
2025-09-22 13:47:00 -04:00
} catch (e: any) {
2025-09-28 11:15:37 -04:00
return NextResponse.json({ error: e?.message || "Failed to load laser sources" }, { status: 500 });
2025-09-22 13:47:00 -04:00
}
}