import { NextRequest, NextResponse } from "next/server"; import { errorToResponse } from "@kri/common/http"; import { createServerApiWithApiKey } from "@/lib/http-server"; import { internalTarget, readInternalProjectListQuery, readInternalQuotaRequest, readInternalReportBatch, readInternalShareRequest, } from "@/lib/kric-internal-policy"; import { readExcelRequest } from "@/types/export"; import { isRecord } from "@/types/kart"; import { isShareLink } from "@/types/share"; import type { RouteContext } from "@/types/common"; export const maxDuration = 660; const noStore = { "Cache-Control": "no-store" }; const jsonError = (message: string, status: number) => NextResponse.json({ message }, { status, headers: noStore }); async function handle(request: NextRequest, context: RouteContext) { const { slug = [] } = await context.params; const target = internalTarget(request.method, slug); if (!target) return jsonError("지원하지 않는 경로입니다.", 404); const apiKey = request.headers.get("x-api-key")?.trim(); if (!apiKey) return jsonError("X-API-Key는 필수입니다.", 401); let body: unknown; let query: Record = {}; if (target.kind === "projects") { try { query = readInternalProjectListQuery(request.nextUrl.searchParams); } catch (error) { return jsonError(error instanceof Error ? error.message : "조회 조건을 확인해 주세요.", 400); } } else if (target.kind !== "list" && target.kind !== "respondent") { try { const input: unknown = await request.json(); if (target.kind === "report") { body = readInternalReportBatch(input); } else if (target.kind === "quota") { body = readInternalQuotaRequest(input); } else if (target.kind === "share") { body = readInternalShareRequest(input); } else { body = readExcelRequest(input); } } catch (error) { let message = "요청 내용을 확인해 주세요."; if (error instanceof SyntaxError) { message = "요청 JSON을 확인해 주세요."; } else if (error instanceof Error) { message = error.message; } return jsonError(message, 400); } } try { const api = createServerApiWithApiKey(apiKey); const options = { signal: request.signal, cache: "no-store" as const }; if ( target.kind === "list" || target.kind === "projects" || target.kind === "quota" || target.kind === "respondent" || target.kind === "share" ) { let result: unknown; if (target.kind === "list") { result = await api.get(target.path, options); } else if (target.kind === "projects") { result = await api.get(target.path, { ...options, query }); } else { result = await api.post(target.path, body, options); } if ( target.kind === "share" && (!isShareLink(result) || result.projectType !== Number(slug[1]) || result.pkey !== slug[2] || result.pageOnly || !isRecord(body) || result.realUrl !== body.realUrl) ) return jsonError("공유 링크 응답을 확인해 주세요.", 502); return NextResponse.json(result, { headers: noStore }); } const upstream = await api.streamPost(target.path, body, { ...options, timeoutMs: 600_000, idleTimeoutMs: 600_000, ...(target.kind === "report" ? { headers: { Accept: "application/x-ndjson" } } : {}), }); const contentType = upstream.headers.get("content-type") ?? "application/octet-stream"; const disposition = upstream.headers.get("content-disposition"); if ( !upstream.body || (target.kind === "report" ? !contentType.includes("application/x-ndjson") : !disposition || /json|text\/html/i.test(contentType)) ) { await upstream.body?.cancel(); return jsonError("서버 응답 형식을 확인해 주세요.", 502); } const headers: Record = { ...noStore, "Content-Type": contentType, }; if (target.kind === "report") { headers["X-Accel-Buffering"] = "no"; } else if (disposition) { headers["Content-Disposition"] = disposition; } return new Response(upstream.body, { headers }); } catch (error: unknown) { const response = errorToResponse(error); response.headers.set("Cache-Control", "no-store"); return response; } } export const GET = handle; export const POST = handle; export const OPTIONS = () => new NextResponse(null, { status: 204, headers: noStore });