refactor(repo-card): reduce coupling and indention

This commit is contained in:
ZhenShuo Leo
2025-06-20 21:41:29 +08:00
parent 1f49f8f89f
commit 91fe08d205
+56 -33
View File
@@ -1,36 +1,59 @@
function fetchRepo() { async function fetchRepo() {
const scriptElement = document.currentScript; const script = document.currentScript;
const repoURL = const repoURL = script?.getAttribute("data-repo-url");
scriptElement && scriptElement.getAttribute("data-repo-url") const repoId = script?.getAttribute("data-repo-id");
? scriptElement.getAttribute("data-repo-url")
: (console.error("data-repo-url is null"), null); if (!repoURL || !repoId) return;
const repoId =
scriptElement && scriptElement.getAttribute("data-repo-id") const platforms = {
? scriptElement.getAttribute("data-repo-id") github: {
: (console.error("data-repo-id is null"), null); full_name: "full_name",
const requestObjects = repoId.startsWith("github") description: "description",
? ["full_name", "description", "stargazers_count", "forks"] stargazers_count: "stargazers",
: repoId.startsWith("gitlab") forks: "forks",
? ["name_with_namespace", "description", "star_count", "forks_count"] },
: ["full_name", "description", "stars_count", "forks_count"]; gitlab: {
fetch(repoURL, { name_with_namespace: "name_with_namespace",
headers: new Headers({ description: "description",
"User-agent": "Mozilla/4.0 Custom User Agent", star_count: "star_count",
}), forks_count: "forks_count",
}) },
.then((response) => response.json()) gitea: {
.then((data) => { full_name: "full_name",
requestObjects.forEach((requestObject) => { description: "description",
let element = document.getElementById(`${repoId}-${requestObject}`); stars_count: "stars_count",
if (requestObject === "stargazers_count" && repoId.startsWith("github")) { forks_count: "forks_count",
element = document.getElementById(`${repoId}-stargazers`); },
} codeberg: {
element full_name: "full_name",
? (element.innerHTML = data[requestObject]) description: "description",
: (console.error(`Element '${repoId}-${requestObject}' not found`), null); stars_count: "stars_count",
}); forks_count: "forks_count",
}) },
.catch((error) => console.error(error)); forgejo: {
full_name: "full_name",
description: "description",
stars_count: "stars_count",
forks_count: "forks_count",
},
};
const platform = Object.keys(platforms).find((p) => repoId.startsWith(p)) || "github";
const mapping = platforms[platform];
try {
const response = await fetch(repoURL, {
headers: { "User-agent": "Mozilla/4.0 Custom User Agent" },
});
const data = await response.json();
Object.entries(mapping).forEach(([dataField, elementSuffix]) => {
const element = document.getElementById(`${repoId}-${elementSuffix}`);
if (element) element.innerHTML = data[dataField];
});
} catch (error) {
console.error(error);
}
} }
fetchRepo(); fetchRepo();