UNPKG

1.1 kBJavaScriptView Raw
1const http = require('http')
2const https = require('https')
3const { parse } = require('url')
4
5module.exports = ({ url, headers, body, agent }, cb) => {
6 let didError = false
7 const onError = (err) => {
8 if (didError) return
9 didError = true
10 cb(err)
11 }
12
13 const parsedUrl = parse(url)
14 const secure = parsedUrl.protocol === 'https:'
15 const transport = secure ? https : http
16 const req = transport.request({
17 method: 'POST',
18 hostname: parsedUrl.hostname,
19 port: parsedUrl.port,
20 path: parsedUrl.path,
21 headers,
22 agent
23 })
24 req.on('error', onError)
25 req.on('response', res => {
26 bufferResponse(res, (err, body) => {
27 if (err) return onError(err)
28 if (res.statusCode < 200 || res.statusCode >= 300) {
29 return onError(new Error(`Bad statusCode from API: ${res.statusCode}\n${body}`))
30 }
31 cb(null, body)
32 })
33 })
34 req.write(body)
35 req.end()
36}
37
38const bufferResponse = (stream, cb) => {
39 let data = ''
40 stream.on('error', cb)
41 stream.setEncoding('utf8')
42 stream.on('data', d => { data += d })
43 stream.on('end', () => cb(null, data))
44}