-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathgithubService.ts
More file actions
329 lines (272 loc) · 9.68 KB
/
githubService.ts
File metadata and controls
329 lines (272 loc) · 9.68 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
// GitHub API service for fetching organization metrics
// Uses localStorage for caching to reduce API calls
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;
}
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';
// 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;
}
// 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, wait a bit
const resetTime = response.headers.get('X-RateLimit-Reset');
if (resetTime) {
const waitTime = Math.max(0, parseInt(resetTime) * 1000 - Date.now());
if (waitTime < 60000) { // Only wait if less than 1 minute
await new Promise(resolve => setTimeout(resolve, Math.min(waitTime, 5000)));
continue;
}
}
}
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) {
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 {
const response = await fetch(
`${this.BASE_URL}/repos/${repo.full_name}/contributors?per_page=1`,
{
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]);
}
}
// 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
// Ensure minimum reasonable number
return Math.max(totalContributors, 140);
}
// Get discussions count (approximate using search)
private async getDiscussionsCount(signal?: AbortSignal): Promise<number> {
try {
const response = await fetch(
`${this.BASE_URL}/search/issues?q=repo:${this.ORG_NAME}/Support+type:issue`,
{
headers: this.getHeaders(),
signal,
}
);
if (response.ok) {
const data = await response.json();
return data.total_count || 0;
}
} catch (error) {
console.warn('Error fetching discussions count:', 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
const [totalContributors, discussionsCount] = await Promise.all([
this.estimateContributors(activeRepos, signal),
this.getDiscussionsCount(signal),
]);
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: 140,
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 };
}
}
export const githubService = new GitHubService();