make Prettier

This commit is contained in:
AJ ONeal 2019-10-29 14:31:30 -06:00
parent b6900b937b
commit 9ab91d9721
12 changed files with 662 additions and 572 deletions

8
.prettierrc Normal file
View File

@ -0,0 +1,8 @@
{
"bracketSpacing": true,
"printWidth": 80,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "none",
"useTabs": false
}

View File

@ -30,10 +30,12 @@ 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
}); });
``` ```
@ -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'
} }
}); });
``` ```
@ -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"`.
--- ---

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

152
index.js
View File

@ -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]);
} }
}); });
@ -44,7 +47,6 @@ function hasHeader(reqOpts, header) {
} }
function toJSONifier(keys) { function toJSONifier(keys) {
return function() { return function() {
var obj = {}; var obj = {};
var me = this; var me = this;
@ -65,7 +67,7 @@ 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) {
@ -79,7 +81,12 @@ 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);
@ -87,7 +94,11 @@ function setDefaults(defs) {
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;
@ -149,7 +164,7 @@ function setDefaults(defs) {
} }
} }
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,13 +187,20 @@ 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) {
@ -192,8 +214,14 @@ function setDefaults(defs) {
// 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',
'host',
'localAddress',
'agent',
'createConnection',
'timeout',
'setHost'
].forEach(function(key) { ].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...
@ -226,9 +260,13 @@ function setDefaults(defs) {
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;
} }
@ -236,7 +274,10 @@ function setDefaults(defs) {
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])) {
@ -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 {
@ -279,7 +320,10 @@ function setDefaults(defs) {
// 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();
}); });
@ -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:
@ -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';
} }
} }
@ -390,7 +441,8 @@ function setDefaults(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(
function(method) {
urequest[method] = function(obj, cb) { urequest[method] = function(obj, cb) {
if ('string' === typeof obj) { if ('string' === typeof obj) {
obj = { url: obj }; obj = { url: obj };
@ -398,38 +450,40 @@ function setDefaults(defs) {
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');

View File

@ -5,7 +5,7 @@ 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());
}); });