-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (69 loc) · 2.19 KB
/
index.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict'
var extend = require('xtend')
var http = require('http')
var https = require('https')
var once = require('once')
var unzipResponse = require('unzip-response') // excluded from browser build
var url = require('url')
module.exports = streamPost
function streamPost (opts, cb) {
opts = typeof opts === 'string' ? { url: opts } : extend(opts)
cb = once(cb)
if (opts.url) parseOptsUrl(opts)
if (opts.headers == null) opts.headers = {}
if (!opts.method) opts.method = 'POST'
opts.method = opts.method.toUpperCase()
if (opts.json) {
opts.headers.accept = 'application/json'
opts.headers['content-type'] = 'application/json'
}
// Request gzip/deflate
var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
return h.toLowerCase() === 'accept-encoding'
})
if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'
// Support http: and https: urls
var protocol = opts.protocol === 'https:' ? https : http
var req = protocol.request(opts, function (res) {
var tryUnzip = typeof unzipResponse === 'function' && opts.method !== 'HEAD'
cb(null, tryUnzip ? unzipResponse(res) : res)
})
req.on('error', cb)
return req
}
module.exports.concat = function (opts, cb) {
return streamPost(opts, function (err, res) {
if (err) return cb(err)
var chunks = []
res.on('data', function (chunk) {
chunks.push(chunk)
})
res.on('end', function () {
var data = Buffer.concat(chunks)
if (opts.json) {
try {
data = JSON.parse(data.toString())
} catch (err) {
return cb(err, res, data)
}
}
cb(null, res, data)
})
})
}
;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
module.exports[method] = function (opts, cb) {
if (typeof opts === 'string') opts = { url: opts }
opts.method = method.toUpperCase()
return streamPost(opts, cb)
}
})
function parseOptsUrl (opts) {
var loc = url.parse(opts.url)
if (loc.hostname) opts.hostname = loc.hostname
if (loc.port) opts.port = loc.port
if (loc.protocol) opts.protocol = loc.protocol
if (loc.auth) opts.auth = loc.auth
opts.path = loc.path
delete opts.url
}