Waafir
이 페이지는 사람의 검토를 기다리는 기계 번역입니다. 오류가 있을 수 있습니다.

비동기 NDJSON으로 대출 테이프 대량 가져오기

이 레시피는 Waafir 대출 포트폴리오의 기본 수집 흐름을 보여 줍니다. 대출 테이프 엔터티당 한 행씩 담긴 NDJSON(줄 바꿈으로 구분된 JSON) 파일을 비동기 가져오기 엔드포인트에 제출한 다음, 워커가 처리를 마칠 때까지 가져오기 상태를 폴링합니다.

이 흐름을 사용해야 하는 경우

비동기 NDJSON 가져오기 흐름은 어느 정도 이상의 행 수를 처리하는 표준 수집 경로입니다. 수백만 행에 이르는 과거 데이터 일괄 적재까지 확장되며, 일일 증분 제출에도 같은 흐름이 사용됩니다. 아래 예제에서는 loan 가져오기를 사용합니다. 같은 흐름이 borrower, scheduled_repayment, actual_payment, collateral, collateral_valuation 종류도 받습니다. kind 필드와 행 형식만 바꾸면 나머지는 모두 동일합니다.

흐름의 구성

코드가 수행해야 하는 단계는 세 가지이며, 그 사이에 파일이 거치는 단계가 하나 있습니다.

  1. POST /api/v1/monitoring/loan/imports — 업로드하려는 내용(종류, 파일 이름, 크기)을 선언합니다. 응답에는 업로드 URL과 가져오기 ID가 포함됩니다.
  2. 업로드 URL에 NDJSON 본문을 PUT합니다 — 파일은 제출된 그대로 변경 없이 저장됩니다.
  3. POST /api/v1/monitoring/loan/imports/{id}/commit — 업로드가 끝났음을 Waafir에 알립니다. 가져오기가 pending_upload에서 queued로 이동하고, 워커가 배치 처리를 시작합니다.
  4. GET /api/v1/monitoring/loan/imports/{id} — status가 succeeded, partial, failed, cancelled 중 하나가 될 때까지 폴링합니다.

레시피

# curl — bulk import flow (loan kind)
set -euo pipefail

PAT="${WAAFIR_PAT}"
BASE_URL="${WAAFIR_BASE_URL:-https://app.waafir.io}"
NDJSON_FILE="loans-2026-05-22.ndjson"

# Step 1 — start the import and capture the upload URL + import ID.
START=$(curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports" \
  -H "Authorization: Bearer ${PAT}" \
  -H "Content-Type: application/json" \
  -d "$(cat <<JSON
{
  "kind": "loan",
  "filename": "${NDJSON_FILE}",
  "sizeBytes": $(stat -c%s "${NDJSON_FILE}")
}
JSON
)")

IMPORT_ID=$(echo "$START" | jq -r .importId)
UPLOAD_URL=$(echo "$START" | jq -r .uploadUrl)

# Step 2 — PUT the NDJSON body to the upload URL. The `headers` field
# on the start response carries the headers the upload URL was signed
# with — apply them all, or the upload is rejected with a signature
# mismatch. At minimum `Content-Type: application/x-ndjson`.
HEADER_ARGS=$(echo "$START" | jq -r '.headers | to_entries[] | "-H \"\(.key): \(.value)\""')
eval curl -fsS -X PUT --data-binary @"\"${NDJSON_FILE}\"" $HEADER_ARGS "\"${UPLOAD_URL}\""

# Step 3 — commit so the worker enqueues the import.
curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}/commit" \
  -H "Authorization: Bearer ${PAT}"

# Step 4 — poll status until it reaches a terminal value.
while :; do
  STATUS=$(curl -fsS "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}" \
    -H "Authorization: Bearer ${PAT}" | jq -r .status)
  echo "import ${IMPORT_ID}: ${STATUS}"
  case "${STATUS}" in
    succeeded|partial|failed|cancelled) break ;;
  esac
  sleep 5
done
// TypeScript — bulk import flow (loan kind)
import { readFileSync, statSync } from "node:fs";

const PAT = process.env.WAAFIR_PAT!;
const BASE_URL = process.env.WAAFIR_BASE_URL ?? "https://app.waafir.io";
const NDJSON_FILE = "loans-2026-05-22.ndjson";

const headers = { Authorization: `Bearer ${PAT}`, "Content-Type": "application/json" };

// Step 1 — start the import.
const startRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports`, {
    method: "POST",
    headers,
    body: JSON.stringify({
        kind: "loan",
        filename: NDJSON_FILE,
        sizeBytes: statSync(NDJSON_FILE).size,
    }),
});
if (!startRes.ok) throw new Error(`start failed: ${startRes.status} ${await startRes.text()}`);
const { importId, uploadUrl, headers: uploadHeaders } = (await startRes.json()) as {
    importId: string;
    uploadUrl: string;
    headers: Record<string, string>;
};

// Step 2 — PUT the NDJSON body to the upload URL with the headers
// the URL was signed against. Skipping them gets the upload
// rejected with a signature mismatch.
const putRes = await fetch(uploadUrl, {
    method: "PUT",
    headers: uploadHeaders,
    body: readFileSync(NDJSON_FILE),
});
if (!putRes.ok) throw new Error(`upload failed: ${putRes.status}`);

// Step 3 — commit.
const commitRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}/commit`, {
    method: "POST",
    headers: { Authorization: `Bearer ${PAT}` },
});
if (!commitRes.ok) throw new Error(`commit failed: ${commitRes.status} ${await commitRes.text()}`);

// Step 4 — poll.
const TERMINAL = new Set(["succeeded", "partial", "failed", "cancelled"]);
while (true) {
    const statusRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}`, {
        headers: { Authorization: `Bearer ${PAT}` },
    });
    const body = (await statusRes.json()) as { status: string };
    console.log(`import ${importId}: ${body.status}`);
    if (TERMINAL.has(body.status)) break;
    await new Promise((r) => setTimeout(r, 5_000));
}
# python — bulk import flow (loan kind)
import os
import time
import requests
from pathlib import Path

PAT = os.environ["WAAFIR_PAT"]
BASE_URL = os.environ.get("WAAFIR_BASE_URL", "https://app.waafir.io")
NDJSON_FILE = Path("loans-2026-05-22.ndjson")

headers = {"Authorization": f"Bearer {PAT}", "Content-Type": "application/json"}

# Step 1 — start the import.
start = requests.post(
    f"{BASE_URL}/api/v1/monitoring/loan/imports",
    headers=headers,
    json={
        "kind": "loan",
        "filename": NDJSON_FILE.name,
        "sizeBytes": NDJSON_FILE.stat().st_size,
    },
    timeout=30,
)
start.raise_for_status()
payload = start.json()
import_id = payload["importId"]
upload_url = payload["uploadUrl"]
upload_headers = payload["headers"]  # signed-into the URL; must be sent on PUT

# Step 2 — PUT the NDJSON body to the upload URL with the headers
# the URL was signed against. Skipping them gets the upload
# rejected with a signature mismatch.
with NDJSON_FILE.open("rb") as fh:
    put = requests.put(upload_url, data=fh, headers=upload_headers, timeout=300)
    put.raise_for_status()

# Step 3 — commit.
commit = requests.post(
    f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}/commit",
    headers={"Authorization": f"Bearer {PAT}"},
    timeout=30,
)
commit.raise_for_status()

# Step 4 — poll.
terminal = {"succeeded", "partial", "failed", "cancelled"}
while True:
    status = requests.get(
        f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}",
        headers={"Authorization": f"Bearer {PAT}"},
        timeout=30,
    ).json()
    print(f"import {import_id}: {status['status']}")
    if status["status"] in terminal:
        break
    time.sleep(5)

확인할 사항

status가 succeeded에 도달하면 NDJSON 파일의 모든 행이 실제 행으로 반영된 것입니다. 응답에는 rowCountProcessed, rowCountSucceeded, rowCountFailed도 표시되며, 문제없이 실행되었다면 성공 건수가 파일의 행 수와 같습니다.

status가 partial에 도달하면 일부 행은 반영되고 일부는 반영되지 않은 것입니다. 부분 실패 검사 레시피로 이동해 행별 오류를 페이지 단위로 살펴보고, 문제가 된 행을 수정해 다시 제출할지 아니면 부분 결과를 받아들일지 결정하세요.

failed 상태는 반영된 행이 하나도 없다는 뜻입니다. errorSummary.samples 필드에는 처음 10개의 오류 페이로드가 담기며, 나머지는 부분 실패 레시피에서 설명하는 페이지 단위 오류 엔드포인트로 조회할 수 있습니다.