forked from then/then-request
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (69 loc) · 2.37 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
'use strict';
var assert = require('assert');
var parseUrl = require('url').parse;
var Promise = require('promise');
var concat = require('concat-stream');
var Response = require('http-response-object');
var handleQs = require('./lib/handle-qs.js');
module.exports = doRequest;
module.exports._request = require('http-basic');
function doRequest(method, url, options, callback) {
var result = new Promise(function (resolve, reject) {
// check types of arguments
if (typeof method !== 'string') {
throw new TypeError('The method must be a string.');
}
if (typeof url !== 'string') {
throw new TypeError('The URL/path must be a string.');
}
if (typeof options === 'function') {
callback = options;
options = {};
}
if (options === null || options === undefined) {
options = {};
}
if (typeof options !== 'object') {
throw new TypeError('Options must be an object (or null).');
}
if (typeof callback !== 'function') {
callback = undefined;
}
method = method.toUpperCase();
options.headers = options.headers || {};
// handle query string
if (options.qs) {
url = handleQs(url, options.qs);
}
// handle json body
if (options.json) {
options.body = JSON.stringify(options.json);
options.headers['content-type'] = 'application/json';
}
var body = options.body ? options.body : new Buffer(0);
if (typeof body === 'string') body = new Buffer(body);
assert(Buffer.isBuffer(body), 'body should be a Buffer or a String');
if (!Object.keys(options.headers).some(function (name) { return name.toLowerCase() === 'content-length'; })) {
options.headers['content-length'] = body.length;
}
var req = module.exports._request(method, url, {
headers: options.headers,
followRedirects: options.followRedirects !== false,
gzip: options.gzip !== false,
cache: options.cache
}, function (err, res) {
if (err) return reject(err);
res.body.on('error', reject);
res.body.pipe(concat(function (body) {
resolve(new Response(res.statusCode, res.headers, Array.isArray(body) ? new Buffer(0) : body));
}));
});
if (req) {
req.end(body);
}
});
result.getBody = function (encoding) {
return result.then(function (res) { return res.getBody(encoding); });
};
return result.nodeify(callback);
}