Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions app/api/user/[username]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { NextResponse } from "next/server";
import { getUserProfile, UserFetchError } from "@/lib/user";
import { normalizeSelectedLanguages } from "@/lib/scoring/languageScoring";
import { toSafeApiError } from "@/lib/github-graphql-client";
import type { SafeApiError } from "@/types/api-response";

export const runtime = "nodejs";

type ClientSafeError = Pick<SafeApiError, "code" | "message" | "targetUsernames">;

function parseSelectedLanguagesFromSearchParams(searchParams: URLSearchParams): string[] {
const fromRepeated = searchParams.getAll("selectedLanguage");
const fromCsv = searchParams
.get("selectedLanguages")
?.split(",")
.map((language) => language.trim())
.filter(Boolean);

return normalizeSelectedLanguages([...(fromRepeated ?? []), ...(fromCsv ?? [])]);
}

function toClientSafeError(error: SafeApiError): ClientSafeError {
return {
code: error.code,
message: error.message,
targetUsernames: error.targetUsernames,
};
}

function toApiErrorStatus(code: ReturnType<typeof toSafeApiError>["code"]): number {
switch (code) {
case "RATE_LIMITED":
case "TEMPORARY_THROTTLE":
return 429;
case "GITHUB_TIMEOUT":
case "GITHUB_RESOURCE_LIMIT":
case "GITHUB_AUTH":
return code === "GITHUB_AUTH" ? 401 : 503;
case "GITHUB_NOT_FOUND":
return 404;
case "NETWORK":
return 503;
case "UNKNOWN":
default:
return 500;
}
}

export async function GET(request: Request, { params }: { params: Promise<{ username: string }> }) {
const { username } = await params;
const trimmed = username?.trim();

if (!trimmed) {
return NextResponse.json(
{ success: false, error: "Username parameter is required" },
{ status: 400 },
);
}

const { searchParams } = new URL(request.url);
const selectedLanguages = parseSelectedLanguagesFromSearchParams(searchParams);

try {
const { user, location } = await getUserProfile(trimmed, selectedLanguages);
return NextResponse.json({ success: true, user, location });
} catch (error: unknown) {
console.error("User profile fetch error:", error);

let safeError: SafeApiError;

if (error instanceof UserFetchError) {
const mappedCause = toSafeApiError(error.causeError);
if (
mappedCause.code === "GITHUB_NOT_FOUND" ||
(error.causeError instanceof Error && error.causeError.message === "User not found")
) {
safeError = {
code: "GITHUB_NOT_FOUND",
message: "GitHub user not found",
targetUsernames: [error.username],
rateLimit: mappedCause.rateLimit,
};
} else {
safeError = mappedCause;
}
} else {
safeError =
error instanceof Error && error.message === "User not found"
? { code: "GITHUB_NOT_FOUND", message: "GitHub user not found" }
: toSafeApiError(error);
}

const clientSafeError = toClientSafeError(safeError);

return NextResponse.json(
{
success: false,
error: clientSafeError.message,
errorDetails: clientSafeError,
},
{ status: toApiErrorStatus(safeError.code) },
);
}
}
3 changes: 3 additions & 0 deletions app/leaderboard/[country]/country-leaderboard-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import type { LeaderboardResult } from "@/lib/leaderboard";

type Props = {
countryTitle: string;
countrySlug?: string;
initialLeaderboard: LeaderboardResult;
initialError?: string | null;
};

export function CountryLeaderboardClient({
countryTitle,
countrySlug,
initialLeaderboard,
initialError = null,
}: Props) {
Expand Down Expand Up @@ -82,6 +84,7 @@ export function CountryLeaderboardClient({
users={scored}
failedUsers={errors}
title={title}
countrySlug={countrySlug}
totalFromSource={totalFromSource}
usersProcessed={scored.length}
/>
Expand Down
6 changes: 5 additions & 1 deletion app/leaderboard/[country]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,11 @@ export default async function CountryLeaderboardPage({ params }: Props) {
: [webPageSchema, breadcrumbSchema]
}
/>
<CountryLeaderboardClient countryTitle={countryInfo.title} initialLeaderboard={leaderboard} />
<CountryLeaderboardClient
countryTitle={countryInfo.title}
countrySlug={country}
initialLeaderboard={leaderboard}
/>
</>
);
}
15 changes: 15 additions & 0 deletions app/user/[username]/loading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { AppHeader } from "@/components/app-header";
import { AppFooter } from "@/components/app-footer";
import { UserProfileSkeleton } from "@/components/user-profile-skeleton";

export default function UserProfileLoading() {
return (
<main className="flex min-h-screen flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">
<UserProfileSkeleton />
</div>
<AppFooter />
</main>
);
}
208 changes: 208 additions & 0 deletions app/user/[username]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import type { Metadata } from "next";
import { JsonLd } from "@/components/seo/json-ld";
import { UserProfileClient } from "@/components/user-profile-client";
import { UserNotFoundCard } from "@/components/user-not-found";
import { AppHeader } from "@/components/app-header";
import { AppFooter } from "@/components/app-footer";
import { getUserProfile } from "@/lib/user";
import { toAbsoluteUrl } from "@/lib/seo";

import countriesData from "@/data/countries.json";
import { detectCountry } from "@/lib/location-detector";

type CountryInfo = {
slug: string;
title: string;
};

const countries = countriesData as CountryInfo[];

type Props = {
params: Promise<{ username: string }>;
searchParams?: Promise<{ country?: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { username } = await params;
const cleanUsername = decodeURIComponent(username.trim());

let displayName = cleanUsername;
try {
const { user } = await getUserProfile(cleanUsername);
displayName = user.name?.trim() || cleanUsername;
} catch {
// Fallback if user cannot be fetched during metadata generation
}

const pageTitle = `${displayName} (@${cleanUsername}) - Developer Impact & Stats`;
const description = `Explore ${displayName}'s (@${cleanUsername}) open-source developer impact score, top repositories, merged pull requests, and community contributions on DevImpact.`;
const pageUrl = `/user/${cleanUsername}`;

return {
title: pageTitle,
description,
keywords: [
`${cleanUsername} GitHub`,
`${displayName} developer stats`,
`${cleanUsername} open source impact`,
"developer impact score",
"GitHub profile analytics",
],
alternates: {
canonical: pageUrl,
},
openGraph: {
type: "profile",
title: `${pageTitle} | DevImpact`,
description,
url: pageUrl,
images: [
{
url: toAbsoluteUrl("/og-image.svg"),
width: 1200,
height: 630,
alt: `${displayName} GitHub developer impact score preview`,
},
],
},
twitter: {
card: "summary_large_image",
title: `${pageTitle} | DevImpact`,
description,
images: [toAbsoluteUrl("/og-image.svg")],
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
"max-image-preview": "large",
"max-snippet": -1,
"max-video-preview": -1,
},
},
};
}

export default async function UserProfilePage({ params, searchParams }: Props) {
const { username } = await params;
const cleanUsername = decodeURIComponent(username.trim());
const profileUrl = toAbsoluteUrl(`/user/${cleanUsername}`);

const resolvedSearchParams = searchParams ? await searchParams : undefined;
const countryParam = resolvedSearchParams?.country;

let profileData: Awaited<ReturnType<typeof getUserProfile>> | null = null;
let fetchErrorMessage: string | null = null;

try {
profileData = await getUserProfile(cleanUsername);
} catch (err: unknown) {
fetchErrorMessage = err instanceof Error ? err.message : "Failed to load user profile";
}

if (!profileData || fetchErrorMessage) {
return (
<main className="flex min-h-screen flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-4xl flex-1 px-4 py-16">
<UserNotFoundCard username={cleanUsername} />
</div>
<AppFooter />
</main>
);
}

const { user, location } = profileData;
const displayName = user.name?.trim() || user.username;

const profilePageSchema = {
"@context": "https://schema.org",
"@type": "ProfilePage",
name: `${displayName} Developer Profile`,
description: `Open-source impact statistics and scoring for ${displayName} (@${user.username}).`,
url: profileUrl,
mainEntity: {
"@type": "Person",
name: displayName,
alternateName: user.username,
image: user.avatarUrl,
url: `https://github.com/${user.username}`,
...(location ? { homeLocation: location } : {}),
interactionStatistic: [
{
"@type": "InteractionCounter",
interactionType: "https://schema.org/LikeAction",
userInteractionCount: user.finalScore,
},
],
},
isPartOf: {
"@type": "WebSite",
name: "DevImpact",
url: toAbsoluteUrl("/"),
},
};

const detectedSlug = (countryParam || detectCountry(location))?.trim().toLowerCase();
const countryInfo = detectedSlug
? countries.find((c) => c.slug.toLowerCase() === detectedSlug)
: null;

const breadcrumbElements = [
{
"@type": "ListItem",
position: 1,
name: "Home",
item: toAbsoluteUrl("/"),
},
{
"@type": "ListItem",
position: 2,
name: "Leaderboards",
item: toAbsoluteUrl("/leaderboard"),
},
];

if (countryInfo) {
breadcrumbElements.push({
"@type": "ListItem",
position: 3,
name: countryInfo.title,
item: toAbsoluteUrl(`/leaderboard/${countryInfo.slug}`),
});
breadcrumbElements.push({
"@type": "ListItem",
position: 4,
name: displayName,
item: profileUrl,
});
} else {
breadcrumbElements.push({
"@type": "ListItem",
position: 3,
name: displayName,
item: profileUrl,
});
}

const breadcrumbSchema = {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: breadcrumbElements,
};

return (
<main className="flex min-h-screen flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">
<JsonLd data={profilePageSchema} />
<JsonLd data={breadcrumbSchema} />

<UserProfileClient user={user} location={location} countryParam={countryParam} />
</div>
<AppFooter />
</main>
);
}
Loading
Loading