rigs route finalized

This commit is contained in:
makearmy 2025-09-29 22:04:25 -04:00
parent 9607830c2f
commit d142ba464a

View file

@ -9,22 +9,10 @@ function bad(msg: string, code = 400) {
return NextResponse.json({ error: msg }, { status: code });
}
function takeRows<T = any>(res: any): T[] {
if (Array.isArray(res)) return res;
if (Array.isArray(res?.data)) return res.data;
return [];
}
export async function GET(req: Request) {
try {
const bearer = requireBearer(req);
// who am i?
const me = await dxGET<{ id: string; role?: { id: string; name?: string } }>(
"/users/me?fields=id,role.id,role.name",
bearer
);
const q = new URL(req.url).searchParams;
const limit = Math.min(parseInt(q.get("limit") || "50", 10), 100);
@ -48,52 +36,15 @@ export async function GET(req: Request) {
"date_updated",
].join(",");
// well try multiple filters; first non-empty result wins
const base = `&fields=${encodeURIComponent(fields)}&sort=-date_updated&limit=${limit}`;
const tries = [
{ label: "owner.id", path: `/items/user_rigs?filter[owner][id][_eq]=${encodeURIComponent(me.id)}${base}` },
{ label: "owner", path: `/items/user_rigs?filter[owner][_eq]=${encodeURIComponent(me.id)}${base}` },
{ label: "user_created", path: `/items/user_rigs?filter[user_created][_eq]=${encodeURIComponent(me.id)}${base}` },
];
// Rely entirely on Directus role rules to scope results ("My Rigs")
const path =
`/items/user_rigs?fields=${encodeURIComponent(fields)}` +
`&sort=-date_updated` +
`&limit=${limit}`;
const attempts: Array<{ label: string; count: number }> = [];
let picked: string | null = null;
let rows: any[] = [];
for (const t of tries) {
const res = await dxGET<any>(t.path, bearer);
const r = takeRows(res);
attempts.push({ label: t.label, count: r.length });
if (r.length) {
picked = t.label;
rows = r;
break;
}
}
// last resort: rely entirely on Directus role rule (no filter)
if (!rows.length) {
const res = await dxGET<any>(`/items/user_rigs?${base.slice(1)}`, bearer);
const r = takeRows(res);
attempts.push({ label: "(no filter, rely on role rule)", count: r.length });
if (r.length) {
picked = "(role rule)";
rows = r;
}
}
if (q.get("debug") === "1") {
return NextResponse.json({
meta: {
me: { id: me.id, role: me.role?.name || me.role?.id || null },
picked,
attempts,
},
data: rows,
});
}
return NextResponse.json(rows);
// dxGET returns the unwrapped `data` array
const rows = await dxGET<any[]>(path, bearer);
return NextResponse.json(rows ?? []);
} catch (e: any) {
return bad(e?.message || "Failed to load rigs", e?.status || 500);
}