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

@ -16,7 +16,7 @@ npm install --save @root/request
```js
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('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.
@ -30,12 +30,14 @@ 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
});
});
```
## Table of contents
@ -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'
}
});
```
@ -177,7 +190,7 @@ var username = 'username',
password = 'password',
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
});
```
@ -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'}
})
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'}
})
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

@ -2,7 +2,7 @@
//var request = require('urequest');
var request = require('../');
request('https://www.google.com', function (error, response, body) {
request('https://www.google.com', function(error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
return;

View File

@ -2,7 +2,7 @@
//var request = require('urequest');
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('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.

View File

@ -2,7 +2,7 @@
//var request = require('urequest');
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('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.

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;

202
index.js
View File

@ -11,7 +11,7 @@ function debug() {
}
function mergeOrDelete(defaults, updates) {
Object.keys(defaults).forEach(function (key) {
Object.keys(defaults).forEach(function(key) {
if (!(key in updates)) {
updates[key] = defaults[key];
return;
@ -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]);
}
});
@ -32,7 +35,7 @@ function mergeOrDelete(defaults, updates) {
// retrieves an existing header, case-sensitive
function getHeaderName(reqOpts, header) {
var headerNames = {};
Object.keys(reqOpts.headers).forEach(function (casedName) {
Object.keys(reqOpts.headers).forEach(function(casedName) {
headerNames[casedName.toLowerCase()] = casedName;
});
// returns the key, which in erroneous cases could be an empty string
@ -44,12 +47,11 @@ function hasHeader(reqOpts, header) {
}
function toJSONifier(keys) {
return function () {
return function() {
var obj = {};
var me = this;
keys.forEach(function (key) {
keys.forEach(function(key) {
if (me[key] && 'function' === typeof me[key].toJSON) {
obj[key] = me[key].toJSON();
} else {
@ -65,13 +67,13 @@ function setDefaults(defs) {
defs = defs || {};
function urequestHelper(opts, cb) {
debug("\n[urequest] processed options:");
debug('\n[urequest] processed options:');
debug(opts);
function onResponse(resp) {
var followRedirect;
Object.keys(defs).forEach(function (key) {
Object.keys(defs).forEach(function(key) {
if (key in opts && 'undefined' !== typeof opts[key]) {
return;
}
@ -79,15 +81,24 @@ 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);
//resp.request.method = opts.method;
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);
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;
@ -122,7 +137,7 @@ function setDefaults(defs) {
resp.body = '';
}
resp._bodyLength = 0;
resp.on('data', function (chunk) {
resp.on('data', function(chunk) {
if ('string' === typeof resp.body) {
resp.body += chunk.toString(opts.encoding);
} else {
@ -130,7 +145,7 @@ function setDefaults(defs) {
resp._bodyLength += chunk.length;
}
});
resp.on('end', function () {
resp.on('end', function() {
if ('string' !== typeof resp.body) {
if (1 === resp._body.length) {
resp.body = resp._body[0];
@ -144,12 +159,12 @@ function setDefaults(defs) {
// but request.js doesn't do that.
try {
resp.body = JSON.parse(resp.body);
} catch(e) {
} catch (e) {
// ignore
}
}
debug("\n[urequest] resp.toJSON():");
debug('\n[urequest] resp.toJSON():');
debug(resp.toJSON());
cb(null, resp, resp.body);
});
@ -172,29 +187,42 @@ 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) {
_body = Buffer.from(_body);
}
Object.keys(opts.uri).forEach(function (key) {
Object.keys(opts.uri).forEach(function(key) {
finalOpts[key] = opts.uri[key];
});
// 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'
].forEach(function (key) {
[
'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...
@ -225,34 +259,41 @@ function setDefaults(defs) {
try {
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");
} 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');
cb(e);
return;
}
try {
form = new MyFormData();
Object.keys(opts.formData).forEach(function (key) {
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])) {
opts.formData[key].forEach(function (data) {
opts.formData[key].forEach(function(data) {
add(key, data);
});
} else {
add(key, opts.formData[key]);
}
});
} catch(e) {
} catch (e) {
cb(e);
return;
}
formHeaders = form.getHeaders();
Object.keys(formHeaders).forEach(function (header) {
Object.keys(formHeaders).forEach(function(header) {
finalOpts.headers[header] = formHeaders[header];
});
}
@ -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 {
@ -278,8 +319,11 @@ function setDefaults(defs) {
debug(formHeaders);
// 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; }
req = form.submit(finalOpts, function(err, resp) {
if (err) {
cb(err);
return;
}
onResponse(resp);
resp.resume();
});
@ -307,14 +351,14 @@ function setDefaults(defs) {
function parseUrl(str) {
var obj = url.parse(str);
var paths;
if ('unix' !== (obj.hostname||obj.host||'').toLowerCase()) {
if ('unix' !== (obj.hostname || obj.host || '').toLowerCase()) {
return obj;
}
obj.href = null;
obj.hostname = obj.host = null;
paths = (obj.pathname||obj.path||'').split(':');
paths = (obj.pathname || obj.path || '').split(':');
obj.socketPath = paths.shift();
obj.pathname = obj.path = paths.join(':');
@ -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:
@ -335,7 +379,7 @@ function setDefaults(defs) {
opts = { url: opts };
}
module.exports._keys.forEach(function (key) {
module.exports._keys.forEach(function(key) {
if (key in opts && 'undefined' !== typeof opts[key]) {
reqOpts[key] = opts[key];
} 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
// 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';
}
}
@ -386,50 +437,53 @@ function setDefaults(defs) {
return urequestHelper(reqOpts, cb);
}
urequest.defaults = function (_defs) {
urequest.defaults = function(_defs) {
_defs = mergeOrDelete(defs, _defs);
return setDefaults(_defs);
};
[ 'get', 'put', 'post', 'patch', 'delete', 'head', 'options' ].forEach(function (method) {
urequest[method] = function (obj, cb) {
['get', 'put', 'post', 'patch', 'delete', 'head', 'options'].forEach(
function(method) {
urequest[method] = function(obj, cb) {
if ('string' === typeof obj) {
obj = { url: obj };
}
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
//, encoding: undefined
, gzip: false
//, body: undefined
//, json: undefined
sendImmediately: true,
method: 'GET',
headers: {},
useQuerystring: false,
followRedirect: true,
followAllRedirects: false,
followOriginalHttpMethod: false,
maxRedirects: 10,
removeRefererHeader: false,
//, encoding: undefined
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

@ -1,11 +1,11 @@
'use strict';
var net = require('net');
var server = net.createServer(function (socket) {
socket.on('data', function (chunk) {
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());
});