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');
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('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
});
```
@ -49,6 +51,7 @@ request('http://www.google.com').then(function (response) {
## Forms
`urequest` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads.
<!-- For `multipart/related` refer to the `multipart` API. -->
#### 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.
```js
request.post('http://service.com/upload', {form:{key:'value'}})
request.post('http://service.com/upload', { form: { key: 'value' } });
// 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
request.post('http://service.com/upload').form({key:'value'})
-->
#### 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.
@ -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) {
return console.error('upload failed:', err);
}
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.)
@ -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');
// or
-->
```js
request.get('http://some.server.com/', {
'auth': {
'user': 'username',
'pass': 'password',
'sendImmediately': false
auth: {
user: 'username',
pass: 'password',
sendImmediately: false
}
});
// or
request.get('http://some.server.com/', {
'auth': {
'bearer': 'bearerToken'
auth: {
bearer: 'bearerToken'
}
});
```
@ -218,8 +231,8 @@ var options = {
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
console.log(info.stargazers_count + ' Stars');
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:
```js
/* Pattern */ 'http://unix:SOCKET:PATH'
/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
/* Pattern */ 'http://unix:SOCKET: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.
@ -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.
For example:
```js
//requests using baseRequest() will set the 'x-token' header
var baseRequest = request.defaults({
headers: { 'x-token': 'my-token' }
})
});
//requests using specialRequest() will include the 'x-token' header set in
//baseRequest and will also include the 'special' header
var specialRequest = baseRequest.defaults({
headers: { special: 'special value' }
})
});
```
### request.METHOD()
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.post()*: Defaults to `method: "POST"`.
- *request.put()*: Defaults to `method: "PUT"`.
- *request.patch()*: Defaults to `method: "PATCH"`.
- *request.del() / request.delete()*: Defaults to `method: "DELETE"`.
- *request.head()*: Defaults to `method: "HEAD"`.
- *request.options()*: Defaults to `method: "OPTIONS"`.
- _request.get()_: Defaults to `method: "GET"`.
- _request.post()_: Defaults to `method: "POST"`.
- _request.put()_: Defaults to `method: "PUT"`.
- _request.patch()_: Defaults to `method: "PATCH"`.
- _request.del() / request.delete()_: Defaults to `method: "DELETE"`.
- _request.head()_: Defaults to `method: "HEAD"`.
- _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
//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) {
console.log('error:', error); // Print the error if one occurred
return;

View File

@ -9,15 +9,18 @@ var request = require('../');
//request('http://www.github.com', function (error, response, body) {
request(
//{ url: 'http://postb.in/syfxxnko'
{ url: 'http://localhost:3007/form-data/'
, method: 'POST'
, headers: { 'X-Foo': 'Bar' }
, formData: {
foo: 'bar'
, baz: require('fs').createReadStream(require('path').join(__dirname, 'get-to-json.js'))
{
url: 'http://localhost:3007/form-data/',
method: 'POST',
headers: { 'X-Foo': 'Bar' },
formData: {
foo: 'bar',
baz: require('fs').createReadStream(
require('path').join(__dirname, 'get-to-json.js')
)
}
}
, function (error, response, body) {
},
function(error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
return;

View File

@ -4,7 +4,11 @@
var request = require('../');
// 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) {
console.log('error:', error); // Print the error if one occurred
return;

View File

@ -8,12 +8,13 @@ var request = require('../');
// will redirect to https://www.github.com and then https://github.com
//request('http://www.github.com', function (error, response, body) {
request(
{ url: 'http://postb.in/2meyt50C'
, method: 'POST'
, headers: { 'X-Foo': 'Bar' }
, form: { foo: 'bar', baz: 'qux' }
}
, function (error, response, body) {
{
url: 'http://postb.in/2meyt50C',
method: 'POST',
headers: { 'X-Foo': 'Bar' },
form: { foo: 'bar', baz: 'qux' }
},
function(error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
return;

152
index.js
View File

@ -21,7 +21,10 @@ function mergeOrDelete(defaults, updates) {
// CRDT probs...
if ('undefined' === typeof 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]);
}
});
@ -44,7 +47,6 @@ function hasHeader(reqOpts, header) {
}
function toJSONifier(keys) {
return function() {
var obj = {};
var me = this;
@ -65,7 +67,7 @@ function setDefaults(defs) {
defs = defs || {};
function urequestHelper(opts, cb) {
debug("\n[urequest] processed options:");
debug('\n[urequest] processed options:');
debug(opts);
function onResponse(resp) {
@ -79,7 +81,12 @@ function setDefaults(defs) {
});
followRedirect = opts.followRedirect;
resp.toJSON = toJSONifier([ 'statusCode', 'body', 'headers', 'request' ]);
resp.toJSON = toJSONifier([
'statusCode',
'body',
'headers',
'request'
]);
resp.request = req;
resp.request.uri = url.parse(opts.url);
@ -87,7 +94,11 @@ function setDefaults(defs) {
resp.request.headers = finalOpts.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);
if ('GET' !== opts.method && !opts.followAllRedirects) {
followRedirect = false;
@ -104,8 +115,12 @@ function setDefaults(defs) {
if (!opts.followOriginalHttpMethod) {
opts.method = 'GET';
opts.body = null;
delete opts.headers[getHeaderName(opts, 'Content-Length')];
delete opts.headers[getHeaderName(opts, 'Transfer-Encoding')];
delete opts.headers[
getHeaderName(opts, 'Content-Length')
];
delete opts.headers[
getHeaderName(opts, 'Transfer-Encoding')
];
}
if (opts.removeRefererHeader && opts.headers) {
delete opts.headers.referer;
@ -149,7 +164,7 @@ function setDefaults(defs) {
}
}
debug("\n[urequest] resp.toJSON():");
debug('\n[urequest] resp.toJSON():');
debug(resp.toJSON());
cb(null, resp, resp.body);
});
@ -172,13 +187,20 @@ function setDefaults(defs) {
} else if (opts.json && true !== opts.json) {
_body = JSON.stringify(opts.json);
} 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]) {
return true;
}
}).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(String(opts.form[key]));
}).join('&');
})
.map(function(key) {
return (
encodeURIComponent(key) +
'=' +
encodeURIComponent(String(opts.form[key]))
);
})
.join('&');
opts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
if ('string' === typeof _body) {
@ -192,8 +214,14 @@ function setDefaults(defs) {
// A bug should be raised if request does it differently,
// but I think we're supposed to pass all acceptable options
// on to the raw http request
[ 'family', 'host', 'localAddress', 'agent', 'createConnection'
, 'timeout', 'setHost'
[
'family',
'host',
'localAddress',
'agent',
'createConnection',
'timeout',
'setHost'
].forEach(function(key) {
finalOpts[key] = opts.uri[key];
});
@ -203,18 +231,24 @@ function setDefaults(defs) {
if (_body) {
// 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
finalOpts.headers['Content-Length'] = _body.byteLength || _body.length;
finalOpts.headers['Content-Length'] =
_body.byteLength || _body.length;
}
if (opts.auth) {
// if opts.uri specifies auth it will be parsed by url.parse and passed directly to the http module
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) {
finalOpts.auth = opts.auth;
}
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) {
// 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');
// potential options https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15
} catch (e) {
console.error("urequest does not include extra dependencies by default");
console.error("if you need to use 'form-data' you may install it, like so:");
console.error(" npm install --save form-data");
console.error(
'urequest does not include extra dependencies by default'
);
console.error(
"if you need to use 'form-data' you may install it, like so:"
);
console.error(' npm install --save form-data');
cb(e);
return;
}
@ -236,7 +274,10 @@ function setDefaults(defs) {
form = new MyFormData();
Object.keys(opts.formData).forEach(function(key) {
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);
}
if (Array.isArray(opts.formData[key])) {
@ -260,12 +301,12 @@ function setDefaults(defs) {
// TODO support unix sockets
if ('https:' === finalOpts.protocol) {
// 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);
requester = https;
} else if ('http:' === finalOpts.protocol) {
// 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);
requester = http;
} else {
@ -279,7 +320,10 @@ function setDefaults(defs) {
// 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.
req = form.submit(finalOpts, function(err, resp) {
if (err) { cb(err); return; }
if (err) {
cb(err);
return;
}
onResponse(resp);
resp.resume();
});
@ -323,7 +367,7 @@ function setDefaults(defs) {
}
function urequest(opts, cb) {
debug("\n[urequest] received options:");
debug('\n[urequest] received options:');
debug(opts);
var reqOpts = {};
// 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
// need to check and probably eliminate it
reqOpts.method = (reqOpts.method || 'POST').toUpperCase();
@ -377,8 +426,10 @@ function setDefaults(defs) {
// crazy case for easier testing
if (!hasHeader(reqOpts, 'CoNTeNT-TyPe')) {
if ((true === reqOpts.json && reqOpts.body)
|| (true !== reqOpts.json && reqOpts.json)) {
if (
(true === reqOpts.json && reqOpts.body) ||
(true !== reqOpts.json && reqOpts.json)
) {
reqOpts.headers['Content-Type'] = 'application/json';
}
}
@ -390,7 +441,8 @@ function setDefaults(defs) {
_defs = mergeOrDelete(defs, _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) {
if ('string' === typeof obj) {
obj = { url: obj };
@ -398,38 +450,40 @@ function setDefaults(defs) {
obj.method = method.toUpperCase();
urequest(obj, cb);
};
});
}
);
urequest.del = urequest.delete;
return urequest;
}
var _defaults = {
sendImmediately: true
, method: 'GET'
, headers: {}
, useQuerystring: false
, followRedirect: true
, followAllRedirects: false
, followOriginalHttpMethod: false
, maxRedirects: 10
, removeRefererHeader: false
sendImmediately: true,
method: 'GET',
headers: {},
useQuerystring: false,
followRedirect: true,
followAllRedirects: false,
followOriginalHttpMethod: false,
maxRedirects: 10,
removeRefererHeader: false,
//, encoding: undefined
, gzip: false
gzip: false
//, body: undefined
//, json: undefined
};
module.exports = setDefaults(_defaults);
module.exports._keys = Object.keys(_defaults).concat([
'encoding'
, 'body'
, 'json'
, 'form'
, 'auth'
, 'formData'
, 'FormData'
'encoding',
'body',
'json',
'form',
'auth',
'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) {
console.info(chunk.toString('utf8'));
});
})
server.listen(3007, function () {
console.info("Listening on", this.address());
});
server.listen(3007, function() {
console.info('Listening on', this.address());
});