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

86 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-09-22 14:18:08 -04:00
// app/api/options/lens/route.ts
2025-09-27 14:30:16 -04:00
export const dynamic = "force-dynamic";
2025-09-22 15:15:06 -04:00
import { NextRequest, NextResponse } from "next/server";
2025-09-22 10:37:53 -04:00
const BASE = (
process.env.DIRECTUS_URL || process.env.NEXT_PUBLIC_API_BASE_URL || ""
).replace(/\/$/, "");
2025-09-22 10:37:53 -04:00
2025-09-27 14:30:16 -04:00
function buildPath(target?: string | null) {
// CO2 Gantry → focus lenses (name)
// everything else (Fiber/UV/CO2 Galvo) → scan lenses (field_size + focal_length)
const isGantry = target === "co2-gantry";
if (isGantry) {
const url = new URL(`${BASE}/items/laser_focus_lens`);
url.searchParams.set("fields", "id,name");
url.searchParams.set("sort", "name");
return String(url);
}
2025-09-27 14:30:16 -04:00
const url = new URL(`${BASE}/items/laser_scan_lens`);
url.searchParams.set("fields", "id,field_size,focal_length");
url.searchParams.set("sort", "field_size,focal_length");
2025-09-27 14:30:16 -04:00
return String(url);
2025-09-22 15:09:05 -04:00
}
async function dFetch(bearer: string, target?: string | null) {
2025-09-27 14:30:16 -04:00
const res = await fetch(buildPath(target), {
headers: { Accept: "application/json", Authorization: `Bearer ${bearer}` },
2025-09-27 14:30:16 -04:00
cache: "no-store",
});
const text = await res.text().catch(() => "");
let json: any = null;
try {
json = text ? JSON.parse(text) : null;
} catch {}
2025-09-27 14:30:16 -04:00
return { res, json, text };
2025-09-22 15:15:06 -04:00
}
2025-09-22 15:09:05 -04:00
2025-09-22 15:15:06 -04:00
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 });
}
2025-09-27 14:30:16 -04:00
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 }
);
2025-09-22 15:15:06 -04:00
}
const rows: any[] = r.json?.data ?? [];
const isGantry = target === "co2-gantry";
const data = rows.map((row) => {
if (isGantry) {
// Focus lens: label is just the stored name
return { id: row.id, name: row.name, label: row.name };
}
// Scan lens: label "300x300 mm | F420" etc
const fs =
row.field_size != null && row.field_size !== ""
? `${row.field_size} mm`
: "";
const fl =
row.focal_length != null && row.focal_length !== ""
? `F${row.focal_length}`
: "";
const label = [fs, fl].filter(Boolean).join(" | ");
return { id: row.id, name: label, label };
});
2025-09-27 14:30:16 -04:00
return NextResponse.json({ data });
2025-09-22 15:15:06 -04:00
} catch (e: any) {
return NextResponse.json(
{ error: e?.message || "Failed to load lenses" },
{ status: 500 }
);
}
}