makearmy-app/lib/directus.ts

250 lines
9.5 KiB
TypeScript

// lib/directus.ts
// Central Directus helpers used by API routes. (user bearer only)
// ⚠️ NOTE: Do NOT import `headers()` / `cookies()` from "next/headers" here.
// Next 15's types can make those async and break build-time type checks in shared libs.
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
const TOKEN_ADMIN_REGISTER = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || ""; // server-only
const ROLE_MEMBER_NAME = process.env.DIRECTUS_ROLE_MEMBER_NAME || "Users";
const PROJECTS_COLLECTION = process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
if (!TOKEN_ADMIN_REGISTER)
console.warn("[directus] Missing DIRECTUS_TOKEN_ADMIN_REGISTER (used for registration)");
export function bytesFromMB(mb: number) {
return Math.round(mb * 1024 * 1024);
}
/**
* Return the user's Directus bearer token from the **incoming Request**.
* Looks at:
* 1) Authorization: Bearer ...
* 2) Raw Cookie header for ma_at / ma_at_beta / ma_session
*
* We intentionally avoid `next/headers` helpers here to keep this library
* compatible with Next 15's stricter type checks.
*/
export function getUserBearerFromRequest(req?: Request): string | null {
if (!req) return null;
// 1) Authorization header (supports server-to-server/proxy calls)
const hAuth = req.headers.get("authorization");
if (hAuth?.startsWith("Bearer ")) return hAuth.slice(7);
// 2) Raw Cookie header (plain Request)
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;
}
// ─────────────────────────────────────────────────────────────
// Low-level helpers (bearer REQUIRED; no fallbacks)
// ─────────────────────────────────────────────────────────────
function authHeaders(bearer: string, extra?: HeadersInit): HeadersInit {
return { Accept: "application/json", Authorization: `Bearer ${bearer}`, ...extra };
}
async function parseJsonSafe(res: Response) {
const text = await res.text();
let json: any = null;
try {
json = text ? JSON.parse(text) : null;
} catch {}
return { json, text };
}
async function throwIfNotOk(res: Response) {
const { json, text } = await parseJsonSafe(res);
if (!res.ok) {
const err: any = new Error(`Directus ${res.status}: ${text || res.statusText}`);
err.status = res.status;
err.detail = json ?? text;
throw err;
}
return json;
}
export async function dxGET<T = any>(path: string, bearer: string): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
headers: authHeaders(bearer),
cache: "no-store",
});
return (await throwIfNotOk(res)) as T;
}
export async function dxPOST<T = any>(path: string, bearer: string, body: any): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: "POST",
headers: authHeaders(bearer, { "content-type": "application/json" }),
body: JSON.stringify(body),
cache: "no-store",
});
return (await throwIfNotOk(res)) as T;
}
export async function dxPATCH<T = any>(path: string, bearer: string, body: any): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: "PATCH",
headers: authHeaders(bearer, { "content-type": "application/json" }),
body: JSON.stringify(body),
cache: "no-store",
});
return (await throwIfNotOk(res)) as T;
}
export async function dxDELETE<T = any>(path: string, bearer: string): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: "DELETE",
headers: authHeaders(bearer),
cache: "no-store",
});
return (await throwIfNotOk(res)) as T;
}
// ─────────────────────────────────────────────────────────────
// Server-only admin fetch (registration flows, etc.)
// ─────────────────────────────────────────────────────────────
export async function directusAdminFetch<T = any>(path: string, init?: RequestInit): Promise<T> {
if (!TOKEN_ADMIN_REGISTER) throw new Error("Missing DIRECTUS_TOKEN_ADMIN_REGISTER");
const res = await fetch(`${BASE}${path}`, {
...init,
headers: {
Accept: "application/json",
Authorization: `Bearer ${TOKEN_ADMIN_REGISTER}`,
...(init?.headers || {}),
},
cache: "no-store",
});
return (await throwIfNotOk(res)) as T;
}
// ─────────────────────────────────────────────────────────────
// Files & items — user bearer ONLY (no folder listing/browsing)
// ─────────────────────────────────────────────────────────────
export async function uploadFile(
file: Blob | File,
filename: string,
bearer: string,
options?: { folderId?: string; title?: string }
): Promise<{ id: string }> {
const form = new FormData();
form.set("file", file, filename);
form.set("filename_download", filename);
if (options?.title) form.set("title", options.title);
if (options?.folderId) form.set("folder", options.folderId); // user-scoped
const res = await fetch(`${BASE}/files`, {
method: "POST",
headers: authHeaders(bearer),
body: form,
cache: "no-store",
});
const json = await throwIfNotOk(res);
const id = json?.data?.id ?? json?.id;
if (!id) throw new Error("File upload succeeded but no id returned");
return { id: String(id) };
}
export async function createSettingsItem(
collection: string,
payload: any,
bearer: string
): Promise<{ data: { id: string } }> {
// Note: callers are already using { data: ... } patterns when needed.
return dxPOST<{ data: { id: string } }>(`/items/${collection}`, bearer, payload);
}
export async function createProjectRow(
payload: any,
bearer: string
): Promise<{ data: { id: string } }> {
return dxPOST<{ data: { id: string } }>(`/items/${PROJECTS_COLLECTION}`, bearer, payload);
}
export async function patchProject(
id: string | number,
payload: any,
bearer: string
): Promise<{ data: { id: string } }> {
return dxPATCH<{ data: { id: string } }>(`/items/${PROJECTS_COLLECTION}/${id}`, bearer, payload);
}
// ─────────────────────────────────────────────────────────────
/** Auth helpers (registration / login support) */
// ─────────────────────────────────────────────────────────────
export async function resolveMemberRoleId(): Promise<string> {
const name = ROLE_MEMBER_NAME;
const q = `/roles?filter[name][_eq]=${encodeURIComponent(name)}&fields=id,name&limit=1`;
const { data } = await directusAdminFetch<{ data: Array<{ id: string }> }>(q);
const hit = data?.[0]?.id;
if (!hit) throw new Error(`Role not found: ${name}`);
return hit;
}
/** Registrations always create a 'Users' role account. No overrides. */
export async function createDirectusUser(input: {
username: string;
password: string;
email?: string;
}): Promise<{ id: string }> {
const role = await resolveMemberRoleId();
// If email is omitted, create a stable placeholder so login can still work.
const email =
input.email && input.email.trim()
? input.email.trim()
: `${input.username}@noemail.local`;
// System endpoint `/users` expects raw fields (no { data } wrapper).
const res = await directusAdminFetch<{ data?: { id?: string } }>(`/users`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
status: "active",
role,
username: input.username,
email,
password: input.password,
}),
});
const id = res?.data?.id as string | undefined;
if (!id) throw new Error("User create succeeded but no id returned");
return { id: String(id) };
}
export async function emailForUsername(username: string): Promise<string | null> {
const q = `/users?filter[username][_eq]=${encodeURIComponent(username)}&fields=email&limit=1`;
const { data } = await directusAdminFetch<{ data: Array<{ email?: string }> }>(q);
const em = data?.[0]?.email;
return em ? String(em) : null;
}
export async function loginDirectus(email: string, password: string) {
const res = await fetch(`${BASE}/auth/login`, {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
cache: "no-store",
});
const json = await throwIfNotOk(res);
// Directus typically returns { data: { access_token, refresh_token, expires } }
return json?.data ?? json;
}