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
61 changes: 33 additions & 28 deletions app/api/compare/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,36 +349,41 @@ async function compareUsers(

// ── Fire-and-forget: detect country & upsert into DB ──────────────
const country = detectCountry(data.location);
if (country) {
if (country && process.env.DATABASE_URL?.trim()) {
const staleDays = parseInt(process.env.GITHUB_USER_STALE_DAYS ?? "14", 10);

const db = getDatabaseStore();
db.upsertUser({
username: data.login,
name: data.name,
avatarUrl: data.avatarUrl,
location: data.location,
country,
rawData: data,
scores: score,
repoScore: Math.round(score.repoScore),
prScore: Math.round(score.prScore),
contributionScore: Math.round(score.contributionScore),
finalScore: Math.round(score.finalScore),
staleDays,
})
.then(() => {
// Invalidate Redis cache for this country
const cacheConfig = getCacheConfigFromEnv();
const cacheStore = createCacheStore(cacheConfig);
if (cacheStore.enabled && cacheStore.del) {
const key = `${cacheConfig.namespace}:leaderboard:${country}`;
cacheStore.del(key).catch(() => {});
}
const dbScore = selectedLanguages.length > 0 ? calculateUserScore(data, data.login) : score;

try {
const db = getDatabaseStore();
db.upsertUser({
username: data.login,
name: data.name,
avatarUrl: data.avatarUrl,
location: data.location,
country,
rawData: data,
scores: dbScore,
repoScore: Math.round(dbScore.repoScore),
prScore: Math.round(dbScore.prScore),
contributionScore: Math.round(dbScore.contributionScore),
finalScore: Math.round(dbScore.finalScore),
staleDays,
})
.catch((err: unknown) => {
console.warn("Failed to upsert user from compare:", err);
});
.then(() => {
// Invalidate Redis cache for this country
const cacheConfig = getCacheConfigFromEnv();
const cacheStore = createCacheStore(cacheConfig);
if (cacheStore.enabled && cacheStore.del) {
const key = `${cacheConfig.namespace}:leaderboard:${country.trim().toLowerCase()}`;
cacheStore.del(key).catch(() => {});
}
})
.catch((err: unknown) => {
console.warn("Failed to upsert user from compare:", err);
});
} catch {
// Ignore DB connection errors in environments without DB
}
}
}

Expand Down
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>
);
}
Loading
Loading