Volver a la lección

Archivo funcional original

public/app.js

El código y las páginas de ejemplo funcionales conservan sus identificadores y textos de muestra originales. La lección y las instrucciones de los archivos los explican en tu idioma.

const form = document.querySelector("form"),
  status = document.querySelector("[role=status]"),
  result = document.querySelector("#result");
form.addEventListener("submit", async (e) => {
  e.preventDefault();
  const b = form.querySelector("button");
  b.disabled = true;
  result.textContent = "";
  status.textContent = "Loading repository…";
  try {
    const owner = form.elements.owner.value.trim(),
      repo = form.elements.repo.value.trim();
    const r = await fetch(
      "https://api.github.com/repos/" +
        encodeURIComponent(owner) +
        "/" +
        encodeURIComponent(repo),
      {
        headers: { Accept: "application/vnd.github+json" },
        signal: AbortSignal.timeout(10000),
      },
    );
    if (r.status === 404) throw Error("Repository not found or not publicly accessible.");
    if (r.status === 403 || r.status === 429)
      throw Error("Request restricted or rate limited. Try later.");
    if (!r.ok) throw Error("The repository service is unavailable.");
    const data = await r.json();
    if (typeof data.full_name !== "string" || !Number.isFinite(data.stargazers_count))
      throw Error("Unexpected repository response.");
    result.textContent =
      data.full_name +
      " — " +
      data.stargazers_count +
      " stars. " +
      (data.description || "No description provided.");
    status.textContent = "Repository loaded.";
  } catch (err) {
    status.textContent =
      err.name === "TimeoutError" ? "The request timed out. Try again." : err.message;
  } finally {
    b.disabled = false;
  }
});