rig_type route fix 2

This commit is contained in:
makearmy 2025-09-27 10:59:28 -04:00
parent 77e30981c3
commit e58f5aaff1

View file

@ -1,29 +1,50 @@
// app/api/options/rig_type/route.ts
import { NextRequest, NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
/**
* Returns [{ id, label }] from the Directus collection `user_rig_type`,
* sorted by the `sort` field. Keeping this dedicated route avoids
* depending on the generic [collection] mapping.
*/
const BASE = process.env.DIRECTUS_URL!;
const SUBMIT = process.env.DIRECTUS_TOKEN_SUBMIT || "";
const q = `/items/user_rig_type?fields=id,name&sort=sort`;
const url = (BASE || "").replace(/\/$/, "") + q;
async function tryFetch(headers: HeadersInit) {
const res = await fetch(url, { headers });
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 res = await directusFetch<{ data: { id: number | string; name: string }[] }>(
`/items/user_rig_type?fields=id,name&sort=sort`
);
// 1) Try with submit token
let { res, json, text } = await tryFetch({
Accept: "application/json",
...(SUBMIT ? { Authorization: `Bearer ${SUBMIT}` } : {}),
});
const items = (res?.data ?? []).map(({ id, name }) => ({
id,
label: name,
}));
// 2) If forbidden, retry anonymously (Public role)
if (res.status === 403) {
({ res, json, text } = await tryFetch({ Accept: "application/json" }));
}
return NextResponse.json({ data: items }, { status: 200 });
if (!res.ok) {
return NextResponse.json(
{ error: `Directus ${res.status}: ${text || res.statusText}` },
{ status: 500 }
);
}
const items: Array<{ id: string | number; name: string }> = json?.data ?? [];
const data = items.map(({ id, name }) => ({ id, label: name }));
return NextResponse.json({ data }, { status: 200 });
} catch (e: any) {
// Surface useful error text in case permissions are off
return NextResponse.json(
{ error: e?.message || "Failed to load rig types" },
{ status: 500 }
);
}
}