Bỏ qua, tới nội dung chính

Bắt đầu nhanh

Gửi một job và lấy kết quả, từ đầu tới cuối.

SDK chưa phát hành. Nội dung dưới đây dùng HTTP thuần.

Trình tự đầy đủ: có khóa API, gửi job kèm Idempotency-Key, chờ job vào trạng thái kết thúc, rồi lấy kết quả. Ví dụ dưới đây viết bằng TypeScript và chạy được ở phía máy chủ.

import { randomUUID } from "node:crypto";

const BASE = "https://<your-host>/api/v1/partners/addons/route-optimization";
const headers = { "api-key": process.env.ROUTE4GREEN_API_KEY! };

// 1. Submit. Generate the key once, reuse it for every retry of THIS submit.
const idempotencyKey = randomUUID();
const submitted = await fetch(`${BASE}/jobs`, {
  method: "POST",
  headers: { ...headers, "Idempotency-Key": idempotencyKey, "content-type": "application/json" },
  body: JSON.stringify({ external_reference: "your-own-id" }),
}).then((r) => r.json());

if (!submitted.success) throw new Error(submitted.error_code);
const jobId: string = submitted.data.id;

// 2. Wait. Stop on any terminal state, and bound the loop.
const TERMINAL = new Set(["SUCCEEDED", "PARTIAL", "FAILED", "CANCELLED"]);
let status = "QUEUED";
const deadline = Date.now() + 30 * 60 * 1000;

while (!TERMINAL.has(status) && Date.now() < deadline) {
  await new Promise((r) => setTimeout(r, 5_000));
  const polled = await fetch(`${BASE}/jobs/${jobId}`, { headers }).then((r) => r.json());
  if (!polled.success) throw new Error(polled.error_code);
  status = polled.data.status;
}

// 3. Collect, but only from a state that has a result.
if (status === "SUCCEEDED" || status === "PARTIAL") {
  const result = await fetch(`${BASE}/jobs/${jobId}/result`, { headers }).then((r) => r.json());
  if (result.success) use(result.data);
}

Khóa API hiện được cấp bằng tay. Nếu chưa có, bạn đăng ký dùng thử trước.