사용한 로직
/**
* 환율 관련 비즈니스 로직을 처리하는 서비스
*/
export class ExchangeRateService {
/**
* @param {string} authkey - 한국수출입은행 API 키
*/
constructor(authkey) {
this.authkey = authkey;
}
/**
* 지정된 날짜의 환율 데이터를 가져옵니다. (캐시 우선 전략)
* @param {string} date - 조회 날짜 (YYYYMMDD)
*/
async getRatesByDate(date) {
try {
const apiData = await this._fetchExchangeApi(date);
if (!apiData || apiData.length === 0) {
return [];
}
// 3. API 데이터를 DB 형식에 맞게 정제하여 저장
const formattedData = this._formatApiData(apiData, date);
return formattedData;
} catch (error) {
console.error('[ExchangeRateService Error]:', error);
throw error;
}
}
/** 내부 API 호출 전용 (private-like) */
async _fetchExchangeApi(date) {
const url = `https://oapi.koreaexim.go.kr/site/program/financial/exchangeJSON?authkey=${this.authkey}&searchdate=${date}&data=AP01`;
const res = await fetch(url);
if (!res.ok) throw new Error('API 응답 실패');
return await res.json();
}
/** 데이터를 DB 스키마에 맞게 매핑 */
_formatApiData(apiData, date) {
return apiData.map((item) => ({
cur_unit: item.cur_unit,
cur_nm: item.cur_nm,
ttb: item.ttb?.replace(/,/g, ''),
tts: item.tts?.replace(/,/g, ''),
deal_bas_r: item.deal_bas_r?.replace(/,/g, ''),
bkpr: item.bkpr?.replace(/,/g, ''),
yy_efee_r: item.yy_efee_r?.replace(/,/g, ''),
ten_dd_efee_r: item.ten_dd_efee_r?.replace(/,/g, ''),
kftc_deal_bas_r: item.kftc_deal_bas_r?.replace(/,/g, ''),
kftc_bkpr: item.kftc_bkpr?.replace(/,/g, ''),
edate: date,
}));
}
}