makearmy-app/app/api/dx/[...path]/route.ts
2025-10-02 22:15:06 -04:00

84 lines
2.9 KiB
TypeScript

// app/api/dx/[...path]/route.ts
import { NextResponse } from "next/server";
import { dxGET, dxPOST, dxPATCH, dxDELETE } from "@/lib/directus";
import { requireBearer } from "@/app/api/_lib/auth";
export const runtime = "nodejs";
export const dynamic = "force-dynamic"; // these are true proxies, never prerender
function buildPath(req: Request, context: any) {
const search = new URL(req.url).search || "";
const params = (context?.params ?? {}) as { path?: string[] };
const pathParts = Array.isArray(params.path) ? params.path : [];
return `/${pathParts.join("/")}${search}`;
}
// GET /api/dx/<anything>?<query>
export async function GET(req: Request, context: any) {
try {
const bearer = requireBearer(req);
const p = buildPath(req, context);
const json = await dxGET<any>(p, bearer);
return NextResponse.json(json, { status: 200 });
} catch (e: any) {
const status = e?.status ?? 500;
return NextResponse.json(
{ errors: [{ message: e?.message || "Directus proxy error", detail: e?.detail }] },
{ status }
);
}
}
// POST JSON → /api/dx/<path>
export async function POST(req: Request, context: any) {
try {
const bearer = requireBearer(req);
const p = buildPath(req, context);
const body = await req.json().catch(() => {
throw new Error("Invalid JSON body");
});
const json = await dxPOST<any>(p, bearer, body);
return NextResponse.json(json, { status: 200 });
} catch (e: any) {
const status = e?.status ?? 500;
return NextResponse.json(
{ errors: [{ message: e?.message || "Directus proxy error", detail: e?.detail }] },
{ status }
);
}
}
// PATCH JSON → /api/dx/<path>
export async function PATCH(req: Request, context: any) {
try {
const bearer = requireBearer(req);
const p = buildPath(req, context);
const body = await req.json().catch(() => {
throw new Error("Invalid JSON body");
});
const json = await dxPATCH<any>(p, bearer, body);
return NextResponse.json(json, { status: 200 });
} catch (e: any) {
const status = e?.status ?? 500;
return NextResponse.json(
{ errors: [{ message: e?.message || "Directus proxy error", detail: e?.detail }] },
{ status }
);
}
}
// DELETE → /api/dx/<path>
export async function DELETE(req: Request, context: any) {
try {
const bearer = requireBearer(req);
const p = buildPath(req, context);
const json = await dxDELETE<any>(p, bearer);
return NextResponse.json(json, { status: 200 });
} catch (e: any) {
const status = e?.status ?? 500;
return NextResponse.json(
{ errors: [{ message: e?.message || "Directus proxy error", detail: e?.detail }] },
{ status }
);
}
}