서버페이징 변경
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** 완성된 Excel을 버퍼/Blob에 모으지 않고 기존 인증 쿠키로 서버에서 브라우저에 스트리밍한다. */
|
||||
export async function GET(request: NextRequest, context: { params: Promise<{ jobId: string }> }) {
|
||||
const { jobId } = await context.params;
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(jobId)) {
|
||||
return NextResponse.json({ message: "다운로드 작업 식별자가 올바르지 않습니다." }, { status: 400 });
|
||||
}
|
||||
const token = (await cookies()).get(process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization")?.value;
|
||||
if (!token) return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||
const base = process.env.SEWERAGE_API_URL;
|
||||
if (!base) return NextResponse.json({ message: "다운로드 서버 설정을 확인해주세요." }, { status: 503 });
|
||||
const url = `${base.replace(/\/$/, "")}/sewerage-service/api/v1/gridExportJobs/${jobId}`;
|
||||
const headers = { Authorization: token, "X-Site-Id": process.env.NEXT_PUBLIC_SITE_ID || "SN" };
|
||||
let upstream: Response;
|
||||
try {
|
||||
upstream = await fetch(`${url}/download`, { headers, cache: "no-store", signal: request.signal });
|
||||
} catch {
|
||||
return NextResponse.json({ message: "다운로드 서버에 연결하지 못했습니다." }, { status: 502 });
|
||||
}
|
||||
if (!upstream.ok || !upstream.body || !upstream.headers.get("content-type")?.includes("spreadsheetml.sheet")) {
|
||||
return NextResponse.json({ message: "Excel 파일을 받을 수 없습니다. 다시 다운로드해주세요." }, { status: upstream.ok ? 502 : upstream.status });
|
||||
}
|
||||
const reader = upstream.body.getReader();
|
||||
let cleaned = false;
|
||||
const cleanup = async () => {
|
||||
if (cleaned) return;
|
||||
cleaned = true;
|
||||
// 수신 완료/취소 후 서버 임시 파일을 정리한다. 연결 실패 시 서버 TTL 정리가 대신 수행한다.
|
||||
await fetch(url, { method: "DELETE", headers, cache: "no-store", signal: AbortSignal.timeout(10_000) }).catch(() => undefined);
|
||||
};
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) { await cleanup(); controller.close(); }
|
||||
else controller.enqueue(value);
|
||||
} catch (error) { await cleanup(); controller.error(error); }
|
||||
},
|
||||
async cancel(reason) { await reader.cancel(reason); await cleanup(); },
|
||||
});
|
||||
const requestedName = (request.nextUrl.searchParams.get("fileName") || "grid.xlsx")
|
||||
.replace(/[\\/:*?"<>|\r\n]/g, "_").replace(/\.xlsx$/i, "");
|
||||
const fileName = `${Array.from(requestedName).slice(0, 180).join("") || "grid"}.xlsx`;
|
||||
const encodedName = encodeURIComponent(fileName).replace(/['()*]/g, (value) => `%${value.charCodeAt(0).toString(16).toUpperCase()}`);
|
||||
return new Response(stream, { headers: {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition": `attachment; filename*=UTF-8''${encodedName}`,
|
||||
"Cache-Control": "no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
} });
|
||||
}
|
||||
Reference in New Issue
Block a user