-
Notifications
You must be signed in to change notification settings - Fork 145
/
github.js
103 lines (85 loc) · 2.34 KB
/
github.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
const pify = require('pify')
const request = pify(require('request'))
function getRequestHeaders() {
const requestHeaders = {
'User-Agent': 'request',
}
const optionalAuthToken = process.env.GITHUB_TOKEN
if (optionalAuthToken) {
requestHeaders.Authorization = `token ${optionalAuthToken}`
}
return requestHeaders
}
function getNextLink(link) {
if (!link) {
return null
}
const nextLink = link.split(',').find(s => s.includes('rel="next"'))
if (!nextLink) {
return null
}
return nextLink.split(';')[0].slice(1, -1)
}
function getContributorsPage(url) {
return request
.get({
url,
headers: getRequestHeaders(),
})
.then(res => {
const body = JSON.parse(res.body)
if (res.statusCode >= 400) {
if (res.statusCode === 404) {
throw new Error('No contributors found on the GitHub repository')
}
throw new Error(body.message)
}
const contributorsIds = body.map(contributor => contributor.login)
const nextLink = getNextLink(res.headers.link)
if (nextLink) {
return getContributorsPage(nextLink).then(nextContributors => {
return contributorsIds.concat(nextContributors)
})
}
return contributorsIds
})
}
const getUserInfo = function(username, hostname) {
/* eslint-disable complexity */
if (!hostname) {
hostname = 'https://github.com'
}
const root = hostname.replace(/:\/\//, '://api.')
return request
.get({
url: `${root}/users/${username}`,
headers: getRequestHeaders(),
})
.then(res => {
const body = JSON.parse(res.body)
let profile = body.blog || body.html_url
// Github throwing specific errors as 200...
if (!profile && body.message) {
throw new Error(body.message)
}
profile = profile.startsWith('http') ? profile : `http://${profile}`
return {
login: body.login,
name: body.name || username,
avatar_url: body.avatar_url,
profile,
}
})
}
const getContributors = function(owner, name, hostname) {
if (!hostname) {
hostname = 'https://github.com'
}
const root = hostname.replace(/:\/\//, '://api.')
const url = `${root}/repos/${owner}/${name}/contributors?per_page=100`
return getContributorsPage(url)
}
module.exports = {
getUserInfo,
getContributors,
}