-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathgithubService.ts
More file actions
604 lines (532 loc) · 18 KB
/
githubService.ts
File metadata and controls
604 lines (532 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// GitHub API service for fetching organization metrics
// Uses localStorage for caching to reduce API calls
// 1) discussions count used org-wide search — replaced with repo-specific GraphQL query (default repo: "Support").
// 2) anonymous contributors (anon=true) made configurable (default: false).
// Changes are annotated with // === ADDED and // === UPDATED where applicable.
export interface GitHubOrgStats {
totalStars: number;
totalForks: number;
totalRepositories: number;
totalContributors: number;
publicRepositories: number;
discussionsCount: number;
lastUpdated: number;
}
export interface GitHubRepository {
id: number;
name: string;
full_name: string;
stargazers_count: number;
forks_count: number;
contributors_url: string;
archived: boolean;
private: boolean;
}
export interface GitHubOrganization {
login: string;
id: number;
public_repos: number;
followers: number;
following: number;
}
export interface GitHubDiscussion {
id: string;
title: string;
body: string;
author: {
login: string;
avatar_url: string;
html_url: string;
};
category: {
name: string;
emoji: string;
};
created_at: string;
updated_at: string;
comments: number;
reactions: {
total_count: number;
};
html_url: string;
labels: Array<{
name: string;
color: string;
}>;
}
class GitHubService {
private readonly ORG_NAME = "recodehive";
private readonly CACHE_KEY = "github_org_stats";
private readonly CACHE_DURATION = 30 * 60 * 1000; // 30 minutes in milliseconds
private readonly BASE_URL = "https://api.github.com";
// === ADDED: include anonymous contributors configurable (default false)
private includeAnonymousContributors = false;
// Get headers for GitHub API requests
private getHeaders(): Record<string, string> {
const headers: Record<string, string> = {
Accept: "application/vnd.github.v3+json",
"Content-Type": "application/json",
};
// Add GitHub token if available in environment
// Note: In production, you might want to use a server-side proxy to avoid exposing tokens
if (typeof window !== "undefined" && (window as any).GITHUB_TOKEN) {
headers["Authorization"] = `token ${(window as any).GITHUB_TOKEN}`;
}
return headers;
}
// === ADDED: setter to toggle anonymous contributors inclusion
setIncludeAnonymousContributors(value: boolean) {
this.includeAnonymousContributors = value;
}
// Fetch with error handling and rate limit consideration
private async fetchWithRetry(url: string, retries = 3): Promise<Response> {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, {
headers: this.getHeaders(),
});
if (response.status === 403) {
// Rate limited - don't retry, just throw error
console.warn("GitHub API rate limit exceeded");
throw new Error("GitHub API rate limit exceeded");
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response;
} catch (error) {
if (i === retries - 1) throw error;
await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
}
}
throw new Error("Failed after retries");
}
// Get cached data if valid
private getCachedData(): GitHubOrgStats | null {
if (typeof window === "undefined") return null;
try {
const cached = localStorage.getItem(this.CACHE_KEY);
if (!cached) return null;
const data = JSON.parse(cached) as GitHubOrgStats;
const now = Date.now();
if (now - data.lastUpdated < this.CACHE_DURATION) {
return data;
}
} catch (error) {
console.warn("Error reading GitHub stats cache:", error);
// Clear invalid cache
localStorage.removeItem(this.CACHE_KEY);
}
return null;
}
// Cache data to localStorage
private setCachedData(data: GitHubOrgStats): void {
if (typeof window === "undefined") return;
try {
localStorage.setItem(
this.CACHE_KEY,
JSON.stringify({
...data,
lastUpdated: Date.now(),
}),
);
} catch (error) {
console.warn("Error caching GitHub stats:", error);
}
}
// Fetch organization basic info
private async fetchOrganizationInfo(
signal?: AbortSignal,
): Promise<GitHubOrganization> {
const response = await fetch(`${this.BASE_URL}/orgs/${this.ORG_NAME}`, {
headers: this.getHeaders(),
signal,
});
if (!response.ok) {
throw new Error(`Failed to fetch organization info: ${response.status}`);
}
return response.json();
}
// Fetch all public repositories for the organization
private async fetchAllRepositories(
signal?: AbortSignal,
): Promise<GitHubRepository[]> {
const repositories: GitHubRepository[] = [];
let page = 1;
const perPage = 100;
while (true) {
const response = await fetch(
`${this.BASE_URL}/orgs/${this.ORG_NAME}/repos?type=public&per_page=${perPage}&page=${page}&sort=updated`,
{
headers: this.getHeaders(),
signal,
},
);
if (!response.ok) {
if (response.status === 403) {
console.warn(
"GitHub API rate limit exceeded while fetching repositories",
);
throw new Error("GitHub API rate limit exceeded");
}
throw new Error(`Failed to fetch repositories: ${response.status}`);
}
const repos: GitHubRepository[] = await response.json();
if (repos.length === 0) break;
repositories.push(...repos);
if (repos.length < perPage) break;
page++;
}
return repositories;
}
// Estimate contributors count (GitHub API doesn't provide org-wide contributor count)
private async estimateContributors(
repositories: GitHubRepository[],
signal?: AbortSignal,
): Promise<number> {
// For performance, we'll sample top repositories by stars/activity
const topRepos = repositories
.filter((repo) => !repo.archived && repo.stargazers_count > 0)
.sort((a, b) => b.stargazers_count - a.stargazers_count)
.slice(0, 10); // Sample top 10 repositories
let totalContributors = 0;
// Use parallel requests for better performance
const contributorPromises = topRepos.map(async (repo) => {
try {
// === UPDATED: make anon param configurable based on class setting
const anonParam = this.includeAnonymousContributors ? "true" : "false";
const response = await fetch(
`${this.BASE_URL}/repos/${repo.full_name}/contributors?per_page=1&anon=${anonParam}`,
{
headers: this.getHeaders(),
signal,
},
);
if (response.ok) {
// Get total count from Link header if available
const linkHeader = response.headers.get("Link");
if (linkHeader) {
const match = linkHeader.match(/page=(\d+)>; rel="last"/);
if (match) {
return parseInt(match[1], 10);
}
}
// Fallback: count actual contributors
const contributors = await response.json();
return Array.isArray(contributors) ? contributors.length : 0;
}
return 0;
} catch (error) {
console.warn(`Error fetching contributors for ${repo.name}:`, error);
return 0;
}
});
const contributorCounts = await Promise.all(contributorPromises);
// Estimate total unique contributors (with some overlap factor)
const sumContributors = contributorCounts.reduce(
(sum, count) => sum + count,
0,
);
// Apply estimation factor for unique contributors across repos
totalContributors = Math.round(sumContributors * 0.7); // Assume 30% overlap
// NOTE: original code had a floor (e.g., Math.max(..., 140)). I kept behavior simple and returned the estimate.
return totalContributors;
}
// === UPDATED: Get discussions count for a specific repository (default: "Support")
// Reason: previous code used an org-wide issues search which returned issues, not discussions.
// This function uses GraphQL to read repository.discussions.totalCount (repo-specific).
// If you need org-wide discussions count, we should iterate all repos and sum totalCount (heavier).
private async getDiscussionsCount(
signal?: AbortSignal,
repoName: string = "Support",
): Promise<number> {
try {
// GraphQL query to get discussions totalCount for a repository
const query = `
query ($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
discussions { totalCount }
}
}
`;
const variables = { owner: this.ORG_NAME, name: repoName };
const resp = await fetch("https://api.github.com/graphql", {
method: "POST",
headers: {
...this.getHeaders(),
"Content-Type": "application/json",
},
body: JSON.stringify({ query, variables }),
signal,
});
if (!resp.ok) {
console.warn(`GraphQL request for discussions failed: ${resp.status}`);
return 0;
}
const data = await resp.json();
if (data.errors) {
console.warn("GraphQL errors while fetching discussions:", data.errors);
return 0;
}
const count = data?.data?.repository?.discussions?.totalCount || 0;
return Number(count);
} catch (error) {
console.warn("Error fetching discussions count via GraphQL:", error);
return 0;
}
}
// Main method to fetch all organization statistics
async fetchOrganizationStats(signal?: AbortSignal): Promise<GitHubOrgStats> {
// Try to get cached data first
const cached = this.getCachedData();
if (cached) {
return cached;
}
try {
// Fetch organization info and repositories in parallel
const [orgInfo, repositories] = await Promise.all([
this.fetchOrganizationInfo(signal),
this.fetchAllRepositories(signal),
]);
// Filter out archived repositories for active stats
const activeRepos = repositories.filter((repo) => !repo.archived);
// Calculate totals
const totalStars = repositories.reduce(
(sum, repo) => sum + repo.stargazers_count,
0,
);
const totalForks = repositories.reduce(
(sum, repo) => sum + repo.forks_count,
0,
);
// Estimate contributors and get discussions count
// === UPDATED: getDiscussionsCount now uses GraphQL for a specific repo (default 'Support')
const [totalContributors, discussionsCount] = await Promise.all([
this.estimateContributors(activeRepos, signal),
this.getDiscussionsCount(signal), // default repoName: "Support" (change if you prefer another repo)
]);
const stats: GitHubOrgStats = {
totalStars,
totalForks,
totalRepositories: repositories.length,
publicRepositories: activeRepos.length,
totalContributors,
discussionsCount,
lastUpdated: Date.now(),
};
// Cache the results
this.setCachedData(stats);
return stats;
} catch (error) {
console.error("Error fetching GitHub organization stats:", error);
// Return fallback data if API fails
const fallbackStats: GitHubOrgStats = {
totalStars: 0,
totalForks: 0,
totalRepositories: 0,
publicRepositories: 0,
totalContributors: 0,
discussionsCount: 0,
lastUpdated: Date.now(),
};
return fallbackStats;
}
}
// Clear cache (useful for manual refresh)
clearCache(): void {
if (typeof window !== "undefined") {
localStorage.removeItem(this.CACHE_KEY);
}
}
// Get cache status
getCacheStatus(): { cached: boolean; age: number; expiresIn: number } {
const cached = this.getCachedData();
if (!cached) {
return { cached: false, age: 0, expiresIn: 0 };
}
const age = Date.now() - cached.lastUpdated;
const expiresIn = Math.max(0, this.CACHE_DURATION - age);
return { cached: true, age, expiresIn };
}
// Fetch GitHub Discussions using GraphQL API (existing method kept intact)
async fetchDiscussions(
limit: number = 20,
signal?: AbortSignal,
): Promise<GitHubDiscussion[]> {
const query = `
query GetDiscussions($owner: String!, $name: String!, $first: Int!) {
repository(owner: $owner, name: $name) {
discussions(first: $first, orderBy: {field: UPDATED_AT, direction: DESC}) {
nodes {
id
title
body
createdAt
updatedAt
url
author {
login
avatarUrl
url
}
category {
name
emoji
}
comments {
totalCount
}
reactions {
totalCount
}
labels(first: 10) {
nodes {
name
color
}
}
}
}
}
}
`;
const variables = {
owner: this.ORG_NAME,
name: "recode-website", // Main repository for discussions (unchanged)
first: limit,
};
try {
const response = await fetch("https://api.github.com/graphql", {
method: "POST",
headers: {
...this.getHeaders(),
"Content-Type": "application/json",
},
body: JSON.stringify({ query, variables }),
signal,
});
if (!response.ok) {
throw new Error(`GraphQL request failed: ${response.status}`);
}
const data = await response.json();
if (data.errors) {
console.error("GraphQL errors:", data.errors);
throw new Error("GraphQL query failed");
}
const discussions = data.data?.repository?.discussions?.nodes || [];
return discussions.map(
(discussion: any): GitHubDiscussion => ({
id: discussion.id,
title: discussion.title,
body: discussion.body || "",
author: {
login: discussion.author?.login || "Unknown",
avatar_url: discussion.author?.avatarUrl || "",
html_url: discussion.author?.url || "",
},
category: {
name: discussion.category?.name || "General",
emoji: discussion.category?.emoji || "💬",
},
created_at: discussion.createdAt,
updated_at: discussion.updatedAt,
comments: discussion.comments?.totalCount || 0,
reactions: {
total_count: discussion.reactions?.totalCount || 0,
},
html_url: discussion.url,
labels:
discussion.labels?.nodes?.map((label: any) => ({
name: label.name,
color: label.color,
})) || [],
}),
);
} catch (error) {
console.error("Error fetching discussions:", error);
// Return mock data for development/fallback
return this.getMockDiscussions();
}
}
// Mock discussions for development/fallback (unchanged)
private getMockDiscussions(): GitHubDiscussion[] {
return [
{
id: "1",
title: "Welcome to recode hive Discussions!",
body: "This is where we discuss ideas, share knowledge, and help each other grow. Feel free to ask questions, share your projects, or just say hello!",
author: {
login: "recodehive",
avatar_url: "https://avatars.githubusercontent.com/u/your-org-id?v=4",
html_url: "https://github.com/recodehive",
},
category: {
name: "Announcements",
emoji: "📢",
},
created_at: new Date(Date.now() - 86400000).toISOString(),
updated_at: new Date(Date.now() - 3600000).toISOString(),
comments: 12,
reactions: {
total_count: 25,
},
html_url: "https://github.com/recodehive/recode-website/discussions",
labels: [
{ name: "welcome", color: "0075ca" },
{ name: "community", color: "7057ff" },
],
},
{
id: "2",
title: "How to contribute to open source projects?",
body: "I'm new to open source and would love to learn how to make my first contribution. Any tips or resources would be greatly appreciated!",
author: {
login: "newcontributor",
avatar_url: "https://avatars.githubusercontent.com/u/example?v=4",
html_url: "https://github.com/newcontributor",
},
category: {
name: "Q&A",
emoji: "❓",
},
created_at: new Date(Date.now() - 172800000).toISOString(),
updated_at: new Date(Date.now() - 7200000).toISOString(),
comments: 8,
reactions: {
total_count: 15,
},
html_url: "https://github.com/recodehive/recode-website/discussions",
labels: [
{ name: "question", color: "d876e3" },
{ name: "beginner", color: "0e8a16" },
],
},
{
id: "3",
title: "Feature Request: Dark Mode for Documentation",
body: "It would be great to have a dark mode option for the documentation pages. This would be easier on the eyes during late-night coding sessions.",
author: {
login: "darkmode-lover",
avatar_url: "https://avatars.githubusercontent.com/u/example2?v=4",
html_url: "https://github.com/darkmode-lover",
},
category: {
name: "Ideas",
emoji: "💡",
},
created_at: new Date(Date.now() - 259200000).toISOString(),
updated_at: new Date(Date.now() - 10800000).toISOString(),
comments: 5,
reactions: {
total_count: 22,
},
html_url: "https://github.com/recodehive/recode-website/discussions",
labels: [
{ name: "enhancement", color: "a2eeef" },
{ name: "ui/ux", color: "f9d0c4" },
],
},
];
}
}
export const githubService = new GitHubService();