co2 galvo owner test
This commit is contained in:
parent
715be11ff9
commit
a38aa4c2f9
5 changed files with 254 additions and 236 deletions
40
.env.local
40
.env.local
|
|
@ -1,9 +1,43 @@
|
||||||
# Client-side (used by the dropdown fetches)
|
# ─────────────────────────────────────────────
|
||||||
|
# Public (used by client-side dropdown fetches)
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
NEXT_PUBLIC_API_BASE_URL=https://forms.lasereverything.net
|
NEXT_PUBLIC_API_BASE_URL=https://forms.lasereverything.net
|
||||||
|
|
||||||
# Server-side (used by API routes)
|
# ─────────────────────────────────────────────
|
||||||
|
# Server-side Directus
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
DIRECTUS_URL=https://forms.lasereverything.net
|
DIRECTUS_URL=https://forms.lasereverything.net
|
||||||
DIRECTUS_TOKEN_ADMIN_REGISTER=l_QqNXKpi--Dt-hHDncHyBX0eiHNYZr7
|
DIRECTUS_TOKEN_ADMIN_REGISTER=l_QqNXKpi--Dt-hHDncHyBX0eiHNYZr7
|
||||||
|
|
||||||
# Image Folders
|
# Optional (default "Users")
|
||||||
|
DIRECTUS_ROLE_MEMBER_NAME=Users
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Files / Folders (IDs only; no folder browsing)
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
DIRECTUS_AVATAR_FOLDER_ID=b8ddddf8-3ee3-4380-b27e-c7a5f01deef1
|
DIRECTUS_AVATAR_FOLDER_ID=b8ddddf8-3ee3-4380-b27e-c7a5f01deef1
|
||||||
|
|
||||||
|
# Settings — CO₂ Galvo
|
||||||
|
DX_FOLDER_GALVO_NOTES=7b04a706-754d-4302-a9a0-6c88cd8faddf
|
||||||
|
DX_FOLDER_GALVO_PHOTOS=e5535371-828a-498b-80fc-3891b6220fd4
|
||||||
|
DX_FOLDER_GALVO_SCREENS=8201e4c0-c39c-456a-bd55-1beb96642bcb
|
||||||
|
|
||||||
|
# Settings — CO₂ Gantry
|
||||||
|
DX_FOLDER_GANTRY_NOTES=926e2c1a-7907-4ef2-b778-859c6f40ba82
|
||||||
|
DX_FOLDER_GANTRY_PHOTOS=d19c4f8d-a42f-422d-b113-b89b736c34e6
|
||||||
|
DX_FOLDER_GANTRY_SCREENS=9b7d0b47-c1f4-4749-8876-2e4b52ccded0
|
||||||
|
|
||||||
|
# Settings — Fiber
|
||||||
|
DX_FOLDER_FIBER_NOTES=00eed759-480e-43cc-9de3-854dc59cca79
|
||||||
|
DX_FOLDER_FIBER_PHOTOS=54f6a9d2-bc57-41fc-8c7d-7c7d7cb9cadc
|
||||||
|
DX_FOLDER_FIBER_SCREENS=5c830975-7926-4e01-911c-2443b62d7f88
|
||||||
|
|
||||||
|
# Settings — UV
|
||||||
|
DX_FOLDER_UV_NOTES=8ca37379-7178-48b2-8670-6b8d8a880677
|
||||||
|
DX_FOLDER_UV_PHOTOS=c639360b-3116-4b5d-98da-f8b502089486
|
||||||
|
DX_FOLDER_UV_SCREENS=a84f54b1-0e92-4ea6-8fbe-37a3a74bd49c
|
||||||
|
|
||||||
|
# Projects
|
||||||
|
DX_FOLDER_PROJECTS_FILES=f264f066-5b38-4335-bb10-5b014bfa62cb
|
||||||
|
DX_FOLDER_PROJECTS_IMAGES=da11b876-2ede-4e19-ad3a-76fc9db449a8
|
||||||
|
DX_FOLDER_PROJECTS_INSTRUCTIONS=905a4259-0c8e-489b-b810-c27186a2f266
|
||||||
|
|
|
||||||
|
|
@ -81,26 +81,36 @@ async function readJsonOrMultipart(req: Request): Promise<ReadResult> {
|
||||||
return { mode: "json", body, photoFile: null, screenFile: null };
|
return { mode: "json", body, photoFile: null, screenFile: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
// map to your Directus folder paths
|
/** Env-based folder IDs (no folder browsing) */
|
||||||
function folderPathFor(target: Target, kind: "photo" | "screen") {
|
function folderIdFor(
|
||||||
switch (target) {
|
target: Target,
|
||||||
case "settings_fiber":
|
kind: "photo" | "screen" | "notes"
|
||||||
return kind === "photo"
|
): string | undefined {
|
||||||
? "le_fiber_settings/le_fiber_settings_photos"
|
const E = process.env;
|
||||||
: "le_fiber_settings/le_fiber_settings_screenshots";
|
const map = {
|
||||||
case "settings_co2gan":
|
settings_co2gal: {
|
||||||
return kind === "photo"
|
photo: E.DX_FOLDER_GALVO_PHOTOS,
|
||||||
? "le_co2gan_settings/le_co2gan_settings_photos"
|
screen: E.DX_FOLDER_GALVO_SCREENS,
|
||||||
: "le_co2gan_settings/le_co2gan_settings_screenshots";
|
notes: E.DX_FOLDER_GALVO_NOTES,
|
||||||
case "settings_co2gal":
|
},
|
||||||
return kind === "photo"
|
settings_co2gan: {
|
||||||
? "le_co2gal_settings/le_co2gal_settings_photos"
|
photo: E.DX_FOLDER_GANTRY_PHOTOS,
|
||||||
: "le_co2gal_settings/le_co2gal_settings_screenshots";
|
screen: E.DX_FOLDER_GANTRY_SCREENS,
|
||||||
case "settings_uv":
|
notes: E.DX_FOLDER_GANTRY_NOTES,
|
||||||
return kind === "photo"
|
},
|
||||||
? "le_uv_settings/le_uv_settings_photos"
|
settings_fiber: {
|
||||||
: "le_uv_settings/le_uv_settings_screenshots";
|
photo: E.DX_FOLDER_FIBER_PHOTOS,
|
||||||
}
|
screen: E.DX_FOLDER_FIBER_SCREENS,
|
||||||
|
notes: E.DX_FOLDER_FIBER_NOTES,
|
||||||
|
},
|
||||||
|
settings_uv: {
|
||||||
|
photo: E.DX_FOLDER_UV_PHOTOS,
|
||||||
|
screen: E.DX_FOLDER_UV_SCREENS,
|
||||||
|
notes: E.DX_FOLDER_UV_NOTES,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
// @ts-expect-error narrow map index
|
||||||
|
return map[target]?.[kind];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
|
|
@ -109,152 +119,141 @@ export async function POST(req: Request) {
|
||||||
const ip =
|
const ip =
|
||||||
(req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() as string) ||
|
(req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() as string) ||
|
||||||
"0.0.0.0";
|
"0.0.0.0";
|
||||||
if (!rateLimitOk(ip)) {
|
if (!rateLimitOk(ip)) {
|
||||||
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
|
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enforce user auth
|
// Enforce user auth (everything uses the user's token)
|
||||||
const bearer = requireBearer(req);
|
const bearer = requireBearer(req);
|
||||||
|
|
||||||
const { mode, body, photoFile, screenFile } = await readJsonOrMultipart(req);
|
const { mode, body, photoFile, screenFile } = await readJsonOrMultipart(req);
|
||||||
|
|
||||||
const target: Target = body?.target;
|
const target: Target = body?.target;
|
||||||
if (
|
if (
|
||||||
!target ||
|
!target ||
|
||||||
!["settings_fiber", "settings_co2gan", "settings_co2gal", "settings_uv"].includes(target)
|
!["settings_fiber", "settings_co2gan", "settings_co2gal", "settings_uv"].includes(target)
|
||||||
) {
|
) {
|
||||||
return NextResponse.json({ error: "Invalid target" }, { status: 400 });
|
return NextResponse.json({ error: "Invalid target" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Required basics
|
// Required basics
|
||||||
const setting_title = String(body?.setting_title || "").trim();
|
const setting_title = String(body?.setting_title || "").trim();
|
||||||
if (!setting_title)
|
if (!setting_title) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Missing required: setting_title" },
|
{ error: "Missing required: setting_title" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Current user (handle both shapes from dxGET) ─────────────
|
// Current user (handle both {data:{...}} and {...} shapes)
|
||||||
const meRes = await dxGET<any>("/users/me?fields=id,username", bearer);
|
const meRes = await dxGET<any>("/users/me?fields=id,username", bearer);
|
||||||
const meId = meRes?.data?.id ?? meRes?.id ?? null;
|
const meId = meRes?.data?.id ?? meRes?.id ?? null;
|
||||||
const meUsername = meRes?.data?.username ?? meRes?.username ?? null;
|
const meUsername = meRes?.data?.username ?? meRes?.username ?? null;
|
||||||
|
|
||||||
// Derive uploader from the authenticated user (server-trusted)
|
// Attribution
|
||||||
const uploader = meUsername || "user";
|
const uploader = meUsername || "user"; // string field mirrors owner.username
|
||||||
|
|
||||||
// Relations & numerics
|
// Relations & numerics
|
||||||
const mat = body?.mat ?? null;
|
const mat = body?.mat ?? null;
|
||||||
const mat_coat = body?.mat_coat ?? null;
|
const mat_coat = body?.mat_coat ?? null;
|
||||||
const mat_color = body?.mat_color ?? null;
|
const mat_color = body?.mat_color ?? null;
|
||||||
const mat_opacity = body?.mat_opacity ?? null;
|
const mat_opacity = body?.mat_opacity ?? null;
|
||||||
const mat_thickness = num(body?.mat_thickness, null);
|
const mat_thickness = num(body?.mat_thickness, null);
|
||||||
const source = body?.source ?? null;
|
const source = body?.source ?? null;
|
||||||
const lens = body?.lens ?? null;
|
const lens = body?.lens ?? null;
|
||||||
const focus = num(body?.focus, null);
|
const focus = num(body?.focus, null);
|
||||||
const setting_notes = String(body?.setting_notes || "").trim();
|
const setting_notes = String(body?.setting_notes || "").trim();
|
||||||
|
|
||||||
// Fiber-only / shared string
|
// Shared string fields
|
||||||
const laser_soft = body?.laser_soft ?? null; // string
|
const laser_soft = body?.laser_soft ?? null; // exact key: 'laser_soft'
|
||||||
const repeat_all =
|
const repeat_all = num(body?.repeat_all, null); // ← universally applicable now
|
||||||
target === "settings_fiber" ? num(body?.repeat_all, null) : undefined;
|
|
||||||
|
|
||||||
// Upload / accept existing file ids
|
// Upload / accept existing file ids
|
||||||
let photo_id: string | null = body?.photo ?? null;
|
let photo_id: string | null = body?.photo ?? null;
|
||||||
let screen_id: string | null = body?.screen ?? null;
|
let screen_id: string | null = body?.screen ?? null;
|
||||||
|
|
||||||
// photo is required: if no id on body, require file
|
// photo is required: if no id on body, require file
|
||||||
if (!photo_id && photoFile) {
|
if (!photo_id && photoFile) {
|
||||||
if (photoFile.size > MAX_BYTES)
|
if (photoFile.size > MAX_BYTES) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: `Photo exceeds ${MAX_MB} MB` },
|
{ error: `Photo exceeds ${MAX_MB} MB` },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
const up = await uploadFile(
|
}
|
||||||
photoFile,
|
const up = await uploadFile(photoFile, (photoFile as File).name, bearer, {
|
||||||
(photoFile as File).name,
|
folderId: folderIdFor(target, "photo"),
|
||||||
bearer,
|
title: setting_title,
|
||||||
{
|
});
|
||||||
folderNamePath: folderPathFor(target, "photo"),
|
photo_id = up.id;
|
||||||
title: setting_title,
|
}
|
||||||
// NOTE: do NOT include `owner` here; uploadFile options don't accept it.
|
if (!photo_id) {
|
||||||
}
|
return NextResponse.json(
|
||||||
);
|
{ error: "Missing required: photo" },
|
||||||
photo_id = up.id;
|
{ status: 400 }
|
||||||
}
|
);
|
||||||
if (!photo_id) {
|
}
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Missing required: photo" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!screen_id && screenFile) {
|
if (!screen_id && screenFile) {
|
||||||
if (screenFile.size > MAX_BYTES)
|
if (screenFile.size > MAX_BYTES) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: `Screenshot exceeds ${MAX_MB} MB` },
|
{ error: `Screenshot exceeds ${MAX_MB} MB` },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
const up = await uploadFile(
|
}
|
||||||
screenFile,
|
const up = await uploadFile(screenFile, (screenFile as File).name, bearer, {
|
||||||
(screenFile as File).name,
|
folderId: folderIdFor(target, "screen"),
|
||||||
bearer,
|
title: `${setting_title} (screen)`,
|
||||||
{
|
});
|
||||||
folderNamePath: folderPathFor(target, "screen"),
|
screen_id = up.id;
|
||||||
title: `${setting_title} (screen)`,
|
}
|
||||||
}
|
|
||||||
);
|
|
||||||
screen_id = up.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Repeaters (pass through; UI already coerces numbers/bools)
|
// Repeaters (pass-through; UI coerces numbers/bools)
|
||||||
const fills = Array.isArray(body?.fill_settings) ? body.fill_settings : [];
|
const fills = Array.isArray(body?.fill_settings) ? body.fill_settings : [];
|
||||||
const lines = Array.isArray(body?.line_settings) ? body.line_settings : [];
|
const lines = Array.isArray(body?.line_settings) ? body.line_settings : [];
|
||||||
const rasters = Array.isArray(body?.raster_settings) ? body.raster_settings : [];
|
const rasters = Array.isArray(body?.raster_settings) ? body.raster_settings : [];
|
||||||
|
|
||||||
// timestamps for required fields
|
// timestamps
|
||||||
const nowIso = new Date().toISOString();
|
const nowIso = new Date().toISOString();
|
||||||
|
|
||||||
const payload: Record<string, any> = {
|
const payload: Record<string, any> = {
|
||||||
setting_title,
|
setting_title,
|
||||||
// Ownership & attribution
|
|
||||||
owner: meId || null, // ✅ M2O to directus_users
|
|
||||||
uploader, // ✅ mirror username into string field
|
|
||||||
|
|
||||||
setting_notes,
|
// Ownership & attribution
|
||||||
|
owner: meId || null, // M2O to directus_users
|
||||||
|
uploader, // string mirror of username
|
||||||
|
|
||||||
submission_date: nowIso, // if required by schema
|
setting_notes,
|
||||||
last_modified_date: nowIso, // keep in sync
|
|
||||||
|
|
||||||
photo: photo_id,
|
submission_date: nowIso,
|
||||||
screen: screen_id ?? null,
|
last_modified_date: nowIso,
|
||||||
|
|
||||||
// ✅ exact key (string)
|
photo: photo_id,
|
||||||
laser_soft,
|
screen: screen_id ?? null,
|
||||||
|
|
||||||
mat,
|
// exact keys
|
||||||
mat_coat,
|
laser_soft,
|
||||||
mat_color,
|
repeat_all, // ← always included
|
||||||
mat_opacity,
|
|
||||||
mat_thickness,
|
|
||||||
source,
|
|
||||||
lens,
|
|
||||||
focus,
|
|
||||||
|
|
||||||
fill_settings: fills,
|
mat,
|
||||||
line_settings: lines,
|
mat_coat,
|
||||||
raster_settings: rasters,
|
mat_color,
|
||||||
|
mat_opacity,
|
||||||
|
mat_thickness,
|
||||||
|
source,
|
||||||
|
lens,
|
||||||
|
focus,
|
||||||
|
|
||||||
status: "pending",
|
fill_settings: fills,
|
||||||
submitted_via: "makearmy-app",
|
line_settings: lines,
|
||||||
submitted_at: nowIso,
|
raster_settings: rasters,
|
||||||
};
|
|
||||||
|
|
||||||
if (target === "settings_fiber") {
|
status: "pending",
|
||||||
payload.repeat_all = repeat_all ?? null;
|
submitted_via: "makearmy-app",
|
||||||
}
|
submitted_at: nowIso,
|
||||||
|
};
|
||||||
|
|
||||||
const { data } = await createSettingsItem(target, payload, bearer);
|
const { data } = await createSettingsItem(target, payload, bearer);
|
||||||
return NextResponse.json({ ok: true, id: data.id });
|
return NextResponse.json({ ok: true, id: data.id });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error("[submit/settings] error", err?.message || err);
|
console.error("[submit/settings] error", err?.message || err);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,6 @@ export default function CO2GalvoSettingDetailPage() {
|
||||||
"submission_id",
|
"submission_id",
|
||||||
"setting_title",
|
"setting_title",
|
||||||
"uploader",
|
"uploader",
|
||||||
// make sure owner expands
|
|
||||||
"owner.id",
|
"owner.id",
|
||||||
"owner.username",
|
"owner.username",
|
||||||
"setting_notes",
|
"setting_notes",
|
||||||
|
|
@ -41,7 +40,6 @@ export default function CO2GalvoSettingDetailPage() {
|
||||||
"lens_apt.name",
|
"lens_apt.name",
|
||||||
"lens_exp.name",
|
"lens_exp.name",
|
||||||
"focus",
|
"focus",
|
||||||
// string-or-relation
|
|
||||||
"laser_soft",
|
"laser_soft",
|
||||||
"laser_soft.name",
|
"laser_soft.name",
|
||||||
"repeat_all",
|
"repeat_all",
|
||||||
|
|
@ -50,7 +48,8 @@ export default function CO2GalvoSettingDetailPage() {
|
||||||
"raster_settings",
|
"raster_settings",
|
||||||
].join(",");
|
].join(",");
|
||||||
|
|
||||||
const url = `/api/dx/items/settings_co2gal/${encodeURIComponent(String(id))}` +
|
const url =
|
||||||
|
`/api/dx/items/settings_co2gal/${encodeURIComponent(String(id))}` +
|
||||||
`?fields=${encodeURIComponent(fields)}`;
|
`?fields=${encodeURIComponent(fields)}`;
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
@ -73,7 +72,6 @@ export default function CO2GalvoSettingDetailPage() {
|
||||||
if (loading) return <p className="p-6">Loading setting...</p>;
|
if (loading) return <p className="p-6">Loading setting...</p>;
|
||||||
if (!setting) return <p className="p-6">Setting not found.</p>;
|
if (!setting) return <p className="p-6">Setting not found.</p>;
|
||||||
|
|
||||||
// ---- display helpers ----
|
|
||||||
const ownerDisplay: string =
|
const ownerDisplay: string =
|
||||||
typeof setting?.owner === "object"
|
typeof setting?.owner === "object"
|
||||||
? (setting.owner?.username ?? setting.owner?.id ?? "—")
|
? (setting.owner?.username ?? setting.owner?.id ?? "—")
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import Image from "next/image";
|
||||||
type Owner = {
|
type Owner = {
|
||||||
id?: string | number;
|
id?: string | number;
|
||||||
username?: string | null;
|
username?: string | null;
|
||||||
// keep extras harmlessly if API returns them
|
|
||||||
first_name?: string | null;
|
first_name?: string | null;
|
||||||
last_name?: string | null;
|
last_name?: string | null;
|
||||||
email?: string | null;
|
email?: string | null;
|
||||||
|
|
@ -31,32 +30,31 @@ export default function CO2GalvoSettingsPage() {
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const url =
|
const fields = [
|
||||||
`${process.env.NEXT_PUBLIC_API_BASE_URL}/items/settings_co2gal` +
|
|
||||||
`?fields=` +
|
|
||||||
[
|
|
||||||
"submission_id",
|
"submission_id",
|
||||||
"setting_title",
|
"setting_title",
|
||||||
"uploader",
|
"uploader",
|
||||||
// owner (M2O) – ensure username is requested
|
|
||||||
"owner.id",
|
"owner.id",
|
||||||
"owner.username",
|
"owner.username",
|
||||||
// assets / denorms
|
|
||||||
"photo.id",
|
"photo.id",
|
||||||
"photo.title",
|
"photo.title",
|
||||||
"mat.name",
|
"mat.name",
|
||||||
"mat_coat.name",
|
"mat_coat.name",
|
||||||
"source.model",
|
"source.model",
|
||||||
"lens.field_size",
|
"lens.field_size",
|
||||||
].join(",") +
|
].join(",");
|
||||||
`&limit=-1`;
|
|
||||||
|
|
||||||
fetch(url, { cache: "no-store" })
|
const url = `/api/dx/items/settings_co2gal?fields=${encodeURIComponent(fields)}&limit=-1`;
|
||||||
.then((res) => {
|
|
||||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
fetch(url, { cache: "no-store", credentials: "include" })
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) {
|
||||||
|
const j = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(j?.errors?.[0]?.message || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
return res.json();
|
return res.json();
|
||||||
})
|
})
|
||||||
.then((data) => setSettings(data?.data || []))
|
.then((json) => setSettings(json?.data || []))
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
console.error("CO2 Galvo settings fetch failed:", e);
|
console.error("CO2 Galvo settings fetch failed:", e);
|
||||||
setSettings([]);
|
setSettings([]);
|
||||||
|
|
|
||||||
135
lib/directus.ts
135
lib/directus.ts
|
|
@ -1,10 +1,11 @@
|
||||||
// lib/directus.ts
|
// lib/directus.ts
|
||||||
// Central Directus helpers used by API routes. (user bearer only)
|
// Central Directus helpers used by API routes. (user bearer only)
|
||||||
|
|
||||||
|
import { cookies, headers } from "next/headers";
|
||||||
|
|
||||||
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
|
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
|
||||||
const TOKEN_ADMIN_REGISTER = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || ""; // server-only
|
const TOKEN_ADMIN_REGISTER = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || ""; // server-only
|
||||||
const ROLE_MEMBER_NAME = process.env.DIRECTUS_ROLE_MEMBER_NAME || "Users";
|
const ROLE_MEMBER_NAME = process.env.DIRECTUS_ROLE_MEMBER_NAME || "Users";
|
||||||
|
|
||||||
const PROJECTS_COLLECTION = process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
|
const PROJECTS_COLLECTION = process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
|
||||||
|
|
||||||
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
|
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
|
||||||
|
|
@ -15,11 +16,45 @@ export function bytesFromMB(mb: number) {
|
||||||
return Math.round(mb * 1024 * 1024);
|
return Math.round(mb * 1024 * 1024);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract a user's bearer (ma_at) from a Next.js Request (server routes)
|
/**
|
||||||
export function getUserBearerFromRequest(req: Request): string | null {
|
* Return the user's Directus bearer token from the request or server context.
|
||||||
const cookieHeader = req.headers.get("cookie") ?? "";
|
* Looks at:
|
||||||
const m = cookieHeader.match(/(?:^|;\s*)ma_at=([^;]+)/);
|
* 1) Authorization: Bearer ...
|
||||||
return m?.[1] ?? null;
|
* 2) Next.js server cookies (ma_at, ma_at_beta, ma_session)
|
||||||
|
* 3) Raw Cookie header (fallback)
|
||||||
|
*/
|
||||||
|
export function getUserBearerFromRequest(req?: Request): string | null {
|
||||||
|
// 1) Authorization header (supports server-to-server/proxy calls)
|
||||||
|
const hAuth = req?.headers?.get("authorization") ?? headers().get("authorization");
|
||||||
|
if (hAuth?.startsWith("Bearer ")) return hAuth.slice(7);
|
||||||
|
|
||||||
|
// 2) Next.js server cookies (App Router)
|
||||||
|
try {
|
||||||
|
const c = cookies();
|
||||||
|
const t =
|
||||||
|
c.get("ma_at")?.value ||
|
||||||
|
c.get("ma_at_beta")?.value ||
|
||||||
|
c.get("ma_session")?.value ||
|
||||||
|
null;
|
||||||
|
if (t) return t;
|
||||||
|
} catch {
|
||||||
|
// Not in a server context that supports cookies()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) Raw Cookie header (plain Request fallback)
|
||||||
|
const raw = req?.headers?.get("cookie") ?? "";
|
||||||
|
if (raw) {
|
||||||
|
const map = Object.fromEntries(
|
||||||
|
raw.split(/;\s*/).map((p) => {
|
||||||
|
const [k, ...v] = p.split("=");
|
||||||
|
return [decodeURIComponent(k), decodeURIComponent(v.join("=") || "")];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const t = map["ma_at"] || map["ma_at_beta"] || map["ma_session"];
|
||||||
|
if (t) return String(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
|
@ -33,7 +68,9 @@ function authHeaders(bearer: string, extra?: HeadersInit): HeadersInit {
|
||||||
async function parseJsonSafe(res: Response) {
|
async function parseJsonSafe(res: Response) {
|
||||||
const text = await res.text();
|
const text = await res.text();
|
||||||
let json: any = null;
|
let json: any = null;
|
||||||
try { json = text ? JSON.parse(text) : null; } catch {}
|
try {
|
||||||
|
json = text ? JSON.parse(text) : null;
|
||||||
|
} catch {}
|
||||||
return { json, text };
|
return { json, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -49,7 +86,10 @@ async function throwIfNotOk(res: Response) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function dxGET<T = any>(path: string, bearer: string): Promise<T> {
|
export async function dxGET<T = any>(path: string, bearer: string): Promise<T> {
|
||||||
const res = await fetch(`${BASE}${path}`, { headers: authHeaders(bearer), cache: "no-store" });
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
|
headers: authHeaders(bearer),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
return (await throwIfNotOk(res)) as T;
|
return (await throwIfNotOk(res)) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -83,89 +123,38 @@ export async function dxDELETE<T = any>(path: string, bearer: string): Promise<T
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────
|
||||||
/** Server-only admin fetch (registration flows, etc.) */
|
// Server-only admin fetch (registration flows, etc.)
|
||||||
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function directusAdminFetch<T = any>(path: string, init?: RequestInit): Promise<T> {
|
export async function directusAdminFetch<T = any>(path: string, init?: RequestInit): Promise<T> {
|
||||||
if (!TOKEN_ADMIN_REGISTER) throw new Error("Missing DIRECTUS_TOKEN_ADMIN_REGISTER");
|
if (!TOKEN_ADMIN_REGISTER) throw new Error("Missing DIRECTUS_TOKEN_ADMIN_REGISTER");
|
||||||
const res = await fetch(`${BASE}${path}`, {
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
...init,
|
...init,
|
||||||
headers: { Accept: "application/json", Authorization: `Bearer ${TOKEN_ADMIN_REGISTER}`, ...(init?.headers || {}) },
|
headers: {
|
||||||
cache: "no-store",
|
Accept: "application/json",
|
||||||
|
Authorization: `Bearer ${TOKEN_ADMIN_REGISTER}`,
|
||||||
|
...(init?.headers || {}),
|
||||||
|
},
|
||||||
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
return (await throwIfNotOk(res)) as T;
|
return (await throwIfNotOk(res)) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────
|
||||||
// Optional folder lookup (server-only if using admin token)
|
// Files & items — user bearer ONLY (no folder listing/browsing)
|
||||||
// ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
type FolderItem = { id: string; name: string; parent?: { id?: string; name?: string } | null };
|
|
||||||
const folderCache = new Map<string, string | undefined>();
|
|
||||||
let folderListCache: FolderItem[] | null = null;
|
|
||||||
let folderListCacheAt = 0;
|
|
||||||
|
|
||||||
async function fetchAllFolders(): Promise<FolderItem[] | null> {
|
|
||||||
try {
|
|
||||||
const q = `/folders?fields=id,name,parent.id,parent.name&limit=500`;
|
|
||||||
const res = await directusAdminFetch<{ data: FolderItem[] }>(q);
|
|
||||||
return res?.data ?? [];
|
|
||||||
} catch (e: any) {
|
|
||||||
console.warn("[directus] fetchAllFolders failed:", e?.message || e);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getFolderIdByPath(path: string): Promise<string | undefined> {
|
|
||||||
if (!path) return undefined;
|
|
||||||
if (folderCache.has(path)) return folderCache.get(path);
|
|
||||||
|
|
||||||
const now = Date.now();
|
|
||||||
const freshForMs = 60_000;
|
|
||||||
if (!folderListCache || now - folderListCacheAt > freshForMs) {
|
|
||||||
folderListCache = await fetchAllFolders();
|
|
||||||
folderListCacheAt = now;
|
|
||||||
}
|
|
||||||
const list = folderListCache;
|
|
||||||
if (!list) {
|
|
||||||
folderCache.set(path, undefined);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts = path.split("/").map((s) => s.trim()).filter(Boolean);
|
|
||||||
const [parentName, childName] = parts;
|
|
||||||
const eq = (a?: string | null, b?: string | null) => String(a ?? "").toLowerCase() === String(b ?? "").toLowerCase();
|
|
||||||
|
|
||||||
let match: FolderItem | undefined;
|
|
||||||
if (parts.length >= 2) {
|
|
||||||
match = list.find((f) => eq(f.name, childName) && eq(f.parent?.name ?? "", parentName));
|
|
||||||
} else {
|
|
||||||
match = list.find((f) => eq(f.name, parts[0]));
|
|
||||||
}
|
|
||||||
|
|
||||||
const id = match?.id ? String(match.id) : undefined;
|
|
||||||
folderCache.set(path, id);
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
|
||||||
// Files & items — user bearer ONLY
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function uploadFile(
|
export async function uploadFile(
|
||||||
file: Blob | File,
|
file: Blob | File,
|
||||||
filename: string,
|
filename: string,
|
||||||
bearer: string,
|
bearer: string,
|
||||||
options?: { folderId?: string; folderNamePath?: string; title?: string }
|
options?: { folderId?: string; title?: string } // folderNamePath removed
|
||||||
): Promise<{ id: string }> {
|
): Promise<{ id: string }> {
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.set("file", file, filename);
|
form.set("file", file, filename);
|
||||||
form.set("filename_download", filename);
|
form.set("filename_download", filename);
|
||||||
if (options?.title) form.set("title", options.title);
|
if (options?.title) form.set("title", options.title);
|
||||||
|
if (options?.folderId) form.set("folder", options.folderId); // user-scoped
|
||||||
let folderId = options?.folderId;
|
|
||||||
if (!folderId && options?.folderNamePath) {
|
|
||||||
try { folderId = await getFolderIdByPath(options.folderNamePath); } catch {}
|
|
||||||
}
|
|
||||||
if (folderId) form.set("folder", folderId);
|
|
||||||
|
|
||||||
const res = await fetch(`${BASE}/files`, {
|
const res = await fetch(`${BASE}/files`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|
@ -204,7 +193,7 @@ export async function patchProject(
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────
|
||||||
// Auth helpers (registration / login support)
|
/** Auth helpers (registration / login support) */
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function resolveMemberRoleId(): Promise<string> {
|
export async function resolveMemberRoleId(): Promise<string> {
|
||||||
|
|
@ -221,7 +210,7 @@ export async function createDirectusUser(input: {
|
||||||
username: string;
|
username: string;
|
||||||
password: string;
|
password: string;
|
||||||
email?: string;
|
email?: string;
|
||||||
}): Promise<{ id: string }> {
|
}: PromiseLike<any> extends never ? never : any): Promise<{ id: string }> {
|
||||||
const role = await resolveMemberRoleId();
|
const role = await resolveMemberRoleId();
|
||||||
|
|
||||||
// If email is omitted, create a stable placeholder so login can still work.
|
// If email is omitted, create a stable placeholder so login can still work.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue