forked from git-for-windows/git-for-windows-automation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttps-request.js
62 lines (59 loc) · 2.08 KB
/
https-request.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
const gently = require('./gently')
module.exports = async (context, hostname, method, requestPath, body, headers) => {
headers = {
'User-Agent': 'GitForWindowsHelperApp/0.0',
Accept: 'application/json',
...headers || {}
}
if (body) {
if (typeof body === 'object') body = JSON.stringify(body)
headers['Content-Type'] = 'application/json'
headers['Content-Length'] = body.length
}
const options = {
port: 443,
hostname: hostname || 'api.github.com',
method: method || 'GET',
path: requestPath,
headers
}
return new Promise((resolve, reject) => {
try {
const https = require('https')
const req = https.request(options, res => {
res.on('error', e => reject(e))
if (res.statusCode === 204) resolve({
statusCode: res.statusCode,
statusMessage: res.statusMessage,
headers: res.headers
})
const chunks = []
res.on('data', data => chunks.push(data))
res.on('end', () => {
const json = Buffer.concat(chunks).toString('utf-8')
if (res.statusCode > 299) {
context.log('FAILED GitHub REST API call!')
context.log(options)
reject({
statusCode: res.statusCode,
statusMessage: res.statusMessage,
body: json,
json: gently(() => JSON.parse(json))
})
return
}
try {
resolve(JSON.parse(json))
} catch (e) {
reject(`Invalid JSON: ${json}`)
}
})
})
req.on('error', err => reject(err))
if (body) req.write(body)
req.end()
} catch (e) {
reject(e)
}
})
}