ANOTHER route fix.
This commit is contained in:
parent
662a6e3278
commit
b0843150b8
1 changed files with 54 additions and 58 deletions
|
|
@ -1,83 +1,79 @@
|
|||
// app/api/my/rigs/route.ts
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { directusFetch } from "@/lib/directus";
|
||||
|
||||
const BASE = process.env.DIRECTUS_URL!;
|
||||
if (!BASE) console.warn("[my/rigs] Missing DIRECTUS_URL");
|
||||
// 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";
|
||||
|
||||
// Pull the user's Directus access token from cookies
|
||||
function bearerFromCookies() {
|
||||
const at = cookies().get("ma_at")?.value;
|
||||
// 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;
|
||||
if (!at) throw new Error("Not authenticated");
|
||||
return `Bearer ${at}`;
|
||||
}
|
||||
|
||||
async function df(path: string, init?: RequestInit) {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: bearerFromCookies(),
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
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 ?? {};
|
||||
// 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;
|
||||
}
|
||||
|
||||
// List rigs that belong to the current user
|
||||
export async function GET(_req: NextRequest) {
|
||||
try {
|
||||
// Ownership is enforced by Directus policy (owner = $CURRENT_USER)
|
||||
const fields = [
|
||||
"id","name","rig_type",
|
||||
"laser_source.id","laser_source.make","laser_source.model",
|
||||
"laser_scan_lens.id","laser_scan_lens.field_size","laser_scan_lens.f_number",
|
||||
"laser_focus_lens.id","laser_focus_lens.name",
|
||||
"laser_scan_lens_apt.id","laser_scan_lens_apt.name",
|
||||
"laser_scan_lens_exp.id","laser_scan_lens_exp.multiplier",
|
||||
"laser_software.id","laser_software.name",
|
||||
"date_created","date_updated"
|
||||
].join(",");
|
||||
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 } }
|
||||
);
|
||||
|
||||
const { data } = await df(`/items/rigs?fields=${encodeURIComponent(fields)}&limit=200&sort=-date_updated`);
|
||||
return NextResponse.json({ ok: true, data });
|
||||
} catch (e: any) {
|
||||
const msg = e?.message || "Failed to load rigs";
|
||||
return NextResponse.json({ error: msg }, { status: msg.includes("Not authenticated") ? 401 : 500 });
|
||||
} catch (err: any) {
|
||||
return NextResponse.json(
|
||||
{ error: err?.message || "List failed" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new rig for the current user
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const auth = await bearerFromCookies();
|
||||
const meId = await getMeId(auth);
|
||||
const body = await req.json();
|
||||
|
||||
// Minimal validation
|
||||
if (!body?.name) return NextResponse.json({ error: "Missing name" }, { status: 400 });
|
||||
if (!body?.rig_type) return NextResponse.json({ error: "Missing rig_type" }, { status: 400 });
|
||||
// Ensure ownership is set to the current user
|
||||
const payload = { ...body, [OWNER_FIELD]: meId };
|
||||
|
||||
// owner is set by Directus preset (owner: $CURRENT_USER)
|
||||
const payload = {
|
||||
name: body.name,
|
||||
rig_type: body.rig_type, // "fiber" | "co2_galvo" | "co2_gantry" | "uv"
|
||||
laser_source: body.laser_source ?? null,
|
||||
laser_scan_lens: body.laser_scan_lens ?? null,
|
||||
laser_focus_lens: body.laser_focus_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,
|
||||
meta: body.meta ?? null, // future: measured focal distance, spot size, etc.
|
||||
};
|
||||
const { data } = await directusFetch<{ data: any }>(
|
||||
`/items/${BASE_COLLECTION}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: auth,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
);
|
||||
|
||||
const { data } = await df(`/items/rigs`, { method: "POST", body: JSON.stringify(payload) });
|
||||
return NextResponse.json({ ok: true, id: data?.id });
|
||||
} catch (e: any) {
|
||||
const msg = e?.message || "Create failed";
|
||||
return NextResponse.json({ error: msg }, { status: msg.includes("Not authenticated") ? 401 : 500 });
|
||||
return NextResponse.json({ ok: true, data });
|
||||
} catch (err: any) {
|
||||
return NextResponse.json(
|
||||
{ error: err?.message || "Create failed" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue