route fixes for api
This commit is contained in:
parent
a1d14fb6ba
commit
01874054c3
1 changed files with 56 additions and 62 deletions
|
|
@ -4,92 +4,86 @@ import { cookies } from "next/headers";
|
|||
|
||||
const BASE = process.env.DIRECTUS_URL!;
|
||||
|
||||
function bearerFromCookies() {
|
||||
const store = cookies();
|
||||
async function bearerFromCookies() {
|
||||
const store = await cookies();
|
||||
const at = store.get("ma_at")?.value;
|
||||
if (!at) throw new Error("Not authenticated");
|
||||
return `Bearer ${at}`;
|
||||
}
|
||||
|
||||
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 ?? {};
|
||||
async function getMyUserId(bearer: string) {
|
||||
const res = await fetch(`${BASE}/users/me`, {
|
||||
headers: { Authorization: bearer, Accept: "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
const txt = await res.text();
|
||||
if (!res.ok) throw new Error(txt || res.statusText);
|
||||
const j = txt ? JSON.parse(txt) : {};
|
||||
return j?.data?.id as string;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
export async function GET(_req: NextRequest) {
|
||||
try {
|
||||
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);
|
||||
const bearer = await bearerFromCookies();
|
||||
const fields = [
|
||||
"id",
|
||||
"name",
|
||||
"rig_type",
|
||||
"rig_type.name",
|
||||
"laser_source",
|
||||
"laser_focus_lens",
|
||||
"laser_scan_lens",
|
||||
"laser_scan_lens_apt",
|
||||
"laser_scan_lens_exp",
|
||||
"laser_software",
|
||||
"notes",
|
||||
"user_created",
|
||||
"date_created",
|
||||
"date_updated",
|
||||
].join(",");
|
||||
|
||||
const res = await fetch(
|
||||
`${BASE}/items/user_rigs?fields=${encodeURIComponent(fields)}&sort=-date_created`,
|
||||
{ headers: { Authorization: bearer, Accept: "application/json" }, cache: "no-store" }
|
||||
);
|
||||
const txt = await res.text();
|
||||
if (!res.ok) return NextResponse.json({ error: txt || res.statusText }, { status: res.status });
|
||||
const j = txt ? JSON.parse(txt) : { data: [] };
|
||||
|
||||
const data = (j.data ?? []).map((r: any) => ({
|
||||
...r,
|
||||
rig_type_name: r?.rig_type?.name ?? r?.rig_type_name ?? null,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ data });
|
||||
} catch (e: any) {
|
||||
return NextResponse.json({ error: e.message || String(e) }, { status: 401 });
|
||||
return NextResponse.json({ error: e?.message || "Failed to list rigs" }, { status: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const auth = bearerFromCookies();
|
||||
const bearer = await bearerFromCookies();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const owner = await getMyUserId(bearer);
|
||||
|
||||
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();
|
||||
const payload = { ...body, owner };
|
||||
|
||||
if (!name) return NextResponse.json({ error: "name is required" }, { status: 400 });
|
||||
if (!rig_type) return NextResponse.json({ error: "rig_type is required" }, { status: 400 });
|
||||
|
||||
// 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");
|
||||
|
||||
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`, {
|
||||
const res = await fetch(`${BASE}/items/user_rigs`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: auth,
|
||||
Authorization: bearer,
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
return NextResponse.json(created);
|
||||
const txt = await res.text();
|
||||
if (!res.ok) return NextResponse.json({ error: txt || res.statusText }, { status: res.status });
|
||||
const j = txt ? JSON.parse(txt) : {};
|
||||
return NextResponse.json(j);
|
||||
} catch (e: any) {
|
||||
return NextResponse.json(
|
||||
{ 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`);
|
||||
return NextResponse.json({ error: e?.message || "Failed to create rig" }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue