79 lines
2.4 KiB
TypeScript
79 lines
2.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { DashboardBalanceResponse } from "@/features/dashboard/types/dashboard.types";
|
|
import { hasKisConfig, normalizeTradingEnv } from "@/lib/kis/config";
|
|
import { getDomesticDashboardBalance } from "@/lib/kis/dashboard";
|
|
import { hasKisApiSession } from "@/app/api/kis/_session";
|
|
import {
|
|
createKisApiErrorResponse,
|
|
KIS_API_ERROR_CODE,
|
|
toKisApiErrorMessage,
|
|
} from "@/app/api/kis/_response";
|
|
import {
|
|
readKisAccountParts,
|
|
readKisCredentialsFromHeaders,
|
|
} from "@/app/api/kis/domestic/_shared";
|
|
|
|
/**
|
|
* @file app/api/kis/domestic/balance/route.ts
|
|
* @description 국내주식 계좌 잔고/보유종목 조회 API
|
|
*/
|
|
|
|
/**
|
|
* 대시보드 잔고 조회 API
|
|
* @returns 총자산/손익/보유종목 목록
|
|
* @see features/dashboard/hooks/use-dashboard-data.ts 대시보드 초기 로드/새로고침에서 호출합니다.
|
|
*/
|
|
export async function GET(request: Request) {
|
|
const hasSession = await hasKisApiSession();
|
|
if (!hasSession) {
|
|
return createKisApiErrorResponse({
|
|
status: 401,
|
|
code: KIS_API_ERROR_CODE.AUTH_REQUIRED,
|
|
message: "로그인이 필요합니다.",
|
|
});
|
|
}
|
|
|
|
const credentials = readKisCredentialsFromHeaders(request.headers);
|
|
|
|
if (!hasKisConfig(credentials)) {
|
|
return createKisApiErrorResponse({
|
|
status: 400,
|
|
code: KIS_API_ERROR_CODE.CREDENTIAL_REQUIRED,
|
|
message: "KIS API 키 설정이 필요합니다.",
|
|
});
|
|
}
|
|
|
|
const account = readKisAccountParts(request.headers);
|
|
if (!account) {
|
|
return createKisApiErrorResponse({
|
|
status: 400,
|
|
code: KIS_API_ERROR_CODE.ACCOUNT_REQUIRED,
|
|
message:
|
|
"계좌번호가 필요합니다. 설정에서 계좌번호(예: 12345678-01)를 입력해 주세요.",
|
|
});
|
|
}
|
|
|
|
try {
|
|
const result = await getDomesticDashboardBalance(account, credentials);
|
|
const response: DashboardBalanceResponse = {
|
|
source: "kis",
|
|
tradingEnv: normalizeTradingEnv(credentials.tradingEnv),
|
|
summary: result.summary,
|
|
holdings: result.holdings,
|
|
fetchedAt: new Date().toISOString(),
|
|
};
|
|
|
|
return NextResponse.json(response, {
|
|
headers: {
|
|
"cache-control": "no-store",
|
|
},
|
|
});
|
|
} catch (error) {
|
|
return createKisApiErrorResponse({
|
|
status: 500,
|
|
code: KIS_API_ERROR_CODE.UPSTREAM_FAILURE,
|
|
message: toKisApiErrorMessage(error, "잔고 조회 중 오류가 발생했습니다."),
|
|
});
|
|
}
|
|
}
|