Bỏ qua đến nội dung

Tài liệu kỹ thuật

Tích hợp LRS trong một buổi chiều.

Gọi API từ JavaScript

Chưa có thư viện chính thức — API là REST JSON nên fetch là đủ. Hàm mẫu gắn sẵn API key, Idempotency-Key, xử lý lỗi và tự thử lại khi bị giới hạn tần suất.

Hàm mẫu dưới đây chạy trên Node.js 20 trở lên. Bạn có thể chép vào dự án và đổi tên cho hợp với quy ước của mình.

Lưu ý: API key cấp quyền thao tác dữ liệu của tổ chức. Chỉ gọi LRS từ máy chủ của bạn; không đưa khoá vào mã chạy trên trình duyệt hay ứng dụng di động.

Hàm mẫu

JavaScript
const BASE_URL = "https://api.lrsvn.com/v1";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export class LrsError extends Error {
  constructor(status, body) {
    super(body?.message ?? "Yêu cầu tới LRS thất bại");
    this.status = status;
    this.code = body?.code;
    this.fields = body?.fields;
    this.requestId = body?.request_id;
  }
}

export async function lrs(method, path, { body, idempotencyKey, apiKey = process.env.LRS_API_KEY } = {}) {
  const headers = { Authorization: "Bearer " + apiKey };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  // Khoá được giữ nguyên qua các lần thử lại của cùng một yêu cầu.
  if (method !== "GET") headers["Idempotency-Key"] = idempotencyKey ?? crypto.randomUUID();

  for (let attempt = 0; ; attempt++) {
    const res = await fetch(BASE_URL + path, {
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body),
    });
    if (res.status === 429 && attempt < 3) {
      await sleep((Number(res.headers.get("Retry-After")) || 2 ** attempt) * 1000);
      continue;
    }
    const data = res.status === 204 ? null : await res.json();
    if (!res.ok) throw new LrsError(res.status, data);
    return data;
  }
}

Ví dụ: một sự kiện anti-cheat

JavaScript
// Game server báo một lần phát hiện (scope anticheat:ingest). Dùng external_ref làm
// Idempotency-Key để gửi lại cùng sự kiện không tạo bản ghi thứ hai.
const externalRef = "match-88231-evt-0042";
const event = await lrs("POST", "/anticheat/events", {
  body: {
    external_ref: externalRef,
    player_id: "player_10293",
    signature: "aimbot.snap.v3",
    confidence: 97.5,
  },
  idempotencyKey: externalRef,
});

// Xem lại các sự kiện của người chơi này (scope anticheat:read).
// Kết quả có dạng { data: [...], meta: { total, page, limit } }.
const history = await lrs("GET", "/anticheat/events?player_id=player_10293&limit=20");

// Nếu là nhận diện nhầm: bỏ qua và đánh dấu false positive (scope anticheat:write).
await lrs("POST", "/anticheat/events/" + event.id + "/action", {
  body: { action: "ignore", false_positive: true, reason: "Người chơi đã được xác minh." },
});

Thuộc tính của LrsError

Thuộc tínhKiểuMô tả
statusnumberMã HTTP của phản hồi.
codestringMã lỗi của LRS, ví dụ validation_error.
fieldsobjectLỗi theo từng trường (chỉ có với lỗi nhập liệu).
requestIdstringrequest_id — gửi kèm khi liên hệ hỗ trợ.