From e58f5aaff16d9632fe99a8431e21cc36e835c83f Mon Sep 17 00:00:00 2001 From: makearmy Date: Sat, 27 Sep 2025 10:59:28 -0400 Subject: [PATCH] rig_type route fix 2 --- app/api/options/rig_type/route.ts | 51 ++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/app/api/options/rig_type/route.ts b/app/api/options/rig_type/route.ts index 5b22cff2..903e557f 100644 --- a/app/api/options/rig_type/route.ts +++ b/app/api/options/rig_type/route.ts @@ -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 } ); } } +