55 lines
2.4 KiB
TypeScript
55 lines
2.4 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { errorToResponse } from "@kri/common/http";
|
|
import { createBackApi, fetchBackBinary } from "@/lib/http-server";
|
|
import type { RouteContext } from "@/types/common";
|
|
|
|
const apiPath = (slug: string[]) => `/review${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
|
|
const toResponse = (result: unknown) => (result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result));
|
|
|
|
/*
|
|
* download/{id}/{slot}, pdf/{id}/{slot}, template/download/{type}, template/pdf/{type}는
|
|
* 파일 바이너리를 그대로 반환한다.
|
|
*/
|
|
const BINARY_GET_PREFIXES = ["download", "pdf", "template"];
|
|
const isBinaryGetPath = (slug: string[]) => BINARY_GET_PREFIXES.includes(slug[0]);
|
|
|
|
export async function GET(request: NextRequest, context: RouteContext) {
|
|
try {
|
|
const { slug = [] } = await context.params;
|
|
|
|
if (isBinaryGetPath(slug)) {
|
|
/*
|
|
* classification 등 백엔드에 필요한 쿼리는 그대로 릴레이한다.
|
|
* inline은 프론트 전용 플래그이므로 백엔드로 넘기지 않는다.
|
|
*/
|
|
const forwarded = new URLSearchParams(request.nextUrl.searchParams);
|
|
forwarded.delete("inline");
|
|
const queryString = forwarded.toString();
|
|
const response = await fetchBackBinary(`${apiPath(slug)}${queryString ? `?${queryString}` : ""}`);
|
|
if (slug[0] === "pdf" && request.nextUrl.searchParams.get("inline") === "true") {
|
|
const disposition = response.headers.get("content-disposition");
|
|
response.headers.set("content-type", "application/pdf");
|
|
response.headers.set("content-disposition", disposition ? disposition.replace(/^[^;]+/, "inline") : "inline");
|
|
}
|
|
return response;
|
|
}
|
|
|
|
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
|
|
const serverApi = await createBackApi();
|
|
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
|
|
} catch (error: unknown) {
|
|
return errorToResponse(error);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest, context: RouteContext) {
|
|
try {
|
|
const { slug = [] } = await context.params;
|
|
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
|
|
const serverApi = await createBackApi();
|
|
return toResponse(await serverApi.postForm<unknown>(apiPath(slug), await request.formData(), { query }));
|
|
} catch (error: unknown) {
|
|
return errorToResponse(error);
|
|
}
|
|
}
|