62 lines
1.9 KiB
TypeScript
62 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 || process.env.NEXT_PUBLIC_API_BASE_URL || ""
|
|
).replace(/\/$/, "");
|
|
|
|
function buildPath() {
|
|
// This collection uses make/model (no `name` field)
|
|
const url = new URL(`${BASE}/items/laser_source`);
|
|
url.searchParams.set("fields", "id,make,model");
|
|
url.searchParams.set("sort", "make,model");
|
|
return String(url);
|
|
}
|
|
|
|
async function dFetch(bearer: string) {
|
|
const res = await fetch(buildPath(), {
|
|
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 r = await dFetch(userAt);
|
|
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: string | number; make?: string; model?: string }> =
|
|
r.json?.data ?? [];
|
|
|
|
// Compose human label from make + model
|
|
const data = rows.map(({ id, make, model }) => {
|
|
const label = [make, model].filter(Boolean).join(" ");
|
|
return { id, name: label, label };
|
|
});
|
|
|
|
return NextResponse.json({ data });
|
|
} catch (e: any) {
|
|
return NextResponse.json(
|
|
{ error: e?.message || "Failed to load laser sources" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|