← Alle Anleitungen

Eine Live-Meisterschaftstabelle bauen

Zeigen Sie die Fahrerwertung von MotoGP, Moto2 oder Moto3 auf Ihrer Website – über einen kleinen Caching-Proxy, der Ihren RapidAPI-Schlüssel aus dem Browser heraushält.

10 Min. Lesezeit

Eine Wertungstabelle ist das häufigste MotoGP-Widget auf Nachrichtenseiten, Fanblogs und Clubseiten. Diese Anleitung baut eine in zwei Teilen:

  1. Ein Proxy – ein winziger Server-Endpunkt, der Ihren Schlüssel hält und Antworten cacht.
  2. Ein Widget – reines HTML und JavaScript, das die Tabelle aus dem Proxy rendert.

1. Der Proxy

Der Browser darf Ihren RapidAPI-Schlüssel nie sehen, daher spricht die Seite mit Ihrem eigenen Endpunkt. Dieses Beispiel nutzt Node.js 18+ und Express; dieselben 30 Zeilen funktionieren als Netlify-, Vercel- oder Cloudflare-Funktion.

// 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"));

Zwei Details sind wichtig:

  • Eingaben validieren. Es werden nur die drei bekannten Kategorien weitergeleitet, damit niemand Ihren Proxy nutzen kann, um Ihr Kontingent für beliebige Endpunkte zu verbrauchen.
  • Cachen. Ein Upstream-Aufruf pro Stunde und Kategorie bedient alle Besucher.

2. Das Widget

<!-- 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>

Starten Sie RAPIDAPI_KEY=... node server.js und öffnen Sie http://localhost:3000.

Varianten

  • Abstand zum Führenden. Fügen Sie eine Spalte mit rows[0].total_points - r.total_points hinzu.
  • Teamwertung. Richten Sie eine zweite Route auf /standings/seasons/{year}/teams – die Zeilen enthalten team_name und total_points.
  • Hersteller. /standings/seasons/{year}/manufacturers liefert Zeilen mit manufacturer_name.
  • Statische Websites. Rufen Sie die Wertung in Ihrem Build-Schritt ab (Astro, Next.js, Hugo) und bauen Sie nach jedem Rennwochenende neu – ganz ohne Proxy.
Nächste Anleitung → Fahrerprofilseiten mit Karrierestatistiken