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

49 lines
1.9 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(/\/$/, "");
function buildPath(target?: string | null) {
// If your schema supports target filtering, add it here. Otherwise we return all.
const url = new URL(`${BASE}/items/laser_source`);
url.searchParams.set("fields", "id,name");
url.searchParams.set("sort", "name");
// Example (uncomment/adjust if you actually have a `target` field or relation):
// if (target) url.searchParams.set("filter[target][_eq]", target);
return String(url);
}
async function dFetch(bearer: string, target?: string | null) {
const res = await fetch(buildPath(target), {
headers: { Accept: "application/json", Authorization: `Bearer ${bearer}` },
cache: "no-store",
});
const text = await res.text().catch(() => "");
let json: any = null;
try { json = text ? JSON.parse(text) : null; } catch {}
return { res, json, text };
}
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 target = req.nextUrl.searchParams.get("target");
const r = await dFetch(userAt, target);
if (!r.res.ok) {
return NextResponse.json(
{ error: `Directus ${r.res.status}: ${r.text || r.res.statusText}` },
{ status: r.res.status }
);
}
const rows: Array<{ id: number | string; name: string }> = r.json?.data ?? [];
const data = rows.map(({ id, name }) => ({ id, name }));
return NextResponse.json({ data });
} catch (e: any) {
return NextResponse.json({ error: e?.message || "Failed to load laser sources" }, { status: 500 });
}
}