Files
co-lite/solvway-admin-portal/app/api/events/[uuid]/[...path]/route.ts
T

47 lines
2.4 KiB
TypeScript

import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// One proxy for the event guest, check-in, attendance and ticket endpoints; mobile-api owns validation and the
// BO_EVENTS / BO_EVENT_GUESTS / BO_EVENT_TICKETS guards.
type Ctx = { params: Promise<{ uuid: string; path: string[] }> };
const ALLOWED =
/^(guests(\/(send|\d+))?|checkin|attendance|tickets\/settings|ticket-types(\/\d+)?|orders(\/\d+(\/(paid|cancel|resend|tickets\/\d+\/cancel))?)?)$/;
// Event uuids are strings, not numbers; word characters and hyphens cover them and nothing that can alter the upstream path.
const EVENT_ID = /^[\w-]+$/;
async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "PUT" | "DELETE") {
const token = await getToken();
if (!token) return unauthorized();
const { uuid, path } = await params;
if (!EVENT_ID.test(uuid) || !ALLOWED.test(path.join("/"))) return badRequest("Invalid path.");
// Only the preview flag, and the orders list's filter and page, are forwarded from the browser's query string.
const query = new URL(req.url).searchParams;
const forwarded = new URLSearchParams();
if (query.getAll("preview").includes("true")) forwarded.set("preview", "true");
if (path.join("/") === "orders") {
for (const k of ["status", "q", "page"]) {
const v = query.get(k);
if (v) forwarded.set(k, v);
}
}
const qs = forwarded.size ? `?${forwarded}` : "";
const target = `/api/admin/events/${encodeURIComponent(uuid)}/${path.map(encodeURIComponent).join("/")}${qs}`;
const result =
method === "POST" || method === "PUT"
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
: method
? await callMobileApi<unknown>(target, { method, token })
: await callMobileApi<unknown>(target, { token });
if (!result.ok) return errorResponse(result);
// A delete answers 204 with no body.
return NextResponse.json(result.data ?? {});
}
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT");
export const DELETE = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "DELETE");