### Run Development Server for Git Wrapped API Source: https://github.com/gabriel-pineda/git-wrapped-api/blob/main/README.md This snippet shows how to start the development server for the Git Wrapped API using either Yarn or npm. After installation, these commands will build and launch the application, typically accessible at http://localhost:3000. This allows for real-time development and testing. ```bash # Using yarn yarn dev # Using npm npm run dev ``` -------------------------------- ### Install Dependencies for Git Wrapped API Source: https://github.com/gabriel-pineda/git-wrapped-api/blob/main/README.md These commands demonstrate how to install project dependencies for the Git Wrapped API using either Yarn or npm. Ensure Node.js and npm/yarn are installed as prerequisites. This step is crucial before running the development server or building the project. ```bash # Using yarn yarn install # Using npm npm install ``` -------------------------------- ### Setup Environment Variables for GitHub API Authentication (Bash) Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt Instructions for setting up the local environment file (.env.local) with a GitHub Personal Access Token. This is crucial for authenticating with the GitHub API. ```bash # Create .env.local file in project root cat > .env.local << EOF GITHUB_TOKEN=ghp_your_personal_access_token_here EOF # GitHub token requirements: # - Token type: Classic Personal Access Token # - Required scopes: public_repo, read:user # - Create at: https://github.com/settings/tokens # Verify environment configuration npm run dev # Server starts at http://localhost:3000 ``` -------------------------------- ### Environment Setup for Git Wrapped API Source: https://github.com/gabriel-pineda/git-wrapped-api/blob/main/README.md This snippet shows how to set up the local environment for the Git Wrapped API by creating a .env.local file. It requires a GitHub Personal Access Token to be added to the GITHUB_TOKEN variable. This token is essential for the API to authenticate with GitHub and retrieve user data. ```bash GITHUB_TOKEN=ghp_ ``` -------------------------------- ### GET /api/stats Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt Fetches comprehensive GitHub statistics for a given username. This includes contributions, streaks, language usage, and repository metrics. Requires a `username` query parameter. ```APIDOC ## GET /api/stats ### Description Fetches comprehensive GitHub statistics for a given username including contributions, streaks, language usage, and repository metrics. ### Method GET ### Endpoint `/api/stats` ### Parameters #### Query Parameters - **username** (string) - Required - The GitHub username to fetch statistics for. ### Request Example ```bash curl -X GET "http://localhost:3000/api/stats?username=octocat" ``` ### Response #### Success Response (200) - **longestStreak** (number) - The longest consecutive streak of contributions. - **totalCommits** (number) - The total number of commits made by the user. - **commitRank** (string) - The user's commit activity rank compared to others. - **calendarData** (array) - An array of objects, each representing a day's contribution count. - **contributionCount** (number) - The number of contributions on a specific date. - **date** (string) - The date in 'YYYY-MM-DD' format. - **weekday** (number) - The day of the week (0=Sunday, 1=Monday, ...). - **mostActiveDay** (object) - Information about the day with the most activity. - **name** (string) - The name of the most active day (e.g., "Wednesday"). - **commits** (number) - The number of commits on the most active day. - **mostActiveMonth** (object) - Information about the month with the most activity. - **name** (string) - The name of the most active month (e.g., "March"). - **commits** (number) - The number of commits in the most active month. - **starsEarned** (number) - The total number of stars received across all repositories. - **topLanguages** (array) - An array of strings listing the user's top programming languages. #### Response Example ```json { "longestStreak": 42, "totalCommits": 1547, "commitRank": "Top 1%-3%", "calendarData": [ { "contributionCount": 5, "date": "2024-01-01", "weekday": 1 } ], "mostActiveDay": { "name": "Wednesday", "commits": 12 }, "mostActiveMonth": { "name": "March", "commits": 247 }, "starsEarned": 1234, "topLanguages": ["TypeScript", "Python", "JavaScript"] } ``` #### Error Response (400) - **error** (string) - "Username parameter is required" #### Error Response (500) - **error** (string) - "Failed to fetch GitHub statistics" ``` -------------------------------- ### Fetch GitHub Statistics via cURL Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt Demonstrates how to fetch comprehensive GitHub statistics for a given username using a cURL request to the API's /api/stats endpoint. Includes examples for successful requests, missing username errors, and invalid/non-existent user errors. ```bash # Fetch statistics for a GitHub user curl -X GET "http://localhost:3000/api/stats?username=octocat" # Expected response structure { "longestStreak": 42, "totalCommits": 1547, "commitRank": "Top 1%-3%", "calendarData": [ { "contributionCount": 5, "date": "2024-01-01", "weekday": 1 } ], "mostActiveDay": { "name": "Wednesday", "commits": 12 }, "mostActiveMonth": { "name": "March", "commits": 247 }, "starsEarned": 1234, "topLanguages": ["TypeScript", "Python", "JavaScript"] } # Error response when username is missing curl -X GET "http://localhost:3000/api/stats" # Response: {"error": "Username parameter is required"} (400) # Error response for invalid/non-existent user curl -X GET "http://localhost:3000/api/stats?username=nonexistentuser12345xyz" # Response: {"error": "Failed to fetch GitHub statistics"} (500) ``` -------------------------------- ### Test API Endpoint with curl Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt This snippet shows how to test the Git Wrapped API endpoint using curl. It demonstrates a GET request to the /api/stats endpoint with a specified username. ```shell curl -X GET "http://localhost:3000/api/stats?username=torvalds" ``` -------------------------------- ### Get User Statistics Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt This endpoint retrieves statistics for a given GitHub username. It's useful for generating personalized 'year in review' reports. ```APIDOC ## GET /api/stats ### Description Retrieves comprehensive GitHub activity statistics for a specified user, including coding activity, language usage, and contribution patterns. ### Method GET ### Endpoint /api/stats ### Parameters #### Query Parameters - **username** (string) - Required - The GitHub username to fetch statistics for. ### Request Example ```bash curl -X GET "http://localhost:3000/api/stats?username=torvalds" ``` ### Response #### Success Response (200) - **stats** (object) - An object containing various GitHub statistics. - **totalCommits** (integer) - Total number of commits. - **topLanguages** (array) - Array of top programming languages used. - **language** (string) - Name of the language. - **percentage** (float) - Percentage of usage. - **mostActiveDay** (string) - The day of the week with the most activity. #### Response Example ```json { "stats": { "totalCommits": 1500, "topLanguages": [ { "language": "JavaScript", "percentage": 0.45 }, { "language": "Python", "percentage": 0.30 } ], "mostActiveDay": "Wednesday" } } ``` ``` -------------------------------- ### Calculate GitHub Commit Rank Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt Provides a TypeScript function to calculate a user's GitHub commit rank based on their total contribution count. The function categorizes users into different percentiles relative to the general GitHub population. Examples show how to use the function and interpret its output in an API context. ```typescript import { getCommitRank } from './src/pages/api/stats'; // Calculate rank for different activity levels const rank1 = getCommitRank(5500); // Returns: "Top 0.5%-1%" const rank2 = getCommitRank(1500); // Returns: "Top 1%-3%" const rank3 = getCommitRank(750); // Returns: "Top 5%-10%" const rank4 = getCommitRank(300); // Returns: "Top 10%-15%" const rank5 = getCommitRank(150); // Returns: "Top 25%-30%" const rank6 = getCommitRank(75); // Returns: "Median 50%" const rank7 = getCommitRank(25); // Returns: "Bottom 30%" // Usage in API response const totalCommits = 2500; const commitRank = getCommitRank(totalCommits); console.log(`User has ${totalCommits} commits and ranks in ${commitRank}`); // Output: "User has 2500 commits and ranks in Top 1%-3%" ``` -------------------------------- ### Fetch GitHub User Stats with Octokit and GraphQL Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt This snippet shows how to initialize Octokit with a GitHub token, define a GraphQL query to fetch user contributions and repository stars, and execute the query. It processes the response to return contribution data and total stars, handling potential API errors. ```typescript import { Octokit } from "@octokit/rest"; // Initialize Octokit with authentication const GITHUB_TOKEN = process.env.GITHUB_TOKEN; const octokit = new Octokit({ auth: GITHUB_TOKEN, }); // GraphQL query for comprehensive user statistics const query = ` query($username: String!) { user(login: $username) { contributionsCollection { contributionCalendar { totalContributions weeks { contributionDays { contributionCount date weekday } } } } repositories(first: 100, orderBy: {field: STARGAZERS, direction: DESC}) { nodes { stargazerCount primaryLanguage { name } } } } } `; // Execute the query async function fetchUserStats(username: string) { try { const response = await octokit.graphql(query, { username }); const userData = response.user; // Process contribution data const contributionDays = userData.contributionsCollection .contributionCalendar.weeks .flatMap((week) => week.contributionDays) .filter((day) => new Date(day.date) >= new Date("2024-01-01")); // Calculate total stars const totalStars = userData.repositories.nodes.reduce( (acc, repo) => acc + repo.stargazerCount, 0 ); return { contributions: contributionDays, totalStars, totalCommits: userData.contributionsCollection.contributionCalendar.totalContributions }; } catch (error) { console.error("GitHub API error:", error); throw new Error("Failed to fetch data from GitHub"); } } // Usage example fetchUserStats("octocat") .then(stats => console.log("User stats:", stats)) .catch(err => console.error(err)); ``` -------------------------------- ### Environment Variable Validation and GitHub Client Initialization in TypeScript Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt This TypeScript code validates the GITHUB_TOKEN environment variable, essential for API authentication. It also demonstrates the initialization of the Octokit GitHub client with error handling for invalid configurations. The code is optimized for the Edge Runtime. ```typescript // Environment variable validation in API const GITHUB_TOKEN = process.env.GITHUB_TOKEN; if (!GITHUB_TOKEN) { throw new Error("Missing GITHUB_TOKEN environment variable"); } // Usage in production export const runtime = "edge"; // Enable Edge Runtime for faster responses // Error handling for missing configuration try { const octokit = new Octokit({ auth: GITHUB_TOKEN }); } catch (error) { console.error("Failed to initialize GitHub client:", error); throw new Error("Invalid GitHub token configuration"); } ``` -------------------------------- ### Process Top Programming Languages from Repositories (TypeScript) Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt Aggregates and ranks programming languages from a user's repository collection to identify their most-used languages. It takes an array of Repository objects and returns an array of the top 3 programming languages. ```typescript interface Repository { stargazerCount: number; primaryLanguage?: { name: string; }; } function processTopLanguages(repositories: Repository[]): string[] { // Count repositories by language const languages = repositories.reduce( (acc: Record, repo) => { if (repo.primaryLanguage?.name) { acc[repo.primaryLanguage.name] = (acc[repo.primaryLanguage.name] || 0) + 1; } return acc; }, {} ); // Sort by frequency and return top 3 const topLanguages = Object.entries(languages) .sort(([, a], [, b]): number => (b as number) - (a as number)) .slice(0, 3) .map(([lang]) => lang); return topLanguages; } // Example usage const userRepositories: Repository[] = [ { stargazerCount: 120, primaryLanguage: { name: "TypeScript" } }, { stargazerCount: 45, primaryLanguage: { name: "Python" } }, { stargazerCount: 89, primaryLanguage: { name: "TypeScript" } }, { stargazerCount: 12, primaryLanguage: { name: "JavaScript" } }, { stargazerCount: 67, primaryLanguage: { name: "Python" } }, { stargazerCount: 34, primaryLanguage: { name: "TypeScript" } }, { stargazerCount: 5, primaryLanguage: { name: "Go" } }, ]; const topLangs = processTopLanguages(userRepositories); console.log("Top programming languages:", topLangs); // Output: "Top programming languages: ['TypeScript', 'Python', 'JavaScript']" // Calculate language distribution percentages const langCounts = topLangs.reduce((acc, lang) => { acc[lang] = userRepositories.filter( r => r.primaryLanguage?.name === lang ).length; return acc; }, {} as Record); console.log("Distribution:", langCounts); // Output: "Distribution: { TypeScript: 3, Python: 2, JavaScript: 1 }" ``` -------------------------------- ### React Component for Fetching GitHub Stats Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt A React component written in TypeScript that allows users to input a GitHub username and fetch their statistics using the Git Wrapped API. It includes state management for the username, fetched stats, loading indicators, and error handling for a seamless user experience. ```typescript import { useState } from 'react'; export default function StatsComponent() { const [username, setUsername] = useState(""); const [stats, setStats] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setError(""); setStats(null); try { const response = await fetch(`/api/stats?username=${username}`); const data = await response.json(); if (!response.ok) { throw new Error(data.error || "Failed to fetch stats"); } setStats(data); console.log("Total commits:", data.totalCommits); console.log("Longest streak:", data.longestStreak); console.log("Top languages:", data.topLanguages.join(", ")); } catch (err: any) { setError(err.message); console.error("Error fetching stats:", err); } finally { setLoading(false); } }; return (
setUsername(e.target.value)} placeholder="GitHub username" required /> {error &&
{error}
} {stats &&
{JSON.stringify(stats, null, 2)}
}
); } ``` -------------------------------- ### Analyze GitHub User Activity Patterns (TypeScript) Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt Analyzes contribution patterns to identify the most active day of the week and month for a GitHub user. It processes an array of ContributionDay objects and returns the most active day and month. ```typescript interface ContributionDay { contributionCount: number; date: string; weekday: number; } const WEEKDAY_NAMES = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] as const; const MONTH_NAMES = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] as const; function analyzeActivityPatterns(contributionDays: ContributionDay[]) { // Calculate monthly commits const monthlyCommits: Record = {}; contributionDays.forEach((day) => { const month = new Date(day.date).getMonth() + 1; const monthKey = month.toString().padStart(2, "0"); monthlyCommits[monthKey] = (monthlyCommits[monthKey] || 0) + day.contributionCount; }); // Calculate daily commits (by weekday) const dailyCommits: Record = {}; contributionDays.forEach((day) => { dailyCommits[day.weekday] = (dailyCommits[day.weekday] || 0) + day.contributionCount; }); // Find peak activity periods const [mostActiveMonth] = Object.entries(monthlyCommits) .sort(([, a], [, b]) => b - a); const [mostActiveDay] = Object.entries(dailyCommits) .sort(([, a], [, b]) => b - a); return { mostActiveDay: { name: WEEKDAY_NAMES[parseInt(mostActiveDay[0])], commits: Math.round(mostActiveDay[1] / (contributionDays.length / 7)), }, mostActiveMonth: { name: MONTH_NAMES[parseInt(mostActiveMonth[0]) - 1], commits: mostActiveMonth[1], }, }; } // Example with realistic data const yearContributions: ContributionDay[] = [ { contributionCount: 8, date: "2024-03-05", weekday: 2 }, // Tuesday, March { contributionCount: 12, date: "2024-03-12", weekday: 2 }, // Tuesday, March { contributionCount: 5, date: "2024-03-19", weekday: 2 }, // Tuesday, March { contributionCount: 3, date: "2024-04-10", weekday: 3 }, // Wednesday, April { contributionCount: 7, date: "2024-04-15", weekday: 1 }, // Monday, April ]; const patterns = analyzeActivityPatterns(yearContributions); console.log(`Most productive on ${patterns.mostActiveDay.name}`); console.log(`Most active in ${patterns.mostActiveMonth.name}`); // Output: "Most productive on Tuesday" // Output: "Most active in March" ``` -------------------------------- ### Calculate Longest Contribution Streak from GitHub Data Source: https://context7.com/gabriel-pineda/git-wrapped-api/llms.txt This TypeScript function calculates the longest consecutive streak of days with contributions greater than zero from a given array of contribution days. It iterates through the days, maintaining a current streak count and updating the maximum streak found. ```typescript interface ContributionDay { contributionCount: number; date: string; weekday: number; } function calculateLongestStreak(contributionDays: ContributionDay[]): number { let currentStreak = 0; let maxStreak = 0; for (const day of contributionDays) { if (day.contributionCount > 0) { currentStreak++; maxStreak = Math.max(maxStreak, currentStreak); } else { currentStreak = 0; } } return maxStreak; } // Example usage with sample data const sampleContributions: ContributionDay[] = [ { contributionCount: 5, date: "2024-01-01", weekday: 1 }, { contributionCount: 3, date: "2024-01-02", weekday: 2 }, { contributionCount: 7, date: "2024-01-03", weekday: 3 }, { contributionCount: 0, date: "2024-01-04", weekday: 4 }, { contributionCount: 4, date: "2024-01-05", weekday: 5 }, { contributionCount: 2, date: "2024-01-06", weekday: 6 }, ]; const longestStreak = calculateLongestStreak(sampleContributions); console.log(`Longest contribution streak: ${longestStreak} days`); // Output: "Longest contribution streak: 3 days" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.