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
67 changes: 59 additions & 8 deletions app/api/compare/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { fetchGitHubUserData } from "../../../lib/github";
import { calculateUserScore } from "../../../lib/score";
import { normalizeSelectedLanguages } from "@/lib/scoring/languageScoring";
import { toSafeApiError } from "@/lib/github-graphql-client";
import type { CompareInsights } from "@/types/api-response";
import type { CompareInsights, SafeApiError } from "@/types/api-response";
import {
DEFAULT_LOCALE,
LOCALE_COOKIE,
Expand All @@ -14,6 +14,18 @@ import {

export const runtime = "nodejs";

class CompareUserFetchError extends Error {
readonly username: string;
readonly causeError: unknown;

constructor(username: string, causeError: unknown) {
super(`Failed to fetch GitHub data for ${username}`);
this.name = "CompareUserFetchError";
this.username = username;
this.causeError = causeError;
}
}

type ComparedUserResult = {
username: string;
name: string | null;
Expand All @@ -36,6 +48,8 @@ type ComparedUserResult = {
explanations: ReturnType<typeof calculateUserScore>["explanations"];
};

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

function parseSelectedLanguagesFromSearchParams(
searchParams: URLSearchParams,
): string[] {
Expand Down Expand Up @@ -292,7 +306,13 @@ async function compareUsers(
const results: ComparedUserResult[] = [];

for (const username of usernames) {
const data = await fetchGitHubUserData(username);
let data: Awaited<ReturnType<typeof fetchGitHubUserData>>;
try {
data = await fetchGitHubUserData(username);
} catch (error: unknown) {
throw new CompareUserFetchError(username, error);
}

const score = calculateUserScore(
{
...data,
Expand Down Expand Up @@ -341,6 +361,14 @@ function toApiErrorStatus(code: ReturnType<typeof toSafeApiError>["code"]): numb
}
}

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

export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const usernames = searchParams
Expand All @@ -364,16 +392,39 @@ export async function GET(request: Request) {
return NextResponse.json({ success: true, users, ...winnerData, insights });
} catch (error: unknown) {
console.error("GitHub score error:", error);
const safeError =
error instanceof Error && error.message === "User not found"
? { code: "GITHUB_NOT_FOUND" as const, message: "GitHub user not found" }
: toSafeApiError(error);

let safeError: SafeApiError;

if (error instanceof CompareUserFetchError) {
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: safeError.message,
errorDetails: safeError,
error: clientSafeError.message,
errorDetails: clientSafeError,
},
{ status: toApiErrorStatus(safeError.code) },
);
Expand Down
27 changes: 18 additions & 9 deletions components/compare-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
CardHeader,
CardTitle,
} from "./ui/card";
import { Alert, AlertDescription } from "./ui/alert";
import { useTranslation } from "./language-provider";
import { cn } from "@/lib/utils";

Expand Down Expand Up @@ -46,7 +45,8 @@ type CompareFormProps = {
loading?: boolean;
reset?: () => void;
swapUsers?: () => void;
error?: string | null;
username1Error?: string | null;
username2Error?: string | null;
};

export function CompareForm({
Expand All @@ -61,7 +61,8 @@ export function CompareForm({
loading,
swapUsers,
reset,
error,
username1Error,
username2Error,
}: CompareFormProps) {
const { t } = useTranslation();
const firstInputRef = useRef<HTMLInputElement>(null);
Expand Down Expand Up @@ -131,7 +132,14 @@ export function CompareForm({
value={username1}
onChange={(e) => setUsername1(e.target.value)}
aria-label={t("form.username1.label")}
aria-invalid={Boolean(username1Error)}
aria-describedby={username1Error ? "username1-error" : undefined}
/>
{username1Error ? (
<p id="username1-error" className="text-xs font-medium text-destructive">
{username1Error}
</p>
) : null}
</div>
<div className="space-y-1.5">
<label htmlFor="username2" className="text-xs font-semibold text-muted-foreground">
Expand All @@ -144,7 +152,14 @@ export function CompareForm({
value={username2}
onChange={(e) => setUsername2(e.target.value)}
aria-label={t("form.username2.label")}
aria-invalid={Boolean(username2Error)}
aria-describedby={username2Error ? "username2-error" : undefined}
/>
{username2Error ? (
<p id="username2-error" className="text-xs font-medium text-destructive">
{username2Error}
</p>
) : null}
</div>
</div>

Expand Down Expand Up @@ -250,12 +265,6 @@ export function CompareForm({
<RefreshCw className="h-4 w-4" />
</Button>
</div>

{error ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
</CardContent>
</Card>
</form>
Expand Down
Loading
Loading