Files
frontend/apps/wr/app/api/common-codes/route.ts
T

286 lines
9.0 KiB
TypeScript

export const dynamic = "force-dynamic";
import { SITE_ID } from "@/src/shared/config";
import { normalizeSelectData } from "@/app/store/common/code/normalizeSelectData";
import { NextResponse } from "next/server";
export const revalidate = 86400; //60 * 60 * 24;
type SelectDataType = {
text: string;
val: string;
};
type EnvPartSelectDataType = SelectDataType & {
adstDliStrCd: string;
};
const codeMapping = {
WR001: "bdstUsgCd",
WR002: "rswtBdstType",
WR003: "rainFcltCd",
WR004: "bdstGrntchClass",
WR005: "rswtPrscCdMthdCd",
WR006: "orgwtKndCd",
WR007: "ruseMngMtd",
WR008: "rusePrcsMthdCd",
WR009: "erctUswtrPrcsMeth",
WR010: "ruseFcltSpot",
WR011: "pplQulity",
WR012: "pplLenght",
WR013: "bdstFilterYn",
WR014: "rainRswtMng",
WR015: "rainFcltFlowRate",
WR016: "dmdUszCd",
WR017: "sewageInFcltUse",
WR018: "sewageOutFclttUse",
WR019: "htdPowerMthdCd",
WR020: "htdUtztnUsgCd",
} as const;
const defaultHeaders = {
accept: "application/json",
"X-Site-Id": SITE_ID,
};
function getServerBaseUrl() {
const port = process.env.PORT ?? process.env.NEXT_PUBLIC_PORT ?? "3000";
const proxyHost = process.env.NEXT_PUBLIC_PROXY_HOST;
if (process.env.NODE_ENV === "production" && process.env.HOSTNAME) {
return `http://${process.env.HOSTNAME}:${port}`;
}
return proxyHost || `http://localhost:${port}`;
}
// 요청 1건당 최대 대기 시간(ms). 넘으면 그 요청만 실패 처리하고 나머지는 정상 응답한다.
const REQUEST_TIMEOUT_MS = 5000;
async function fetchJson(url: string, cookieHeader?: string) {
const response = await fetch(url, {
method: "GET",
headers: {
...defaultHeaders,
...(cookieHeader ? { cookie: cookieHeader } : {}),
},
next: { revalidate },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
const responseText = await response.text();
throw new Error(
`Failed to fetch ${url}: ${response.status} ${response.statusText}${
responseText ? ` - ${responseText}` : ""
}`
);
}
return response.json();
}
async function fetchOperationData(path: string, cookieHeader?: string) {
const json = await fetchJson(
`${getServerBaseUrl()}/operation-service${path}`,
cookieHeader
);
return json.data;
}
async function fetchCmsData(path: string, cookieHeader?: string) {
return fetchJson(`${getServerBaseUrl()}${path}`, cookieHeader);
}
// 조회에 실패한 항목 1건. 응답의 failedCodes로 브라우저에 전달해 개발자 도구 콘솔에 표시한다.
type FailedCodeType = {
label: string; // 요청 이름(예: "/addr/sgg", "WR003")
reason: string; // 실패 사유(시간 초과, HTTP 상태, 연결 오류 등)
};
/**
* 요청 결과(Promise.allSettled)에서 성공 값만 꺼낸다. 실패하면 로그를 남기고 기본값을 돌려준다.
* @param result allSettled가 돌려준 요청 1건의 결과
* @param label 로그에 남길 요청 이름(예: "/addr/sgg", "WR001")
* @param fallback 실패했을 때 대신 쓸 값
* @param failures 실패 항목을 모으는 배열(요청마다 새로 만든 배열을 넘긴다)
*/
function settledValue<T>(
result: PromiseSettledResult<T>,
label: string,
fallback: T,
failures: FailedCodeType[]
): T {
if (result.status === "fulfilled") return result.value;
console.error(`Failed to load common code [${label}]:`, result.reason);
const reason = result.reason;
failures.push({
label,
reason:
reason instanceof Error
? reason.name === "TimeoutError"
? `시간 초과(${REQUEST_TIMEOUT_MS}ms)`
: reason.message
: String(reason),
});
return fallback;
}
/**
* WR 하위코드(lwpo-cds)를 코드별로 동시에 조회한다.
* 한 코드가 실패하거나 시간 제한을 넘으면 그 코드만 빈 목록으로 채우고 나머지는 정상으로 돌려준다.
* @param keys 조회할 WR 상위코드 목록(예: ["WR001", "WR002"])
* @param cookieHeader 브라우저 요청의 cookie 헤더(인증 전달용)
* @param failures 실패 항목을 모으는 배열
*/
async function fetchCommonCodesByKeys(
keys: string[],
cookieHeader: string,
failures: FailedCodeType[]
) {
const targets = [...new Set(keys)].filter(
(cd) => Boolean(codeMapping[cd as keyof typeof codeMapping])
);
const results = await Promise.allSettled(
targets.map(async (cd) => {
const lwCd = await fetchCmsData(
`/cms-service/api/v1/lwpo-cds/up-cd/${cd}`,
cookieHeader
);
const list = Array.isArray(lwCd) ? lwCd : (lwCd.content ?? []);
return list.map((it: any) => ({
text: it.lwpoCdNm,
val: it.lwpoCd,
})) as SelectDataType[];
})
);
// allSettled 결과는 targets와 같은 순서로 온다.
const entries = results.map((result, idx) => {
const cd = targets[idx] as keyof typeof codeMapping;
return [
codeMapping[cd],
settledValue<SelectDataType[]>(result, cd, [], failures),
];
});
return Object.fromEntries(entries) as Record<string, SelectDataType[]>;
}
export async function GET(request: Request) {
try {
const cookieHeader = request.headers.get("cookie") ?? "";
// 이번 요청에서 실패한 항목 목록(동시 요청끼리 섞이지 않도록 요청마다 새로 만든다)
const failures: FailedCodeType[] = [];
// 주소 6건과 WR 하위코드를 한 번에 동시에 조회한다.
// 조회할 WR 상위코드는 codeMapping에 정해져 있으므로 up-codes는 조회하지 않는다.
const addrPaths = [
"/addr/sgg",
"/addr/city",
"/addr/sarea",
"/addr/midArea",
"/addr/largeArea",
"/addr/govArea",
];
const [addrResults, lwCds] = await Promise.all([
Promise.allSettled(
addrPaths.map((path) => fetchOperationData(path, cookieHeader))
),
fetchCommonCodesByKeys(Object.keys(codeMapping), cookieHeader, failures),
]);
// 주소 조회는 실패한 항목만 빈 목록으로 처리한다.
const [sgg, city, rvbsn, mdmbsn, lgbsn, lclgvrnmnt] = addrResults.map(
(result, idx) =>
settledValue<any[]>(result, addrPaths[idx] ?? "addr", [], failures)
);
const payload = {
sggCd: [
...((sgg ?? []).map((item: any) => ({
text: item.gugun || "",
val: String(item.adstDstrCd) || "",
})) as SelectDataType[]),
],
cityCd: normalizeSelectData(
(city ?? []).map((item: any) => ({
val: item.adstDstrCd,
text: item.sido,
})),
),
rvbsnCd: [
{ val: "0", text: "전체" },
...((rvbsn ?? []).map((item: any) => ({
val: item.rvbsnCd,
text: item.rvbsn,
})) as SelectDataType[]),
],
mdmbsnCd: [
{ val: "0", text: "전체" },
...((mdmbsn ?? []).map((item: any) => ({
val: item.rvbsnCd,
text: item.mdmbsn,
})) as SelectDataType[]),
],
lgbsnCd: [
{ val: "0", text: "전체" },
...((lgbsn ?? []).map((item: any) => ({
val: item.rvbsnCd,
text: item.lgbsn,
})) as SelectDataType[]),
],
lclgvrnmntCd: [
{ val: "0", text: "전체", adstDliStrCd: "" },
...((lclgvrnmnt ?? []).map((item: any) => ({
val: item.lclgvrnmntCd,
text: item.lclgvrnmntNm,
adstDliStrCd: item.adstDliStrCd || "",
})) as EnvPartSelectDataType[]),
],
rainFcltCd: lwCds["rainFcltCd"] ?? [],
bdstUsgCd: lwCds["bdstUsgCd"] ?? [],
orgwtKndCd: lwCds["orgwtKndCd"] ?? [],
pplQulity: lwCds["pplQulity"] ?? [],
pplLenght: lwCds["pplLenght"] ?? [],
dmdUszCd: lwCds["dmdUszCd"] ?? [],
sewageOutFclttUse: lwCds["sewageOutFclttUse"] ?? [],
rainRswtMng: lwCds["rainRswtMng"] ?? [],
rainFcltFlowRate: lwCds["rainFcltFlowRate"] ?? [],
ruseMngMtd: lwCds["ruseMngMtd"] ?? [],
rusePrcsMthdCd: lwCds["rusePrcsMthdCd"] ?? [],
erctUswtrPrcsMeth: lwCds["erctUswtrPrcsMeth"] ?? [],
bdstGrntchClass: lwCds["bdstGrntchClass"] ?? [],
htdPowerMthdCd: lwCds["htdPowerMthdCd"] ?? [],
htdUtztnUsgCd: lwCds["htdUtztnUsgCd"] ?? [],
rswtBdstType: lwCds["rswtBdstType"] ?? [],
bdstTotalUsgType: (lwCds["bdstUsgCd"] ?? []).concat(lwCds["rswtBdstType"] ?? []),
// 조회에 실패해 빈 목록으로 채운 항목. 브라우저 store에서 개발자 도구 콘솔에 표시한다.
failedCodes: failures,
};
return NextResponse.json(payload, {
headers: {
// 일부가 실패한 결과는 캐시하지 않는다(빈 목록이 하루 동안 남지 않도록).
"Cache-Control":
failures.length > 0
? "no-store"
: "s-maxage=86400, stale-while-revalidate=3600",
},
});
} catch (error) {
console.error("Failed to load common codes:", error);
const message =
error instanceof Error ? error.message : "Failed to load common codes";
return NextResponse.json(
{
message: "Failed to load common codes",
detail:message ,
},
{ status: 500 }
);
}
}