실습 핵심 학습 개념 기본 노드 사용
여행자 환율 리포트 • Code 노드 • Schedule Trigger
• HTTP

[n8n workflow]

image.png

1. Trigger

매일 아침 10시에 실행하도록 Rule 설정

2. Task

2-1. Get row

환율 데이터를 가져올 수 있도록 code 값이 있는 테이블 생성하여 읽어오기

image.png

2-2. HTTP Request

한국은행 Open API 서비스( https://ecos.bok.or.kr/api/#/ ) 사용해서 일주일 치 환율 데이터 가져오기

<https://ecos.bok.or.kr/api/StatisticSearch/인증키/json/kr/1/100/731Y001/D/>{{ $now.minus({days:7}).toFormat('yyyyMMdd') }}/{{ $now.toFormat('yyyyMMdd') }}/{{ $json.code }}

2-3. Split Out

배열(Array)을 여러 개의 Item으로 쪼갬

image.png

2-4. Code in JS

Item List에서 통화별 최근 영업일, 직전 영업일 데이터 추출

const currencyData = {};

// 통화별 데이터 모으기
for (const item of items) {
  const row = item.json;

  const key = row.ITEM_CODE1 || row.ITEM_NAME1;

  if (!currencyData[key]) {
    currencyData[key] = [];
  }

  currencyData[key].push(row);
}

// 결과 생성
const result = [];

for (const [key, rows] of Object.entries(currencyData)) {

  // 날짜 최신순 정렬
  rows.sort((a, b) => b.TIME.localeCompare(a.TIME));

  const today = rows[0];
  const yesterday = rows[1] || null;

  const todayRate = Number(today.DATA_VALUE);

  let change = null;
  let changePercent = null;

  if (yesterday) {
    const yesterdayRate = Number(yesterday.DATA_VALUE);

    change = +(todayRate - yesterdayRate).toFixed(4);

    changePercent = +(
      ((todayRate - yesterdayRate) / yesterdayRate) * 100
    ).toFixed(2);
  }

  result.push({
    json: {
      currency: today.ITEM_NAME1,
      today,
      yesterday,
      change,
      changePercent
    }
  });
}

return result;

2-5. Edit Fields

필요한 값들만 뽑아냄