makearmy-app/app/api/options/_lib.ts
2025-09-28 14:54:52 -04:00

48 lines
1.8 KiB
TypeScript

// app/api/options/_lib.ts
import { NextRequest, NextResponse } from "next/server";
export type Option = { id: string | number; label: string };
export function readCookie(name: string, cookieHeader: string) {
const m = cookieHeader.match(new RegExp(`(?:^|;\\s*)${name}=([^;]+)`));
return m?.[1] ?? null;
}
export function getAuthHeaders(req: NextRequest) {
const cookieHeader = req.headers.get("cookie") ?? "";
const ma_at = readCookie("ma_at", cookieHeader);
const headers: Record<string, string> = { Accept: "application/json" };
if (cookieHeader) headers.cookie = cookieHeader;
if (ma_at) headers.authorization = `Bearer ${ma_at}`;
return headers;
}
export function apiBase() {
const base = (process.env.DIRECTUS_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
if (!base) throw new Error("Missing DIRECTUS_URL or NEXT_PUBLIC_API_BASE_URL");
return base;
}
export async function dFetchJSON<T = any>(req: NextRequest, path: string): Promise<T> {
const res = await fetch(`${apiBase()}${path}`, {
headers: getAuthHeaders(req),
cache: "no-store",
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`Directus ${res.status} fetching ${path}: ${text}`);
}
return res.json() as Promise<T>;
}
export function applyQFilter<T>(rows: T[], q: string | null, pick: (row: T) => string): T[] {
if (!q) return rows;
const needle = q.trim().toLowerCase();
if (!needle) return rows;
return rows.filter((r) => (pick(r) || "").toLowerCase().includes(needle));
}
export function json(data: Option[] | { data: Option[] }, status = 200) {
const body = Array.isArray(data) ? { data } : data;
return NextResponse.json(body, { status, headers: { "cache-control": "no-store" } });
}