UNPKG

1.27 kBJavaScriptView Raw
1const http = require('http')
2const https = require('https')
3
4const post = async (lokiUrl, contentType, headers = {}, data = '', timeout) => {
5 // Construct a buffer from the data string to have deterministic data size
6 const dataBuffer = Buffer.from(data, 'utf8')
7
8 // Construct the headers
9 const defaultHeaders = {
10 'Content-Type': contentType,
11 'Content-Length': dataBuffer.length
12 }
13
14 return new Promise((resolve, reject) => {
15 // Decide which http library to use based on the url
16 const lib = lokiUrl.protocol === 'https:' ? https : http
17
18 // Construct the node request options
19 const options = {
20 hostname: lokiUrl.hostname,
21 port: lokiUrl.port !== '' ? lokiUrl.port : (lokiUrl.protocol === 'https:' ? 443 : 80),
22 path: lokiUrl.pathname,
23 method: 'POST',
24 headers: Object.assign(defaultHeaders, headers),
25 timeout: timeout
26 }
27
28 // Construct the request
29 const req = lib.request(options, res => {
30 let resData = ''
31 res.on('data', _data => (resData += _data))
32 res.on('end', () => resolve(resData))
33 })
34
35 // Error listener
36 req.on('error', error => {
37 reject(error)
38 })
39
40 // Write to request
41 req.write(dataBuffer)
42 req.end()
43 })
44}
45
46module.exports = { post }