feat: update Directus API routes, add health endpoint

This commit is contained in:
makearmy 2025-09-22 11:28:07 -04:00
parent 78f8d225ee
commit 79f0af51eb
7 changed files with 771 additions and 807 deletions

View file

@ -1,13 +1,17 @@
// lib/directus.ts
// Central Directus helpers used by API routes.
// Central Directus helpers used by API routes. Minimal hard-coding, robust parsing.
const BASE = process.env.DIRECTUS_URL!;
const TOKEN_SUBMIT = process.env.DIRECTUS_TOKEN_SUBMIT!;
const TOKEN_SUBMIT =
process.env.DIRECTUS_TOKEN_SUBMIT ??
process.env.DIRECTUS_STATIC_TOKEN ??
process.env.DIRECTUS_TOKEN ??
"";
const PROJECTS_COLLECTION =
process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
if (!TOKEN_SUBMIT) console.warn("[directus] Missing DIRECTUS_TOKEN_SUBMIT");
if (!TOKEN_SUBMIT) console.warn("[directus] Missing submit token (DIRECTUS_TOKEN_SUBMIT / DIRECTUS_STATIC_TOKEN / DIRECTUS_TOKEN)");
export function bytesFromMB(mb: number) {
return Math.round(mb * 1024 * 1024);
@ -42,22 +46,20 @@ export async function directusFetch<T = any>(
Authorization: `Bearer ${TOKEN_SUBMIT}`,
...(init?.headers || {}),
},
cache: "no-store",
});
const { json, text } = await parseJsonSafe(res);
if (!res.ok) {
throw new Error(
`Directus error ${res.status}: ${text || res.statusText}`
);
throw new Error(`Directus error ${res.status}: ${text || res.statusText}`);
}
return (json ?? {}) as T;
}
/*
* On-the-fly folder lookup by "path" = "<parent>/<child>"
* Caches results in-memory. If lookup is forbidden (403) or not found,
* we return undefined and uploads proceed without a folder.
* Requires READ on directus_folders (id,name,parent.name) to fully work.
* Folder lookup (by "path" = "<parent>/<child>") with caching.
* Requires READ on directus_folders to fully resolve, but gracefully
* degrades (returns undefined) if forbidden/not found.
* */
type FolderItem = {
@ -101,7 +103,7 @@ async function getFolderIdByPath(path: string): Promise<string | undefined> {
const [parentName, childName] = parts;
const eq = (a?: string | null, b?: string | null) =>
String(a ?? "").toLowerCase() === String(b ?? "").toLowerCase();
String(a ?? "").toLowerCase() === String(b ?? "").toLowerCase();
let match: FolderItem | undefined;
if (parts.length >= 2) {
@ -119,10 +121,8 @@ async function getFolderIdByPath(path: string): Promise<string | undefined> {
/**
* uploadFile:
* Robustly uploads a file (Blob/File). Accepts optional folder routing:
* - options.folderId: direct UUID if you have it
* - options.folderNamePath: "<parent>/<child>" lookup via /folders
* Also sets filename_download & optional title.
* Uploads a file and (optionally) sets the folder **at create time**
* so we don't need UPDATE permission on directus_files.
*/
export async function uploadFile(
file: Blob | File,
@ -152,14 +152,11 @@ export async function uploadFile(
const { json, text } = await parseJsonSafe(res);
if (!res.ok) {
throw new Error(
`File upload failed: status=${res.status} ${res.statusText} body=${(text || "").slice(
0,
400
) || "<empty>"}`
`File upload failed: status=${res.status} ${res.statusText} body=${(text || "").slice(0, 400) || "<empty>"}`
);
}
const id = json?.data?.id ?? json?.id;
const id = json?.data?.submission_id ?? json?.data?.id ?? json?.submission_id ?? json?.id;
if (!id) throw new Error("File upload succeeded but no id returned");
return { id: String(id) };
}
@ -168,43 +165,51 @@ export async function uploadFile(
export async function createSettingsItem(
collection: string,
payload: any
): Promise<{ data: { id: string } }> {
return directusFetch<{ data: { id: string } }>(`/items/${collection}`, {
): Promise<{ data: any }> {
return directusFetch<{ data: any }>(`/items/${collection}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
/**
* Project helpers (used by app/api/submit/project/route.ts)
* Collection can be overridden via DIRECTUS_PROJECTS_COLLECTION
* */
/** Project helpers (used by app/api/submit/project/route.ts) */
export async function createProjectRow(
payload: any
): Promise<{ data: { id: string } }> {
return directusFetch<{ data: { id: string } }>(
`/items/${PROJECTS_COLLECTION}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}
);
): Promise<{ data: any }> {
return directusFetch<{ data: any }>(`/items/${PROJECTS_COLLECTION}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function patchProject(
id: string | number,
payload: any
): Promise<{ data: { id: string } }> {
return directusFetch<{ data: { id: string } }>(
`/items/${PROJECTS_COLLECTION}/${id}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}
);
): Promise<{ data: any }> {
return directusFetch<{ data: any }>(`/items/${PROJECTS_COLLECTION}/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
// One-time diagnostic: log which role this token maps to (safe in prod)
(async () => {
if (!BASE || !TOKEN_SUBMIT) return;
try {
const r = await fetch(`${BASE}/users/me?fields=role.name`, {
headers: { Authorization: `Bearer ${TOKEN_SUBMIT}` },
cache: "no-store",
});
if (r.ok) {
const j = await r.json().catch(() => ({}));
console.log(`[directus] using role: ${j?.data?.role?.name ?? "unknown"}`);
} else {
console.warn(`[directus] whoami failed with ${r.status}`);
}
} catch (e: any) {
console.warn(`[directus] whoami error: ${e?.message ?? e}`);
}
})();