-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub-api.js
More file actions
264 lines (233 loc) · 6.5 KB
/
github-api.js
File metadata and controls
264 lines (233 loc) · 6.5 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
/**
* GitHub API 集成模块
* 用于获取 GitHub 仓库统计信息和动态数据
*/
class GitHubAPI {
constructor(username = 'jacksoncode', repository = 'jacksoncode.github.io') {
this.username = username;
this.repository = repository;
this.baseURL = 'https://api.github.com';
this.cacheKey = 'github-data-cache';
this.cacheExpiry = 15 * 60 * 1000; // 15分钟缓存
}
/**
* 获取缓存的 GitHub 数据
*/
getCachedData() {
try {
const cached = localStorage.getItem(this.cacheKey);
if (!cached) return null;
const data = JSON.parse(cached);
const now = Date.now();
// 检查缓存是否过期
if (now - data.timestamp > this.cacheExpiry) {
localStorage.removeItem(this.cacheKey);
return null;
}
return data.content;
} catch (error) {
console.warn('读取缓存失败:', error);
return null;
}
}
/**
* 缓存 GitHub 数据
*/
cacheData(data) {
try {
const cacheEntry = {
timestamp: Date.now(),
content: data
};
localStorage.setItem(this.cacheKey, JSON.stringify(cacheEntry));
} catch (error) {
console.warn('缓存数据失败:', error);
}
}
/**
* 获取仓库基本信息
*/
async getRepositoryInfo() {
try {
const response = await fetch(
`${this.baseURL}/repos/${this.username}/${this.repository}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('获取仓库信息失败:', error);
return null;
}
}
/**
* 获取仓库 star 数
*/
async getStarCount() {
try {
const response = await fetch(
`${this.baseURL}/repos/${this.username}/${this.repository}`
);
const data = await response.json();
return data.stargazers_count || 0;
} catch (error) {
console.error('获取 star 数失败:', error);
return 0;
}
}
/**
* 获取最新提交记录
*/
async getRecentCommits(limit = 5) {
try {
const response = await fetch(
`${this.baseURL}/repos/${this.username}/${this.repository}/commits?per_page=${limit}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('获取提交记录失败:', error);
return [];
}
}
/**
* 获取 issues 数量
*/
async getIssuesCount() {
try {
const response = await fetch(
`${this.baseURL}/repos/${this.username}/${this.repository}`
);
const data = await response.json();
return data.open_issues_count || 0;
} catch (error) {
console.error('获取 issues 数失败:', error);
return 0;
}
}
/**
* 获取贡献者统计
*/
async getContributors() {
try {
const response = await fetch(
`${this.baseURL}/repos/${this.username}/${this.repository}/contributors`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('获取贡献者失败:', error);
return [];
}
}
/**
* 获取语言分布
*/
async getLanguages() {
try {
const response = await fetch(
`${this.baseURL}/repos/${this.username}/${this.repository}/languages`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('获取语言分布失败:', error);
return {};
}
}
/**
* 获取所有统计数据(带缓存)
*/
async getAllStats() {
// 尝试从缓存获取
const cached = this.getCachedData();
if (cached) {
console.log('使用缓存的 GitHub 数据');
return cached;
}
// 缓存未命中,获取新数据
console.log('从 GitHub API 获取新数据');
try {
const [repoInfo, commits, contributors, languages] = await Promise.all([
this.getRepositoryInfo(),
this.getRecentCommits(),
this.getContributors(),
this.getLanguages()
]);
const stats = {
repository: {
name: repoInfo?.full_name || '',
description: repoInfo?.description || '',
stars: repoInfo?.stargazers_count || 0,
forks: repoInfo?.forks_count || 0,
issues: repoInfo?.open_issues_count || 0,
watchers: repoInfo?.subscribers_count || 0,
createdAt: repoInfo?.created_at || '',
updatedAt: repoInfo?.updated_at || '',
url: repoInfo?.html_url || ''
},
recentCommits: commits.map(commit => ({
sha: commit.sha.substring(0, 7),
message: commit.commit.message.split('\n')[0],
author: commit.commit.author.name,
date: commit.commit.author.date,
url: commit.html_url
})),
contributors: contributors.map(contributor => ({
login: contributor.login,
contributions: contributor.contributions,
avatar: contributor.avatar_url,
url: contributor.html_url
})),
languages: languages,
lastUpdate: new Date().toISOString()
};
// 缓存数据
this.cacheData(stats);
return stats;
} catch (error) {
console.error('获取 GitHub 统计数据失败:', error);
return null;
}
}
/**
* 格式化日期
*/
formatDate(dateString) {
const date = new Date(dateString);
const now = new Date();
const diffTime = Math.abs(now - date);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 0) return '今天';
if (diffDays === 1) return '昨天';
if (diffDays < 7) return `${diffDays}天前`;
if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`;
if (diffDays < 365) return `${Math.floor(diffDays / 30)}月前`;
return `${Math.floor(diffDays / 365)}年前`;
}
/**
* 格式化数字(添加千位分隔符)
*/
formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
}
// 创建全局实例
const githubAPI = new GitHubAPI();
// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
module.exports = GitHubAPI;
}