This repository has been archived by the owner on Nov 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (87 loc) · 2.75 KB
/
index.js
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
const https = require('https');
const GITHUB_USER = process.env.GITHUB_USER ? process.env.GITHUB_USER : '';
const GITHUB_API_KEY = process.env.GITHUB_API_KEY ? process.env.GITHUB_API_KEY : '';
function fetchReposMetadataJson(host, path) {
const url = `https://${host}/${path}`;
const options = {
headers: {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0',
'Authorization': `token ${GITHUB_API_KEY}`,
},
};
return new Promise((resolve, reject) => {
const callback = function (response) {
if (!response) {
reject('Error: response is undefined!');
return;
}
if (response.statusCode !== 200) {
let errStr = '';
response.on('data', function (chunk) {
errStr += chunk;
});
response.on('end', function () {
reject(`Got unexpected status code: '${response ? response.statusCode : undefined}'! Details:\n${errStr}`);
});
return;
}
let dataStr = '';
response.on('data', function (chunk) {
dataStr += chunk;
});
response.on('end', function () {
let dataObj;
try {
dataObj = JSON.parse(dataStr);
} catch (err) {
reject(err);
return;
}
resolve(dataObj);
});
};
https.get(url, options, callback).on('error', reject);
});
}
function fetchAllRepos(repoType) {
const repos = [];
return new Promise((resolve, reject) => {
function fetchReposByPage(page) {
fetchReposMetadataJson('api.github.com', `${repoType}/${GITHUB_USER}/repos?page=${page}&per_page=30`).then((data) => {
if (data.length === 0) {
resolve(repos);
} else {
console.log(`[page ${page}]`);
console.log(`--------------`);
// Here `data` is already parsed as JSON. Append to `repos` array.
repos.push.apply(repos, data.map((repo) => repo.name));
setTimeout(() => {
fetchReposByPage(page + 1);
}, 800 + Math.floor(Math.random() * 400));
}
}).catch((error) => {
if (error.res) {
console.log('Status: ', error.res.statusCode);
console.log('Body: ', error.res.body);
} else if (error.err) {
console.log('Error: ', error.err);
} else if (error) {
console.log(error);
} else {
console.log('Unknown error!');
}
resolve(repos);
});
}
fetchReposByPage(1);
});
}
fetchAllRepos('users').then((repos) => {
console.log('\n-----');
console.log(`Total repos: ${repos.length}`);
console.log('-----\n');
repos.forEach((repo) => {
console.log(`"${repo}"`);
});
});