-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.js
66 lines (60 loc) · 1.85 KB
/
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
63
64
65
66
const https = require('https')
async function request({
apiToken,
hostname = 'api.tidbyt.com',
port = '443',
path,
method = 'GET',
headers = {},
body = null,
raw = false,
encoding = 'utf-8',
}) {
const httpOptions = {
hostname,
port,
path,
method,
headers: {
'Authorization': `Bearer ${apiToken}`,
...headers,
}
}
if (!apiToken) throw new Error('apiToken is required')
if (!path) throw new Error('path is required')
return new Promise((resolve, reject) => {
const request = https.request(httpOptions, (res) => {
let responseBufs = []
let responseStr = ''
res.on('data', (chunk) => {
if (Buffer.isBuffer(chunk)) {
responseBufs.push(chunk)
}
else {
responseStr = responseStr + chunk;
}
}).on('end', () => {
const buf = Buffer.concat(responseBufs)
if (raw) {
return resolve(buf)
}
responseStr = responseBufs.length > 0 ? buf.toString(encoding) : responseStr
const response = JSON.parse(responseStr)
if (res.statusCode >= 400) {
const error = new Error(`${response.message || res.statusMessage}`)
error.code = response.code || res.statusCode
error.statusCode = res.statusCode
return reject(error)
}
resolve(response)
})
})
.setTimeout(0)
.on('error', reject)
if (body) {
request.write(JSON.stringify(body))
}
request.end()
})
}
module.exports = request