--- import FontAwesome from "@components/form/FontAwesome.svelte"; import { error } from "@utils/logger"; const { github } = Astro.props; interface GitHubRepoData { stargazers_count?: number; forks_count?: number; open_issues_count?: number; language?: string; license?: { spdx_id?: string; name?: string }; } /** * For a given `user/repo` fetch repository stats from the GitHub API data * If API key is available through env var, use it to increase rate limit * Returns the response data and status code (200 == success) * @param repo */ const fetchGitHubData = async (repo: string) => { const apiKey = import.meta.env.GITHUB_API_KEY; const headers = new Headers(); if (apiKey) { headers.append("Authorization", `token ${apiKey}`); } let data: GitHubRepoData = {}; let statusCode; const response = await fetch(`https://api.github.com/repos/${repo}`, { headers: headers, }).catch((e) => { error('GitHub API', `Network error for ${repo}: ${e.message}`); // Return a placeholder response to handle this gracefully return null; }); // Check if fetch was successful but caught by the catch block if (!response) { return { data, statusCode: 503 }; // Use an appropriate error status code } statusCode = response.status; // Only attempt to parse JSON if the response was OK if (response.ok) { data = await response.json(); } else { error('GitHub API', `HTTP ${response.status} for ${repo}`); } return { data, statusCode }; }; /** * Given a license object, return SPDX ID, or a formatted name * @param license */ const formatLicense = (license?: { spdx_id?: string, name?: string }) => { if (!license) { return "Unknown"; } if (license.spdx_id === "NOASSERTION") { return "No License"; } return license.spdx_id; } /** * Given a (possibly large) number, return a formatted string * E.g. If greater than thousand, then return in k format * @param num */ const formatBigNumber = (num: number | undefined) => { if (num == null) return 0; if (num > 1000) { return `${(num / 1000).toFixed(1)}k`; } return num; } // Initiate GitHub fetch, and make available to the component const stats = await fetchGitHubData(github); const { stargazers_count, forks_count, open_issues_count, language, license, } = stats.data; ---