← 全部指南

构建实时锦标赛积分榜表格

通过一个小型缓存代理,在你的网站上展示 MotoGP、Moto2 或 Moto3 车手锦标赛,并让 RapidAPI 密钥远离浏览器。

阅读约 10 分钟

积分榜表格是新闻网站、车迷博客和俱乐部页面上最常见的 MotoGP 小组件。本指南分两部分来构建:

  1. 代理:一个持有密钥并缓存响应的小型服务端接口。
  2. 小组件:用纯 HTML 和 JavaScript 从代理渲染表格。

1. 代理

浏览器绝不能看到你的 RapidAPI 密钥,所以页面应调用你自己的接口。本例使用 Node.js 18+ 和 Express;同样的 30 行代码也可作为 Netlify、Vercel 或 Cloudflare 函数运行。

// server.js — npm install express
import express from "express";

const HOST = "motogp-api-championship-data-statistics.p.rapidapi.com";
const KEY = process.env.RAPIDAPI_KEY;
if (!KEY) throw new Error("RAPIDAPI_KEY is not set");

const CATEGORIES = new Set(["MOTOGP", "MOTO2", "MOTO3"]);
const TTL_MS = 60 * 60 * 1000; // 1 hour
const cache = new Map();

async function cached(path) {
  const hit = cache.get(path);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.body;
  const res = await fetch(`https://${HOST}${path}`, {
    headers: { "X-RapidAPI-Key": KEY, "X-RapidAPI-Host": HOST },
  });
  if (!res.ok) throw new Error(`Upstream ${res.status}`);
  const body = await res.json();
  cache.set(path, { at: Date.now(), body });
  return body;
}

const app = express();

app.get("/api/standings", async (req, res) => {
  const category = String(req.query.category ?? "MOTOGP").toUpperCase();
  if (!CATEGORIES.has(category)) return res.status(400).json({ error: "Unknown category" });
  try {
    const { data: season } = await cached("/seasons/latest");
    const { data } = await cached(`/standings/seasons/${season.year}/riders?category=${category}`);
    res.set("Cache-Control", "public, max-age=300").json({ season: season.year, category, rows: data });
  } catch (err) {
    res.status(502).json({ error: "Standings are unavailable right now" });
  }
});

app.use(express.static("public"));
app.listen(3000, () => console.log("http://localhost:3000"));

有两个细节很重要:

  • 校验输入。 只转发三个已知组别,这样没人能利用你的代理,把你的配额消耗在任意端点上。
  • 缓存。 每个组别每小时一次上游调用,即可服务所有访客。

2. 小组件

<!-- public/index.html -->
<div class="standings">
  <div role="tablist">
    <button data-category="MOTOGP" aria-selected="true">MotoGP</button>
    <button data-category="MOTO2">Moto2</button>
    <button data-category="MOTO3">Moto3</button>
  </div>
  <table>
    <caption></caption>
    <thead>
      <tr><th>Pos</th><th>Rider</th><th>Team</th><th>Wins</th><th>Pts</th></tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

<script type="module">
  const tbody = document.querySelector(".standings tbody");
  const caption = document.querySelector(".standings caption");

  function cell(text) {
    const td = document.createElement("td");
    td.textContent = text; // textContent, never innerHTML, for data from an API
    return td;
  }

  async function load(category) {
    caption.textContent = "Loading…";
    const res = await fetch(`/api/standings?category=${category}`);
    if (!res.ok) {
      caption.textContent = "Standings are unavailable right now.";
      tbody.replaceChildren();
      return;
    }
    const { season, rows } = await res.json();
    caption.textContent = `${season} ${category} riders' championship`;
    tbody.replaceChildren(
      ...rows.map((r) => {
        const tr = document.createElement("tr");
        tr.append(
          cell(r.position),
          cell(`#${r.rider_number} ${r.rider_name}`),
          cell(r.team_name),
          cell(r.wins),
          cell(r.total_points),
        );
        return tr;
      }),
    );
  }

  document.querySelectorAll("[data-category]").forEach((button) => {
    button.addEventListener("click", () => {
      document.querySelectorAll("[data-category]").forEach((b) => b.setAttribute("aria-selected", b === button));
      load(button.dataset.category);
    });
  });

  load("MOTOGP");
</script>

运行 RAPIDAPI_KEY=... node server.js,然后打开 http://localhost:3000。

变体

  • 与领跑者的差距。 添加一列,值为 rows[0].total_points - r.total_points。
  • 车队锦标赛。 让第二条路由指向 /standings/seasons/{year}/teams,每行包含 team_name 和 total_points。
  • 制造商。 /standings/seasons/{year}/manufacturers 返回带 manufacturer_name 的行。
  • 静态网站。 在构建步骤中获取积分榜(Astro、Next.js、Hugo),并在每个比赛周末之后重新构建,完全不需要代理。
下一篇指南 → 带生涯统计的车手资料页