|
| 1 | +import { ContributionTotals, GitHubUserData, PullRequestNode, RepoNode } from "@/types/github"; |
| 2 | +import { graphql } from "@octokit/graphql"; |
| 3 | + |
| 4 | +if (!process.env.GITHUB_TOKEN) { |
| 5 | + throw new Error("Missing GITHUB_TOKEN"); |
| 6 | +} |
| 7 | + |
| 8 | +const client = graphql.defaults({ |
| 9 | + headers: { |
| 10 | + authorization: `token ${process.env.GITHUB_TOKEN}`, |
| 11 | + }, |
| 12 | +}); |
| 13 | + |
| 14 | + |
| 15 | +const QUERY = /* GraphQL */ ` |
| 16 | + query FetchUserData($login: String!, $repoCount: Int = 100, $prCount: Int = 100) { |
| 17 | + user(login: $login) { |
| 18 | + repositories( |
| 19 | + first: $repoCount |
| 20 | + privacy: PUBLIC |
| 21 | + ownerAffiliations: OWNER |
| 22 | + orderBy: { field: STARGAZERS, direction: DESC } |
| 23 | + ) { |
| 24 | + nodes { |
| 25 | + name |
| 26 | + stargazerCount |
| 27 | + forkCount |
| 28 | + watchers { |
| 29 | + totalCount |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + pullRequests( |
| 34 | + first: $prCount |
| 35 | + states: [MERGED] |
| 36 | + orderBy: { field: CREATED_AT, direction: DESC } |
| 37 | + ) { |
| 38 | + nodes { |
| 39 | + merged |
| 40 | + additions |
| 41 | + deletions |
| 42 | + repository { |
| 43 | + nameWithOwner |
| 44 | + stargazerCount |
| 45 | + owner { |
| 46 | + login |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + contributionsCollection { |
| 52 | + totalCommitContributions |
| 53 | + totalPullRequestContributions |
| 54 | + totalIssueContributions |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +`; |
| 59 | + |
| 60 | +export async function fetchGitHubUserData( |
| 61 | + username: string |
| 62 | +): Promise<GitHubUserData> { |
| 63 | + const { user } = await client<{ user: any }>(QUERY, { login: username }); |
| 64 | + |
| 65 | + if (!user) { |
| 66 | + throw new Error("User not found"); |
| 67 | + } |
| 68 | + |
| 69 | + return { |
| 70 | + repos: user.repositories.nodes as RepoNode[], |
| 71 | + pullRequests: user.pullRequests.nodes as PullRequestNode[], |
| 72 | + contributions: user.contributionsCollection as ContributionTotals, |
| 73 | + }; |
| 74 | +} |
0 commit comments