fixes to rig type definitions causing 500 errors

This commit is contained in:
makearmy 2025-09-26 18:23:15 -04:00
parent 226fcc8013
commit 384f0a4958
2 changed files with 391 additions and 297 deletions

View file

@ -1,79 +1,95 @@
// app/api/my/rigs/route.ts
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { directusFetch } from "@/lib/directus";
// Change these if your collection/owner field differ
const BASE_COLLECTION = process.env.RIGS_COLLECTION || "rigs";
const OWNER_FIELD = process.env.RIGS_OWNER_FIELD || "owner";
const BASE = process.env.DIRECTUS_URL!;
// Pull the user's Directus access token from cookies (await to satisfy Next 15 typings)
async function bearerFromCookies() {
const jar = await cookies();
const at = jar.get("ma_at")?.value;
function bearerFromCookies() {
const store = cookies();
const at = store.get("ma_at")?.value;
if (!at) throw new Error("Not authenticated");
return `Bearer ${at}`;
}
// Resolve current Directus user id using their access token
async function getMeId(auth: string): Promise<string> {
const res = await directusFetch<{ data: { id: string } }>(
`/users/me?fields=id`,
{ headers: { Authorization: auth } }
);
const id = res?.data?.id;
if (!id) throw new Error("Unable to resolve current user id");
return id;
async function fetchJSON(path: string, init: RequestInit = {}) {
const res = await fetch(`${BASE}${path}`, init);
const text = await res.text();
let json: any = null;
try { json = text ? JSON.parse(text) : null; } catch {}
if (!res.ok) {
throw new Error(
`Directus error ${res.status}: ${text || res.statusText}`
);
}
return json ?? {};
}
// List rigs that belong to the current user
export async function GET(_req: NextRequest) {
export async function GET() {
try {
const auth = await bearerFromCookies();
const meId = await getMeId(auth);
const { data } = await directusFetch<{ data: any[] }>(
`/items/${BASE_COLLECTION}?filter[${OWNER_FIELD}][_eq]=${encodeURIComponent(
meId
)}&limit=200&sort=-date_created`,
{ headers: { Authorization: auth } }
);
return NextResponse.json({ ok: true, data });
} catch (err: any) {
return NextResponse.json(
{ error: err?.message || "List failed" },
{ status: 401 }
);
const auth = bearerFromCookies();
// Your Users role already restricts READ to owner == $CURRENT_USER
const out = await fetchJSON(`/items/user_rigs?fields=*,owner.username`, {
headers: { Authorization: auth, Accept: "application/json" },
});
return NextResponse.json(out);
} catch (e: any) {
return NextResponse.json({ error: e.message || String(e) }, { status: 401 });
}
}
// Create a new rig for the current user
export async function POST(req: NextRequest) {
const started = Date.now();
try {
const auth = await bearerFromCookies();
const meId = await getMeId(auth);
const auth = bearerFromCookies();
const body = await req.json();
// minimal validation keep it light, let Directus enforce the rest
const name = String(body?.name ?? "").trim();
const rig_type = String(body?.rig_type ?? "").trim();
// Ensure ownership is set to the current user
const payload = { ...body, [OWNER_FIELD]: meId };
if (!name) return NextResponse.json({ error: "name is required" }, { status: 400 });
if (!rig_type) return NextResponse.json({ error: "rig_type is required" }, { status: 400 });
const { data } = await directusFetch<{ data: any }>(
`/items/${BASE_COLLECTION}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: auth,
},
body: JSON.stringify(payload),
}
);
// Get the current user's id so we can set owner explicitly
const me = await fetchJSON(`/users/me`, {
headers: { Authorization: auth, Accept: "application/json" },
});
const ownerId = me?.data?.id;
if (!ownerId) throw new Error("Could not resolve current user id");
return NextResponse.json({ ok: true, data });
} catch (err: any) {
const payload = {
name,
rig_type,
owner: ownerId,
// pass through optional relational fields only if present (prevents FK violations)
laser_source: body?.laser_source ?? null,
laser_focus_lens: body?.laser_focus_lens ?? null,
laser_scan_lens: body?.laser_scan_lens ?? null,
laser_scan_lens_apt: body?.laser_scan_lens_apt ?? null,
laser_scan_lens_exp: body?.laser_scan_lens_exp ?? null,
laser_software: body?.laser_software ?? null,
notes: body?.notes ?? null,
};
const created = await fetchJSON(`/items/user_rigs`, {
method: "POST",
headers: {
Authorization: auth,
Accept: "application/json",
"Content-Type": "application/json",
Prefer: "return=representation",
},
body: JSON.stringify(payload),
});
return NextResponse.json(created);
} catch (e: any) {
return NextResponse.json(
{ error: err?.message || "Create failed" },
{ error: e?.message || "Failed to create rig" },
{ status: 400 }
);
} finally {
const ms = Date.now() - started;
if (ms) console.log(`[my/rigs POST] in ~${ms}ms`);
}
}