Skip to content
Open
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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,8 @@ GITHUB_SECRET=your_github_oauth_app_client_secret
# 32-byte hex string for AES-256-GCM token encryption
# Generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
ENCRYPTION_KEY=

# Optional Upstash Redis cache for /api/metrics GitHub responses
# Metrics still work without these values; Redis reduces repeated GitHub API calls in production.
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
29 changes: 16 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@supabase/supabase-js": "^2.43.4",
"@upstash/redis": "^1.38.0",
"clsx": "^2.1.1",
"date-fns": "^3.6.0",
"jspdf": "^4.2.1",
Expand Down
88 changes: 58 additions & 30 deletions src/app/api/metrics/contributions/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import {
mergeMetrics,
} from "@/lib/github-accounts";
import { GITHUB_API } from "@/lib/github";
import {
isMetricsCacheBypassed,
METRICS_CACHE_TTL_SECONDS,
metricsCacheKey,
withMetricsCache,
} from "@/lib/metrics-cache";
import { supabaseAdmin } from "@/lib/supabase";

export const dynamic = "force-dynamic";
Expand Down Expand Up @@ -35,39 +41,54 @@ function mergeContributionDays(
async function fetchContributionsForAccount(
token: string,
githubLogin: string,
days: number
days: number,
cacheContext: { bypass: boolean; userId: string }
): Promise<ContributionResponse> {
const since = new Date();
since.setDate(since.getDate() - days);
const sinceStr = toLocalDateStr(since);
const key = metricsCacheKey(cacheContext.userId, "contributions", {
days,
githubLogin,
});

const searchRes = await fetch(
`${GITHUB_API}/search/commits?q=author:${githubLogin}+author-date:>=${sinceStr}&per_page=100&sort=author-date&order=desc`,
return withMetricsCache(
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github+json",
},
cache: "no-store",
}
);
bypass: cacheContext.bypass,
key,
ttlSeconds: METRICS_CACHE_TTL_SECONDS.contributions,
},
async () => {
const since = new Date();
since.setDate(since.getDate() - days);
const sinceStr = toLocalDateStr(since);

const searchRes = await fetch(
`${GITHUB_API}/search/commits?q=author:${githubLogin}+author-date:>=${sinceStr}&per_page=100&sort=author-date&order=desc`,
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github+json",
},
cache: "no-store",
}
);

if (!searchRes.ok) {
throw new Error("GitHub API error");
}
if (!searchRes.ok) {
throw new Error("GitHub API error");
}

const data = (await searchRes.json()) as {
total_count: number;
items: Array<{ commit: { author: { date: string } } }>;
};
const data = (await searchRes.json()) as {
total_count: number;
items: Array<{ commit: { author: { date: string } } }>;
};

const commitsByDay: Record<string, number> = {};
for (const item of data.items) {
const date = item.commit.author.date.slice(0, 10);
commitsByDay[date] = (commitsByDay[date] ?? 0) + 1;
}
const commitsByDay: Record<string, number> = {};
for (const item of data.items) {
const date = item.commit.author.date.slice(0, 10);
commitsByDay[date] = (commitsByDay[date] ?? 0) + 1;
}

return { days, total: data.total_count, data: commitsByDay };
return { days, total: data.total_count, data: commitsByDay };
}
);
}

export async function GET(req: NextRequest) {
Expand All @@ -78,13 +99,15 @@ export async function GET(req: NextRequest) {

const days = Number(req.nextUrl.searchParams.get("days")) || 30;
const accountId = req.nextUrl.searchParams.get("accountId");
const bypass = isMetricsCacheBypassed(req);

if (!accountId) {
try {
const result = await fetchContributionsForAccount(
session.accessToken,
session.githubLogin,
days
days,
{ bypass, userId: session.githubId ?? session.githubLogin }
);
return Response.json(result);
} catch {
Expand Down Expand Up @@ -118,7 +141,10 @@ export async function GET(req: NextRequest) {

const results = await Promise.allSettled(
accounts.map((account) =>
fetchContributionsForAccount(account.token, account.githubLogin, days)
fetchContributionsForAccount(account.token, account.githubLogin, days, {
bypass,
userId: account.githubId,
})
)
);

Expand All @@ -140,7 +166,8 @@ export async function GET(req: NextRequest) {
const result = await fetchContributionsForAccount(
session.accessToken,
session.githubLogin,
days
days,
{ bypass, userId: session.githubId }
);
return Response.json(result);
} catch {
Expand Down Expand Up @@ -169,7 +196,8 @@ export async function GET(req: NextRequest) {
const result = await fetchContributionsForAccount(
accountToken,
accountRow.github_login,
days
days,
{ bypass, userId: accountId }
);
return Response.json(result);
} catch {
Expand Down
Loading