-
Notifications
You must be signed in to change notification settings - Fork 53
/
requests.js
46 lines (38 loc) · 1.24 KB
/
requests.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
const http = require('http')
const https = require('https')
const post = async (lokiUrl, contentType, headers = {}, data = '', timeout) => {
// Construct a buffer from the data string to have deterministic data size
const dataBuffer = Buffer.from(data, 'utf8')
// Construct the headers
const defaultHeaders = {
'Content-Type': contentType,
'Content-Length': dataBuffer.length
}
return new Promise((resolve, reject) => {
// Decide which http library to use based on the url
const lib = lokiUrl.protocol === 'https:' ? https : http
// Construct the node request options
const options = {
hostname: lokiUrl.hostname,
port: lokiUrl.port !== '' ? lokiUrl.port : (lokiUrl.protocol === 'https:' ? 443 : 80),
path: lokiUrl.pathname,
method: 'POST',
headers: Object.assign(defaultHeaders, headers),
timeout: timeout
}
// Construct the request
const req = lib.request(options, res => {
let resData = ''
res.on('data', _data => (resData += _data))
res.on('end', () => resolve(resData))
})
// Error listener
req.on('error', error => {
reject(error)
})
// Write to request
req.write(dataBuffer)
req.end()
})
}
module.exports = { post }