첫 번역 요청하기

인라인 JSON 작업을 만들고 시작한 뒤, Node.js로 스페인어 번역 결과를 저장하세요.

영어 메시지 두 개를 스페인어로 번역해 es.json로 저장하세요. Node.js 22 이상, Lingo.dev 조직, 번역 모델이 설정된 엔진, 해당 엔진에서 번역할 권한이 있는 API 키가 필요합니다.

첫 요청에서는 휴먼 리뷰 없이 번역을 실행하도록 엔진을 설정하세요. 제출부터 다운로드까지 정상적으로 작동하는 것을 확인한 뒤 검토를 추가할 수 있습니다.

요청 설정하기 #

사용 중인 조직과 엔진의 ID로 셸에서 다음 값을 설정하세요. ID를 찾는 방법은 조직 및 엔진 선택에서 확인하세요.

sh
export LINGO_API_KEY="YOUR_API_KEY"
export LINGO_ORGANIZATION_ID="YOUR_ORGANIZATION_ID"
export LINGO_ENGINE_ID="YOUR_ENGINE_ID"
export LINGO_REQUEST_ID="welcome-messages-v1-es"

LINGO_REQUEST_ID는 이번 제출을 식별하는 값입니다. 같은 요청을 다시 시도할 때는 이 값을 재사용하세요. 원문, 로캘 또는 다른 요청 옵션이 바뀌면 새 값을 사용하세요.

작업 생성, 시작 및 다운로드하기 #

다음 프로그램을 translate.mjs로 저장하세요:

js
import { writeFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";

const origin = "https://api.lingo.dev";
const {
  LINGO_API_KEY: apiKey,
  LINGO_ORGANIZATION_ID: orgId,
  LINGO_ENGINE_ID: engineId,
  LINGO_REQUEST_ID: requestId,
} = process.env;
if (!apiKey || !orgId || !engineId || !requestId) {
  throw new Error("Set LINGO_API_KEY, LINGO_ORGANIZATION_ID, LINGO_ENGINE_ID, and LINGO_REQUEST_ID");
}

async function request(path, options = {}) {
  const response = await fetch(new URL(path, origin), {
    ...options,
    headers: { "X-API-Key": apiKey, ...options.headers },
    signal: AbortSignal.timeout(30_000),
  });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  }
  return response;
}

let job = await (
  await request(`/v2/organizations/${encodeURIComponent(orgId)}/localization/jobs`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "Idempotency-Key": requestId },
    body: JSON.stringify({
      engineId,
      sourceLocale: "en",
      targetLocales: ["es"],
      documents: [
        {
          key: "messages.json",
          format: { type: "json", options: { context: "Account settings buttons" } },
          source: { content: { save: "Save changes", cancel: "Cancel" } },
        },
      ],
    }),
  })
).json();

await writeFile("translation-job.json", JSON.stringify({ id: job.id, requestId }, null, 2));
console.log(`Created ${job.id}; saved its ID to translation-job.json`);
if (job.uploads.length !== 0) throw new Error("Upload the artifacts listed in job.uploads before starting");

job = await (
  await request(`/v2/localization/jobs/${encodeURIComponent(job.id)}/start`, {
    method: "POST",
  })
).json();

const deadline = Date.now() + 120_000;
while (["Pending", "Running"].includes(job.status._tag)) {
  if (Date.now() >= deadline) {
    throw new Error(`Still waiting for ${job.id}. Keep its ID and retrieve it again later.`);
  }
  await delay(2000);
  job = await (await request(`/v2/localization/jobs/${encodeURIComponent(job.id)}`)).json();
}

const target = job.documents
  .find((document) => document.key === "messages.json")
  ?.targets.find((item) => item.locale === "es");
if (target?.status._tag !== "Completed") {
  throw new Error(`Translation did not complete: ${JSON.stringify(job.status)}`);
}
const translated = await (await request(target.status.downloadUrl)).json();
await writeFile("es.json", JSON.stringify(translated, null, 2) + "\n");
console.log("Saved es.json");

실행하세요:

sh
node translate.mjs

es.json를 열어 save와 cancel를 확인하세요. 두 항목 모두 스페인어 텍스트가 들어 있어야 합니다. API는 작업을 생성할 때 인라인 JSON을 저장하지만, 별도로 /start 요청을 보내야 합니다.

중단된 요청 복구하기 #

작업 생성 후 프로그램이 중단되면 translation-job.json에서 ID를 읽어 작업을 조회하세요. 같은 Idempotency-Key로 동일한 생성 요청을 다시 보내면 원래 작업을 조회합니다. /start를 다시 요청하면 새 작업을 만들지 않고 기존 작업을 이어서 진행합니다.

폴링 제한 시간이 초과되면 이 프로그램의 대기만 끝나고 서버의 작업은 취소되지 않습니다. 작업 ID를 보관해 두고 나중에 다시 확인하세요. 실패한 대상이 있다면 해당 메시지와 단계별 결과를 확인한 뒤, 새 키로 수정된 요청을 제출하세요.

다음으로 파일을 번역하거나, JSON 힌트와 키 제어 기능을 추가하거나, 애플리케이션에 작업 수명 주기를 통합해 보세요.