| 57 | } |
| 58 | |
| 59 | export async function fetchGithubStats(username: string) { |
| 60 | const query = ` |
| 61 | query($login: String!) { |
| 62 | user(login: $login) { |
| 63 | contributionsCollection { |
| 64 | contributionCalendar { |
| 65 | totalContributions |
| 66 | } |
| 67 | } |
| 68 | followers { |
| 69 | totalCount |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | `; |
| 74 | |
| 75 | const res = await fetch("https://api.github.com/graphql", { |
| 76 | method: "POST", |
| 77 | headers: { |
| 78 | "Content-Type": "application/json", |
| 79 | Authorization: `Bearer ${process.env.GITHUB_TOKEN}`, |
| 80 | }, |
| 81 | body: JSON.stringify({ |
| 82 | query, |
| 83 | variables: { login: username }, |
| 84 | }), |
| 85 | }); |
| 86 | |
| 87 | const json = await res.json(); |
| 88 | |
| 89 | if (!res.ok || json?.errors?.length) { |
| 90 | const details = |
| 91 | json?.errors |
| 92 | ?.map((e: { message?: string }) => e?.message) |
| 93 | .filter(Boolean) |
| 94 | .join("; ") || `HTTP ${res.status}`; |
| 95 | throw new Error( |
| 96 | `Failed to fetch GitHub stats for "${username}": ${details}` |
| 97 | ); |
| 98 | } |
| 99 | |
| 100 | if (!json?.data?.user) { |
| 101 | throw new Error(`GitHub user "${username}" not found (or inaccessible).`); |
| 102 | } |
| 103 | |
| 104 | const repos = await fetch( |
| 105 | `https://api.github.com/users/${encodeURIComponent( |
| 106 | username |
| 107 | )}/repos?per_page=100&page=1` |
| 108 | ); |
| 109 | |
| 110 | const totalStars = (await repos.json()).reduce( |
| 111 | (acc: number, repo: { stargazers_count: number }) => |
| 112 | acc + repo.stargazers_count, |
| 113 | 0 |
| 114 | ); |
| 115 | |
| 116 | return { |