1 | const http = require('http')
|
2 | const https = require('https')
|
3 | const { parse } = require('url')
|
4 |
|
5 | module.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 | })
|
23 | req.on('error', onError)
|
24 | req.on('response', res => {
|
25 | bufferResponse(res, (err, body) => {
|
26 | if (err) return onError(err)
|
27 | if (res.statusCode < 200 || res.statusCode >= 300) {
|
28 | return onError(new Error(`Bad statusCode from API: ${res.statusCode}\n${body}`))
|
29 | }
|
30 | cb(null, body)
|
31 | })
|
32 | })
|
33 | req.write(body)
|
34 | req.end()
|
35 | }
|
36 |
|
37 | const bufferResponse = (stream, cb) => {
|
38 | let data = ''
|
39 | stream.on('error', cb)
|
40 | stream.setEncoding('utf8')
|
41 | stream.on('data', d => { data += d })
|
42 | stream.on('end', () => cb(null, data))
|
43 | }
|