make Prettier
This commit is contained in:
parent
b6900b937b
commit
9ab91d9721
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"printWidth": 80,
|
||||||
|
"singleQuote": true,
|
||||||
|
"tabWidth": 4,
|
||||||
|
"trailingComma": "none",
|
||||||
|
"useTabs": false
|
||||||
|
}
|
78
README.md
78
README.md
|
@ -16,7 +16,7 @@ npm install --save @root/request
|
||||||
|
|
||||||
```js
|
```js
|
||||||
var request = require('@root/request');
|
var request = require('@root/request');
|
||||||
request('http://www.google.com', function (error, response, body) {
|
request('http://www.google.com', function(error, response, body) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
||||||
console.log('body:', body); // Print the HTML for the Google homepage.
|
console.log('body:', body); // Print the HTML for the Google homepage.
|
||||||
|
@ -30,12 +30,14 @@ var promisify = require('util').promisify;
|
||||||
var request = require('@root/request');
|
var request = require('@root/request');
|
||||||
request = promisify(request);
|
request = promisify(request);
|
||||||
|
|
||||||
request('http://www.google.com').then(function (response) {
|
request('http://www.google.com')
|
||||||
|
.then(function(response) {
|
||||||
console.log('statusCode:', response.statusCode); // Print the response status code if a response was received
|
console.log('statusCode:', response.statusCode); // Print the response status code if a response was received
|
||||||
console.log('body:', response.body); // Print the HTML for the Google homepage.
|
console.log('body:', response.body); // Print the HTML for the Google homepage.
|
||||||
}).catch(function (error) {
|
})
|
||||||
|
.catch(function(error) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Table of contents
|
## Table of contents
|
||||||
|
@ -49,6 +51,7 @@ request('http://www.google.com').then(function (response) {
|
||||||
## Forms
|
## Forms
|
||||||
|
|
||||||
`urequest` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads.
|
`urequest` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads.
|
||||||
|
|
||||||
<!-- For `multipart/related` refer to the `multipart` API. -->
|
<!-- For `multipart/related` refer to the `multipart` API. -->
|
||||||
|
|
||||||
#### application/x-www-form-urlencoded (URL-Encoded Forms)
|
#### application/x-www-form-urlencoded (URL-Encoded Forms)
|
||||||
|
@ -56,16 +59,21 @@ request('http://www.google.com').then(function (response) {
|
||||||
URL-encoded forms are simple.
|
URL-encoded forms are simple.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
request.post('http://service.com/upload', {form:{key:'value'}})
|
request.post('http://service.com/upload', { form: { key: 'value' } });
|
||||||
// or
|
// or
|
||||||
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
|
request.post(
|
||||||
|
{ url: 'http://service.com/upload', form: { key: 'value' } },
|
||||||
|
function(err, httpResponse, body) {
|
||||||
|
/* ... */
|
||||||
|
}
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
// or
|
// or
|
||||||
request.post('http://service.com/upload').form({key:'value'})
|
request.post('http://service.com/upload').form({key:'value'})
|
||||||
-->
|
-->
|
||||||
|
|
||||||
|
|
||||||
#### multipart/form-data (Multipart Form Uploads)
|
#### multipart/form-data (Multipart Form Uploads)
|
||||||
|
|
||||||
For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
|
For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
|
||||||
|
@ -100,13 +108,17 @@ var formData = {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
|
request.post(
|
||||||
|
{ url: 'http://service.com/upload', formData: formData },
|
||||||
|
function optionalCallback(err, httpResponse, body) {
|
||||||
if (err) {
|
if (err) {
|
||||||
return console.error('upload failed:', err);
|
return console.error('upload failed:', err);
|
||||||
}
|
}
|
||||||
console.log('Upload successful! Server responded with:', body);
|
console.log('Upload successful! Server responded with:', body);
|
||||||
});
|
}
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
|
|
||||||
For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.)
|
For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.)
|
||||||
|
@ -133,18 +145,19 @@ request.get('http://some.server.com/').auth('username', 'password', false);
|
||||||
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
|
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
|
||||||
// or
|
// or
|
||||||
-->
|
-->
|
||||||
|
|
||||||
```js
|
```js
|
||||||
request.get('http://some.server.com/', {
|
request.get('http://some.server.com/', {
|
||||||
'auth': {
|
auth: {
|
||||||
'user': 'username',
|
user: 'username',
|
||||||
'pass': 'password',
|
pass: 'password',
|
||||||
'sendImmediately': false
|
sendImmediately: false
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// or
|
// or
|
||||||
request.get('http://some.server.com/', {
|
request.get('http://some.server.com/', {
|
||||||
'auth': {
|
auth: {
|
||||||
'bearer': 'bearerToken'
|
bearer: 'bearerToken'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
@ -177,7 +190,7 @@ var username = 'username',
|
||||||
password = 'password',
|
password = 'password',
|
||||||
url = 'http://' + username + ':' + password + '@some.server.com';
|
url = 'http://' + username + ':' + password + '@some.server.com';
|
||||||
|
|
||||||
request({url: url}, function (error, response, body) {
|
request({ url: url }, function(error, response, body) {
|
||||||
// Do more stuff with 'body' here
|
// Do more stuff with 'body' here
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
@ -218,8 +231,8 @@ var options = {
|
||||||
function callback(error, response, body) {
|
function callback(error, response, body) {
|
||||||
if (!error && response.statusCode == 200) {
|
if (!error && response.statusCode == 200) {
|
||||||
var info = JSON.parse(body);
|
var info = JSON.parse(body);
|
||||||
console.log(info.stargazers_count + " Stars");
|
console.log(info.stargazers_count + ' Stars');
|
||||||
console.log(info.forks_count + " Forks");
|
console.log(info.forks_count + ' Forks');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -235,8 +248,10 @@ request(options, callback);
|
||||||
`urequest` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
|
`urequest` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
/* Pattern */ 'http://unix:SOCKET:PATH'
|
/* Pattern */ 'http://unix:SOCKET:PATH';
|
||||||
/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
|
/* Example */ request.get(
|
||||||
|
'http://unix:/absolute/path/to/unix.socket:/request/path'
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
|
Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
|
||||||
|
@ -314,30 +329,31 @@ instead, it **returns a wrapper** that has your default settings applied to it.
|
||||||
`request.defaults` to add/override defaults that were previously defaulted.
|
`request.defaults` to add/override defaults that were previously defaulted.
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
//requests using baseRequest() will set the 'x-token' header
|
//requests using baseRequest() will set the 'x-token' header
|
||||||
var baseRequest = request.defaults({
|
var baseRequest = request.defaults({
|
||||||
headers: {'x-token': 'my-token'}
|
headers: { 'x-token': 'my-token' }
|
||||||
})
|
});
|
||||||
|
|
||||||
//requests using specialRequest() will include the 'x-token' header set in
|
//requests using specialRequest() will include the 'x-token' header set in
|
||||||
//baseRequest and will also include the 'special' header
|
//baseRequest and will also include the 'special' header
|
||||||
var specialRequest = baseRequest.defaults({
|
var specialRequest = baseRequest.defaults({
|
||||||
headers: {special: 'special value'}
|
headers: { special: 'special value' }
|
||||||
})
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### request.METHOD()
|
### request.METHOD()
|
||||||
|
|
||||||
These HTTP method convenience functions act just like `request()` but with a default method already set for you:
|
These HTTP method convenience functions act just like `request()` but with a default method already set for you:
|
||||||
|
|
||||||
- *request.get()*: Defaults to `method: "GET"`.
|
- _request.get()_: Defaults to `method: "GET"`.
|
||||||
- *request.post()*: Defaults to `method: "POST"`.
|
- _request.post()_: Defaults to `method: "POST"`.
|
||||||
- *request.put()*: Defaults to `method: "PUT"`.
|
- _request.put()_: Defaults to `method: "PUT"`.
|
||||||
- *request.patch()*: Defaults to `method: "PATCH"`.
|
- _request.patch()_: Defaults to `method: "PATCH"`.
|
||||||
- *request.del() / request.delete()*: Defaults to `method: "DELETE"`.
|
- _request.del() / request.delete()_: Defaults to `method: "DELETE"`.
|
||||||
- *request.head()*: Defaults to `method: "HEAD"`.
|
- _request.head()_: Defaults to `method: "HEAD"`.
|
||||||
- *request.options()*: Defaults to `method: "OPTIONS"`.
|
- _request.options()_: Defaults to `method: "OPTIONS"`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
@ -5,7 +5,11 @@ var request = require('../');
|
||||||
|
|
||||||
// will redirect to https://www.github.com and then https://github.com
|
// will redirect to https://www.github.com and then https://github.com
|
||||||
//request('http://www.github.com', function (error, response, body) {
|
//request('http://www.github.com', function (error, response, body) {
|
||||||
request({ uri: { protocol: 'http:', hostname: 'www.github.com' } }, function (error, response, body) {
|
request({ uri: { protocol: 'http:', hostname: 'www.github.com' } }, function(
|
||||||
|
error,
|
||||||
|
response,
|
||||||
|
body
|
||||||
|
) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -9,15 +9,18 @@ var request = require('../');
|
||||||
//request('http://www.github.com', function (error, response, body) {
|
//request('http://www.github.com', function (error, response, body) {
|
||||||
request(
|
request(
|
||||||
//{ url: 'http://postb.in/syfxxnko'
|
//{ url: 'http://postb.in/syfxxnko'
|
||||||
{ url: 'http://localhost:3007/form-data/'
|
{
|
||||||
, method: 'POST'
|
url: 'http://localhost:3007/form-data/',
|
||||||
, headers: { 'X-Foo': 'Bar' }
|
method: 'POST',
|
||||||
, formData: {
|
headers: { 'X-Foo': 'Bar' },
|
||||||
foo: 'bar'
|
formData: {
|
||||||
, baz: require('fs').createReadStream(require('path').join(__dirname, 'get-to-json.js'))
|
foo: 'bar',
|
||||||
|
baz: require('fs').createReadStream(
|
||||||
|
require('path').join(__dirname, 'get-to-json.js')
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
, function (error, response, body) {
|
function(error, response, body) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
//var request = require('urequest');
|
//var request = require('urequest');
|
||||||
var request = require('../');
|
var request = require('../');
|
||||||
request('https://www.google.com', function (error, response, body) {
|
request('https://www.google.com', function(error, response, body) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
//var request = require('urequest');
|
//var request = require('urequest');
|
||||||
var request = require('../');
|
var request = require('../');
|
||||||
request('http://www.google.com', function (error, response, body) {
|
request('http://www.google.com', function(error, response, body) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
||||||
console.log('body:', body); // Print the HTML for the Google homepage.
|
console.log('body:', body); // Print the HTML for the Google homepage.
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
//var request = require('urequest');
|
//var request = require('urequest');
|
||||||
var request = require('../');
|
var request = require('../');
|
||||||
request('https://www.google.com', function (error, response, body) {
|
request('https://www.google.com', function(error, response, body) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
||||||
console.log('body:', body); // Print the HTML for the Google homepage.
|
console.log('body:', body); // Print the HTML for the Google homepage.
|
||||||
|
|
|
@ -4,7 +4,11 @@
|
||||||
var request = require('../');
|
var request = require('../');
|
||||||
|
|
||||||
// would normally redirect to https://www.github.com and then https://github.com
|
// would normally redirect to https://www.github.com and then https://github.com
|
||||||
request({ uri: 'https://www.github.com', followRedirect: false }, function (error, response, body) {
|
request({ uri: 'https://www.github.com', followRedirect: false }, function(
|
||||||
|
error,
|
||||||
|
response,
|
||||||
|
body
|
||||||
|
) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -8,12 +8,13 @@ var request = require('../');
|
||||||
// will redirect to https://www.github.com and then https://github.com
|
// will redirect to https://www.github.com and then https://github.com
|
||||||
//request('http://www.github.com', function (error, response, body) {
|
//request('http://www.github.com', function (error, response, body) {
|
||||||
request(
|
request(
|
||||||
{ url: 'http://postb.in/2meyt50C'
|
{
|
||||||
, method: 'POST'
|
url: 'http://postb.in/2meyt50C',
|
||||||
, headers: { 'X-Foo': 'Bar' }
|
method: 'POST',
|
||||||
, form: { foo: 'bar', baz: 'qux' }
|
headers: { 'X-Foo': 'Bar' },
|
||||||
}
|
form: { foo: 'bar', baz: 'qux' }
|
||||||
, function (error, response, body) {
|
},
|
||||||
|
function(error, response, body) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log('error:', error); // Print the error if one occurred
|
console.log('error:', error); // Print the error if one occurred
|
||||||
return;
|
return;
|
||||||
|
|
202
index.js
202
index.js
|
@ -11,7 +11,7 @@ function debug() {
|
||||||
}
|
}
|
||||||
|
|
||||||
function mergeOrDelete(defaults, updates) {
|
function mergeOrDelete(defaults, updates) {
|
||||||
Object.keys(defaults).forEach(function (key) {
|
Object.keys(defaults).forEach(function(key) {
|
||||||
if (!(key in updates)) {
|
if (!(key in updates)) {
|
||||||
updates[key] = defaults[key];
|
updates[key] = defaults[key];
|
||||||
return;
|
return;
|
||||||
|
@ -21,7 +21,10 @@ function mergeOrDelete(defaults, updates) {
|
||||||
// CRDT probs...
|
// CRDT probs...
|
||||||
if ('undefined' === typeof updates[key]) {
|
if ('undefined' === typeof updates[key]) {
|
||||||
delete updates[key];
|
delete updates[key];
|
||||||
} else if ('object' === typeof defaults[key] && 'object' === typeof updates[key]) {
|
} else if (
|
||||||
|
'object' === typeof defaults[key] &&
|
||||||
|
'object' === typeof updates[key]
|
||||||
|
) {
|
||||||
updates[key] = mergeOrDelete(defaults[key], updates[key]);
|
updates[key] = mergeOrDelete(defaults[key], updates[key]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -32,7 +35,7 @@ function mergeOrDelete(defaults, updates) {
|
||||||
// retrieves an existing header, case-sensitive
|
// retrieves an existing header, case-sensitive
|
||||||
function getHeaderName(reqOpts, header) {
|
function getHeaderName(reqOpts, header) {
|
||||||
var headerNames = {};
|
var headerNames = {};
|
||||||
Object.keys(reqOpts.headers).forEach(function (casedName) {
|
Object.keys(reqOpts.headers).forEach(function(casedName) {
|
||||||
headerNames[casedName.toLowerCase()] = casedName;
|
headerNames[casedName.toLowerCase()] = casedName;
|
||||||
});
|
});
|
||||||
// returns the key, which in erroneous cases could be an empty string
|
// returns the key, which in erroneous cases could be an empty string
|
||||||
|
@ -44,12 +47,11 @@ function hasHeader(reqOpts, header) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function toJSONifier(keys) {
|
function toJSONifier(keys) {
|
||||||
|
return function() {
|
||||||
return function () {
|
|
||||||
var obj = {};
|
var obj = {};
|
||||||
var me = this;
|
var me = this;
|
||||||
|
|
||||||
keys.forEach(function (key) {
|
keys.forEach(function(key) {
|
||||||
if (me[key] && 'function' === typeof me[key].toJSON) {
|
if (me[key] && 'function' === typeof me[key].toJSON) {
|
||||||
obj[key] = me[key].toJSON();
|
obj[key] = me[key].toJSON();
|
||||||
} else {
|
} else {
|
||||||
|
@ -65,13 +67,13 @@ function setDefaults(defs) {
|
||||||
defs = defs || {};
|
defs = defs || {};
|
||||||
|
|
||||||
function urequestHelper(opts, cb) {
|
function urequestHelper(opts, cb) {
|
||||||
debug("\n[urequest] processed options:");
|
debug('\n[urequest] processed options:');
|
||||||
debug(opts);
|
debug(opts);
|
||||||
|
|
||||||
function onResponse(resp) {
|
function onResponse(resp) {
|
||||||
var followRedirect;
|
var followRedirect;
|
||||||
|
|
||||||
Object.keys(defs).forEach(function (key) {
|
Object.keys(defs).forEach(function(key) {
|
||||||
if (key in opts && 'undefined' !== typeof opts[key]) {
|
if (key in opts && 'undefined' !== typeof opts[key]) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -79,15 +81,24 @@ function setDefaults(defs) {
|
||||||
});
|
});
|
||||||
followRedirect = opts.followRedirect;
|
followRedirect = opts.followRedirect;
|
||||||
|
|
||||||
resp.toJSON = toJSONifier([ 'statusCode', 'body', 'headers', 'request' ]);
|
resp.toJSON = toJSONifier([
|
||||||
|
'statusCode',
|
||||||
|
'body',
|
||||||
|
'headers',
|
||||||
|
'request'
|
||||||
|
]);
|
||||||
|
|
||||||
resp.request = req;
|
resp.request = req;
|
||||||
resp.request.uri = url.parse(opts.url);
|
resp.request.uri = url.parse(opts.url);
|
||||||
//resp.request.method = opts.method;
|
//resp.request.method = opts.method;
|
||||||
resp.request.headers = finalOpts.headers;
|
resp.request.headers = finalOpts.headers;
|
||||||
resp.request.toJSON = toJSONifier([ 'uri', 'method', 'headers' ]);
|
resp.request.toJSON = toJSONifier(['uri', 'method', 'headers']);
|
||||||
|
|
||||||
if (followRedirect && resp.headers.location && -1 !== [ 301, 302, 307, 308 ].indexOf(resp.statusCode)) {
|
if (
|
||||||
|
followRedirect &&
|
||||||
|
resp.headers.location &&
|
||||||
|
-1 !== [301, 302, 307, 308].indexOf(resp.statusCode)
|
||||||
|
) {
|
||||||
debug('Following redirect: ' + resp.headers.location);
|
debug('Following redirect: ' + resp.headers.location);
|
||||||
if ('GET' !== opts.method && !opts.followAllRedirects) {
|
if ('GET' !== opts.method && !opts.followAllRedirects) {
|
||||||
followRedirect = false;
|
followRedirect = false;
|
||||||
|
@ -104,8 +115,12 @@ function setDefaults(defs) {
|
||||||
if (!opts.followOriginalHttpMethod) {
|
if (!opts.followOriginalHttpMethod) {
|
||||||
opts.method = 'GET';
|
opts.method = 'GET';
|
||||||
opts.body = null;
|
opts.body = null;
|
||||||
delete opts.headers[getHeaderName(opts, 'Content-Length')];
|
delete opts.headers[
|
||||||
delete opts.headers[getHeaderName(opts, 'Transfer-Encoding')];
|
getHeaderName(opts, 'Content-Length')
|
||||||
|
];
|
||||||
|
delete opts.headers[
|
||||||
|
getHeaderName(opts, 'Transfer-Encoding')
|
||||||
|
];
|
||||||
}
|
}
|
||||||
if (opts.removeRefererHeader && opts.headers) {
|
if (opts.removeRefererHeader && opts.headers) {
|
||||||
delete opts.headers.referer;
|
delete opts.headers.referer;
|
||||||
|
@ -122,7 +137,7 @@ function setDefaults(defs) {
|
||||||
resp.body = '';
|
resp.body = '';
|
||||||
}
|
}
|
||||||
resp._bodyLength = 0;
|
resp._bodyLength = 0;
|
||||||
resp.on('data', function (chunk) {
|
resp.on('data', function(chunk) {
|
||||||
if ('string' === typeof resp.body) {
|
if ('string' === typeof resp.body) {
|
||||||
resp.body += chunk.toString(opts.encoding);
|
resp.body += chunk.toString(opts.encoding);
|
||||||
} else {
|
} else {
|
||||||
|
@ -130,7 +145,7 @@ function setDefaults(defs) {
|
||||||
resp._bodyLength += chunk.length;
|
resp._bodyLength += chunk.length;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
resp.on('end', function () {
|
resp.on('end', function() {
|
||||||
if ('string' !== typeof resp.body) {
|
if ('string' !== typeof resp.body) {
|
||||||
if (1 === resp._body.length) {
|
if (1 === resp._body.length) {
|
||||||
resp.body = resp._body[0];
|
resp.body = resp._body[0];
|
||||||
|
@ -144,12 +159,12 @@ function setDefaults(defs) {
|
||||||
// but request.js doesn't do that.
|
// but request.js doesn't do that.
|
||||||
try {
|
try {
|
||||||
resp.body = JSON.parse(resp.body);
|
resp.body = JSON.parse(resp.body);
|
||||||
} catch(e) {
|
} catch (e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("\n[urequest] resp.toJSON():");
|
debug('\n[urequest] resp.toJSON():');
|
||||||
debug(resp.toJSON());
|
debug(resp.toJSON());
|
||||||
cb(null, resp, resp.body);
|
cb(null, resp, resp.body);
|
||||||
});
|
});
|
||||||
|
@ -172,29 +187,42 @@ function setDefaults(defs) {
|
||||||
} else if (opts.json && true !== opts.json) {
|
} else if (opts.json && true !== opts.json) {
|
||||||
_body = JSON.stringify(opts.json);
|
_body = JSON.stringify(opts.json);
|
||||||
} else if (opts.form) {
|
} else if (opts.form) {
|
||||||
_body = Object.keys(opts.form).filter(function (key) {
|
_body = Object.keys(opts.form)
|
||||||
|
.filter(function(key) {
|
||||||
if ('undefined' !== typeof opts.form[key]) {
|
if ('undefined' !== typeof opts.form[key]) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}).map(function (key) {
|
})
|
||||||
return encodeURIComponent(key) + '=' + encodeURIComponent(String(opts.form[key]));
|
.map(function(key) {
|
||||||
}).join('&');
|
return (
|
||||||
|
encodeURIComponent(key) +
|
||||||
|
'=' +
|
||||||
|
encodeURIComponent(String(opts.form[key]))
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.join('&');
|
||||||
opts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
opts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||||
}
|
}
|
||||||
if ('string' === typeof _body) {
|
if ('string' === typeof _body) {
|
||||||
_body = Buffer.from(_body);
|
_body = Buffer.from(_body);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.keys(opts.uri).forEach(function (key) {
|
Object.keys(opts.uri).forEach(function(key) {
|
||||||
finalOpts[key] = opts.uri[key];
|
finalOpts[key] = opts.uri[key];
|
||||||
});
|
});
|
||||||
|
|
||||||
// A bug should be raised if request does it differently,
|
// A bug should be raised if request does it differently,
|
||||||
// but I think we're supposed to pass all acceptable options
|
// but I think we're supposed to pass all acceptable options
|
||||||
// on to the raw http request
|
// on to the raw http request
|
||||||
[ 'family', 'host', 'localAddress', 'agent', 'createConnection'
|
[
|
||||||
, 'timeout', 'setHost'
|
'family',
|
||||||
].forEach(function (key) {
|
'host',
|
||||||
|
'localAddress',
|
||||||
|
'agent',
|
||||||
|
'createConnection',
|
||||||
|
'timeout',
|
||||||
|
'setHost'
|
||||||
|
].forEach(function(key) {
|
||||||
finalOpts[key] = opts.uri[key];
|
finalOpts[key] = opts.uri[key];
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -203,18 +231,24 @@ function setDefaults(defs) {
|
||||||
if (_body) {
|
if (_body) {
|
||||||
// Most APIs expect (or require) Content-Length except in the case of multipart uploads
|
// Most APIs expect (or require) Content-Length except in the case of multipart uploads
|
||||||
// Transfer-Encoding: Chunked (the default) is generally only well-supported downstream
|
// Transfer-Encoding: Chunked (the default) is generally only well-supported downstream
|
||||||
finalOpts.headers['Content-Length'] = _body.byteLength || _body.length;
|
finalOpts.headers['Content-Length'] =
|
||||||
|
_body.byteLength || _body.length;
|
||||||
}
|
}
|
||||||
if (opts.auth) {
|
if (opts.auth) {
|
||||||
// if opts.uri specifies auth it will be parsed by url.parse and passed directly to the http module
|
// if opts.uri specifies auth it will be parsed by url.parse and passed directly to the http module
|
||||||
if ('string' !== typeof opts.auth) {
|
if ('string' !== typeof opts.auth) {
|
||||||
opts.auth = (opts.auth.user||opts.auth.username||'') + ':' + (opts.auth.pass||opts.auth.password||'');
|
opts.auth =
|
||||||
|
(opts.auth.user || opts.auth.username || '') +
|
||||||
|
':' +
|
||||||
|
(opts.auth.pass || opts.auth.password || '');
|
||||||
}
|
}
|
||||||
if ('string' === typeof opts.auth) {
|
if ('string' === typeof opts.auth) {
|
||||||
finalOpts.auth = opts.auth;
|
finalOpts.auth = opts.auth;
|
||||||
}
|
}
|
||||||
if (false === opts.sendImmediately) {
|
if (false === opts.sendImmediately) {
|
||||||
console.warn("[Warn] setting `sendImmediately: false` is not yet supported. Please open an issue if this is an important feature that you need.");
|
console.warn(
|
||||||
|
'[Warn] setting `sendImmediately: false` is not yet supported. Please open an issue if this is an important feature that you need.'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (opts.bearer) {
|
if (opts.bearer) {
|
||||||
// having a shortcut for base64 encoding makes sense, but this? Eh, whatevs...
|
// having a shortcut for base64 encoding makes sense, but this? Eh, whatevs...
|
||||||
|
@ -225,34 +259,41 @@ function setDefaults(defs) {
|
||||||
try {
|
try {
|
||||||
MyFormData = opts.FormData || require('form-data');
|
MyFormData = opts.FormData || require('form-data');
|
||||||
// potential options https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15
|
// potential options https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15
|
||||||
} catch(e) {
|
} catch (e) {
|
||||||
console.error("urequest does not include extra dependencies by default");
|
console.error(
|
||||||
console.error("if you need to use 'form-data' you may install it, like so:");
|
'urequest does not include extra dependencies by default'
|
||||||
console.error(" npm install --save form-data");
|
);
|
||||||
|
console.error(
|
||||||
|
"if you need to use 'form-data' you may install it, like so:"
|
||||||
|
);
|
||||||
|
console.error(' npm install --save form-data');
|
||||||
cb(e);
|
cb(e);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
form = new MyFormData();
|
form = new MyFormData();
|
||||||
Object.keys(opts.formData).forEach(function (key) {
|
Object.keys(opts.formData).forEach(function(key) {
|
||||||
function add(key, data, opts) {
|
function add(key, data, opts) {
|
||||||
if (data.value) { opts = data.options; data = data.value; }
|
if (data.value) {
|
||||||
|
opts = data.options;
|
||||||
|
data = data.value;
|
||||||
|
}
|
||||||
form.append(key, data, opts);
|
form.append(key, data, opts);
|
||||||
}
|
}
|
||||||
if (Array.isArray(opts.formData[key])) {
|
if (Array.isArray(opts.formData[key])) {
|
||||||
opts.formData[key].forEach(function (data) {
|
opts.formData[key].forEach(function(data) {
|
||||||
add(key, data);
|
add(key, data);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
add(key, opts.formData[key]);
|
add(key, opts.formData[key]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch(e) {
|
} catch (e) {
|
||||||
cb(e);
|
cb(e);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
formHeaders = form.getHeaders();
|
formHeaders = form.getHeaders();
|
||||||
Object.keys(formHeaders).forEach(function (header) {
|
Object.keys(formHeaders).forEach(function(header) {
|
||||||
finalOpts.headers[header] = formHeaders[header];
|
finalOpts.headers[header] = formHeaders[header];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -260,12 +301,12 @@ function setDefaults(defs) {
|
||||||
// TODO support unix sockets
|
// TODO support unix sockets
|
||||||
if ('https:' === finalOpts.protocol) {
|
if ('https:' === finalOpts.protocol) {
|
||||||
// https://nodejs.org/api/https.html#https_https_request_options_callback
|
// https://nodejs.org/api/https.html#https_https_request_options_callback
|
||||||
debug("\n[urequest] https.request(opts):");
|
debug('\n[urequest] https.request(opts):');
|
||||||
debug(finalOpts);
|
debug(finalOpts);
|
||||||
requester = https;
|
requester = https;
|
||||||
} else if ('http:' === finalOpts.protocol) {
|
} else if ('http:' === finalOpts.protocol) {
|
||||||
// https://nodejs.org/api/http.html#http_http_request_options_callback
|
// https://nodejs.org/api/http.html#http_http_request_options_callback
|
||||||
debug("\n[urequest] http.request(opts):");
|
debug('\n[urequest] http.request(opts):');
|
||||||
debug(finalOpts);
|
debug(finalOpts);
|
||||||
requester = http;
|
requester = http;
|
||||||
} else {
|
} else {
|
||||||
|
@ -278,8 +319,11 @@ function setDefaults(defs) {
|
||||||
debug(formHeaders);
|
debug(formHeaders);
|
||||||
// generally uploads don't use Chunked Encoding (some systems have issues with it)
|
// generally uploads don't use Chunked Encoding (some systems have issues with it)
|
||||||
// and I don't want to do the work to calculate the content-lengths. This seems to work.
|
// and I don't want to do the work to calculate the content-lengths. This seems to work.
|
||||||
req = form.submit(finalOpts, function (err, resp) {
|
req = form.submit(finalOpts, function(err, resp) {
|
||||||
if (err) { cb(err); return; }
|
if (err) {
|
||||||
|
cb(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
onResponse(resp);
|
onResponse(resp);
|
||||||
resp.resume();
|
resp.resume();
|
||||||
});
|
});
|
||||||
|
@ -307,14 +351,14 @@ function setDefaults(defs) {
|
||||||
function parseUrl(str) {
|
function parseUrl(str) {
|
||||||
var obj = url.parse(str);
|
var obj = url.parse(str);
|
||||||
var paths;
|
var paths;
|
||||||
if ('unix' !== (obj.hostname||obj.host||'').toLowerCase()) {
|
if ('unix' !== (obj.hostname || obj.host || '').toLowerCase()) {
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
obj.href = null;
|
obj.href = null;
|
||||||
obj.hostname = obj.host = null;
|
obj.hostname = obj.host = null;
|
||||||
|
|
||||||
paths = (obj.pathname||obj.path||'').split(':');
|
paths = (obj.pathname || obj.path || '').split(':');
|
||||||
|
|
||||||
obj.socketPath = paths.shift();
|
obj.socketPath = paths.shift();
|
||||||
obj.pathname = obj.path = paths.join(':');
|
obj.pathname = obj.path = paths.join(':');
|
||||||
|
@ -323,7 +367,7 @@ function setDefaults(defs) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function urequest(opts, cb) {
|
function urequest(opts, cb) {
|
||||||
debug("\n[urequest] received options:");
|
debug('\n[urequest] received options:');
|
||||||
debug(opts);
|
debug(opts);
|
||||||
var reqOpts = {};
|
var reqOpts = {};
|
||||||
// request.js behavior:
|
// request.js behavior:
|
||||||
|
@ -335,7 +379,7 @@ function setDefaults(defs) {
|
||||||
opts = { url: opts };
|
opts = { url: opts };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports._keys.forEach(function (key) {
|
module.exports._keys.forEach(function(key) {
|
||||||
if (key in opts && 'undefined' !== typeof opts[key]) {
|
if (key in opts && 'undefined' !== typeof opts[key]) {
|
||||||
reqOpts[key] = opts[key];
|
reqOpts[key] = opts[key];
|
||||||
} else if (key in defs) {
|
} else if (key in defs) {
|
||||||
|
@ -364,7 +408,12 @@ function setDefaults(defs) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.body || 'string' === typeof opts.json || opts.form || opts.formData) {
|
if (
|
||||||
|
opts.body ||
|
||||||
|
'string' === typeof opts.json ||
|
||||||
|
opts.form ||
|
||||||
|
opts.formData
|
||||||
|
) {
|
||||||
// TODO this is probably a deviation from request's API
|
// TODO this is probably a deviation from request's API
|
||||||
// need to check and probably eliminate it
|
// need to check and probably eliminate it
|
||||||
reqOpts.method = (reqOpts.method || 'POST').toUpperCase();
|
reqOpts.method = (reqOpts.method || 'POST').toUpperCase();
|
||||||
|
@ -377,8 +426,10 @@ function setDefaults(defs) {
|
||||||
|
|
||||||
// crazy case for easier testing
|
// crazy case for easier testing
|
||||||
if (!hasHeader(reqOpts, 'CoNTeNT-TyPe')) {
|
if (!hasHeader(reqOpts, 'CoNTeNT-TyPe')) {
|
||||||
if ((true === reqOpts.json && reqOpts.body)
|
if (
|
||||||
|| (true !== reqOpts.json && reqOpts.json)) {
|
(true === reqOpts.json && reqOpts.body) ||
|
||||||
|
(true !== reqOpts.json && reqOpts.json)
|
||||||
|
) {
|
||||||
reqOpts.headers['Content-Type'] = 'application/json';
|
reqOpts.headers['Content-Type'] = 'application/json';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -386,50 +437,53 @@ function setDefaults(defs) {
|
||||||
return urequestHelper(reqOpts, cb);
|
return urequestHelper(reqOpts, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
urequest.defaults = function (_defs) {
|
urequest.defaults = function(_defs) {
|
||||||
_defs = mergeOrDelete(defs, _defs);
|
_defs = mergeOrDelete(defs, _defs);
|
||||||
return setDefaults(_defs);
|
return setDefaults(_defs);
|
||||||
};
|
};
|
||||||
[ 'get', 'put', 'post', 'patch', 'delete', 'head', 'options' ].forEach(function (method) {
|
['get', 'put', 'post', 'patch', 'delete', 'head', 'options'].forEach(
|
||||||
urequest[method] = function (obj, cb) {
|
function(method) {
|
||||||
|
urequest[method] = function(obj, cb) {
|
||||||
if ('string' === typeof obj) {
|
if ('string' === typeof obj) {
|
||||||
obj = { url: obj };
|
obj = { url: obj };
|
||||||
}
|
}
|
||||||
obj.method = method.toUpperCase();
|
obj.method = method.toUpperCase();
|
||||||
urequest(obj, cb);
|
urequest(obj, cb);
|
||||||
};
|
};
|
||||||
});
|
}
|
||||||
|
);
|
||||||
urequest.del = urequest.delete;
|
urequest.del = urequest.delete;
|
||||||
|
|
||||||
return urequest;
|
return urequest;
|
||||||
}
|
}
|
||||||
|
|
||||||
var _defaults = {
|
var _defaults = {
|
||||||
sendImmediately: true
|
sendImmediately: true,
|
||||||
, method: 'GET'
|
method: 'GET',
|
||||||
, headers: {}
|
headers: {},
|
||||||
, useQuerystring: false
|
useQuerystring: false,
|
||||||
, followRedirect: true
|
followRedirect: true,
|
||||||
, followAllRedirects: false
|
followAllRedirects: false,
|
||||||
, followOriginalHttpMethod: false
|
followOriginalHttpMethod: false,
|
||||||
, maxRedirects: 10
|
maxRedirects: 10,
|
||||||
, removeRefererHeader: false
|
removeRefererHeader: false,
|
||||||
//, encoding: undefined
|
//, encoding: undefined
|
||||||
, gzip: false
|
gzip: false
|
||||||
//, body: undefined
|
//, body: undefined
|
||||||
//, json: undefined
|
//, json: undefined
|
||||||
};
|
};
|
||||||
module.exports = setDefaults(_defaults);
|
module.exports = setDefaults(_defaults);
|
||||||
|
|
||||||
module.exports._keys = Object.keys(_defaults).concat([
|
module.exports._keys = Object.keys(_defaults).concat([
|
||||||
'encoding'
|
'encoding',
|
||||||
, 'body'
|
'body',
|
||||||
, 'json'
|
'json',
|
||||||
, 'form'
|
'form',
|
||||||
, 'auth'
|
'auth',
|
||||||
, 'formData'
|
'formData',
|
||||||
, 'FormData'
|
'FormData'
|
||||||
]);
|
]);
|
||||||
module.exports.debug = (-1 !== (process.env.NODE_DEBUG||'').split(/\s+/g).indexOf('urequest'));
|
module.exports.debug =
|
||||||
|
-1 !== (process.env.NODE_DEBUG || '').split(/\s+/g).indexOf('urequest');
|
||||||
|
|
||||||
debug("DEBUG ON for urequest");
|
debug('DEBUG ON for urequest');
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var net = require('net');
|
var net = require('net');
|
||||||
var server = net.createServer(function (socket) {
|
var server = net.createServer(function(socket) {
|
||||||
socket.on('data', function (chunk) {
|
socket.on('data', function(chunk) {
|
||||||
console.info(chunk.toString('utf8'));
|
console.info(chunk.toString('utf8'));
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
server.listen(3007, function () {
|
server.listen(3007, function() {
|
||||||
console.info("Listening on", this.address());
|
console.info('Listening on', this.address());
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in New Issue