ibm-blockchain-js
Advanced tools
Comparing version 1.3.1 to 1.3.2
305
index.js
@@ -295,3 +295,3 @@ 'use strict'; | ||
var shim_regex = /github.com\/\S+\/shim/g; //find chaincode's shim version | ||
var shim_regex = /github.com\/\S+\/shim/g; //find chaincode's shim version | ||
var result = file.match(shim_regex); | ||
@@ -567,11 +567,12 @@ if(result[0]){ | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] Chain Stats - success'); | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] Chain Stats - failure:', statusCode, e); | ||
if(cb) cb(helper.eFmt('chain_stats() error', statusCode, e), null); | ||
}; | ||
rest.get(options, ''); | ||
rest.get(options, null, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] Chain Stats - failure:', statusCode, data); | ||
if(cb) cb(helper.eFmt('chain_stats() error', statusCode, data), null); | ||
} | ||
else{ | ||
logger.log('[ibc-js] Chain Stats - success'); | ||
if(cb) cb(null, data); | ||
} | ||
}); | ||
}; | ||
@@ -584,11 +585,13 @@ | ||
var options = {path: '/chain/blocks/' + id}; //i think block IDs start at 0, height starts at 1, fyi | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] Block Stats ', id , '- success'); | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] Block Stats ', id , '- failure:', statusCode); | ||
if(cb) cb(helper.eFmt('block_stats() error', statusCode, e), null); | ||
}; | ||
rest.get(options, ''); | ||
rest.get(options, null, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] Block Stats ', id , '- failure:', statusCode); | ||
if(cb) cb(helper.eFmt('block_stats() error', statusCode, data), null); | ||
} | ||
else{ | ||
logger.log('[ibc-js] Block Stats ', id , '- success'); | ||
if(cb) cb(null, data); | ||
} | ||
}); | ||
}; | ||
@@ -608,32 +611,34 @@ | ||
var options = { | ||
path: '/devops/query' | ||
var options = {path: '/chaincode'}; | ||
var body = { | ||
jsonrpc: '2.0', | ||
method: 'query', | ||
params: { | ||
type: 1, | ||
chaincodeID:{ | ||
name: ibc.chaincode.details.deployed_name | ||
}, | ||
ctorMsg: { | ||
function: 'query', | ||
args: args | ||
}, | ||
secureContext: enrollId | ||
}, | ||
id: Date.now() | ||
}; | ||
var body = { | ||
chaincodeSpec: { | ||
type: 'GOLANG', | ||
chaincodeID: { | ||
name: ibc.chaincode.details.deployed_name, | ||
}, | ||
ctorMsg: { | ||
function: 'query', | ||
args: args | ||
}, | ||
secureContext: enrollId | ||
} | ||
}; | ||
//logger.log('body', body); | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] (Read) - success:', data); | ||
if(cb){ | ||
if(data.error) cb(helper.eFmt('query() resp error', 400, data.error), null); | ||
else if(data.result) cb(null, data.result.message); | ||
else cb(null, data.OK); | ||
rest.post(options, null, body, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] (Read) - failure:', statusCode); | ||
if(cb) cb(helper.eFmt('read() error', statusCode, data), null); | ||
} | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] (Read) - failure:', statusCode); | ||
if(cb) cb(helper.eFmt('read() error', statusCode, e), null); | ||
}; | ||
rest.post(options, '', body); | ||
else{ | ||
logger.log('[ibc-js] (Read) - success:', data); | ||
if(cb){ | ||
if(data.error) cb(helper.eFmt('query() resp error', 400, data.error), null); | ||
else if(data.result) cb(null, data.result.message); | ||
else cb(null, data.OK); | ||
} | ||
} | ||
}); | ||
} | ||
@@ -661,19 +666,19 @@ | ||
}; | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] Registration success x' + attempt + ' :', enrollId); | ||
ibc.chaincode.details.peers[index].enrollId = enrollId; //remember a valid enrollId for this peer | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] Register - failure x' + attempt + ' :', enrollId, statusCode); | ||
if(attempt <= maxRetry){ //lets try again after a short delay, maybe the peer is still starting | ||
logger.log('[ibc-js] \tgoing to try to register again in 30 secs'); | ||
setTimeout(function(){register(index, enrollId, enrollSecret, maxRetry, ++attempt, cb);}, 30000); | ||
rest.post(options, null, body, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] Register - failure x' + attempt + ' :', enrollId, statusCode); | ||
if(attempt <= maxRetry){ //lets try again after a short delay, maybe the peer is still starting | ||
logger.log('[ibc-js] \tgoing to try to register again in 30 secs'); | ||
setTimeout(function(){register(index, enrollId, enrollSecret, maxRetry, ++attempt, cb);}, 30000); | ||
} | ||
else{ | ||
if(cb) cb(helper.eFmt('register() error', statusCode, data), null); //give up | ||
} | ||
} | ||
else{ | ||
if(cb) cb(helper.eFmt('register() error', statusCode, e), null); //give up | ||
else { | ||
logger.log('[ibc-js] Registration success x' + attempt + ' :', enrollId); | ||
ibc.chaincode.details.peers[index].enrollId = enrollId; //remember a valid enrollId for this peer | ||
if(cb) cb(null, data); | ||
} | ||
}; | ||
rest.post(options, '', body); | ||
}); | ||
} | ||
@@ -693,12 +698,13 @@ | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] Unregistering success:', enrollId); | ||
ibc.chaincode.details.peers[index].enrollId = null; //unremember a valid enrollId for this peer | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.log('[ibc-js] Unregistering - failure:', enrollId, statusCode); | ||
if(cb) cb(helper.eFmt('unregister() error', statusCode, e), null); | ||
}; | ||
rest.delete(options, ''); | ||
rest.delete(options, null, null, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.log('[ibc-js] Unregistering - failure:', enrollId, statusCode); | ||
if(cb) cb(helper.eFmt('unregister() error', statusCode, data), null); | ||
} | ||
else { | ||
logger.log('[ibc-js] Unregistering success:', enrollId); | ||
ibc.chaincode.details.peers[index].enrollId = null; //unremember a valid enrollId for this peer | ||
if(cb) cb(null, data); | ||
} | ||
}); | ||
}; | ||
@@ -718,11 +724,12 @@ | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] Check Register success:', enrollId); | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] Check Register - failure:', enrollId, statusCode); | ||
if(cb) cb(helper.eFmt('check_register() error', statusCode, e), null); | ||
}; | ||
rest.get(options, ''); | ||
rest.get(options, null, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] Check Register - failure:', enrollId, statusCode); | ||
if(cb) cb(helper.eFmt('check_register() error', statusCode, data), null); | ||
} | ||
else{ | ||
logger.log('[ibc-js] Check Register success:', enrollId); | ||
if(cb) cb(null, data); | ||
} | ||
}); | ||
}; | ||
@@ -765,43 +772,44 @@ | ||
// ---- Success ---- // | ||
options.success = function(statusCode, data){ | ||
if(data.result && ibc.chaincode.details.version.indexOf('hyperledger/fabric/core/chaincode/shim') >= 0){//hyperledger response | ||
ibc.chaincode.details.deployed_name = data.result.message; | ||
rest.post(options, null, body, function(statusCode, data){ | ||
// ---- Failure ---- /// | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] deploy - failure:', statusCode); | ||
if(cb) cb(helper.eFmt('deploy() error', statusCode, data), null); | ||
} | ||
else ibc.chaincode.details.deployed_name = data.message; //obc-peer response | ||
if(!ibc.chaincode.details.deployed_name || ibc.chaincode.details.deployed_name.length < 32){ | ||
ibc.chaincode.details.deployed_name = ''; //doesnt look right, let code below catch error | ||
} | ||
if(ibc.chaincode.details.deployed_name === ''){ | ||
logger.error('\n\n\t deploy resp error - there is no chaincode hash name in response:', data); | ||
if(cb) cb(helper.eFmt('deploy() error no cc name', 502, data), null); | ||
} | ||
// ---- Success ---- // | ||
else{ | ||
ibc.prototype.save(tempDirectory); //save it to known place so we remember the cc name | ||
if(deploy_options && deploy_options.save_path != null) { //save it to custom route | ||
ibc.prototype.save(deploy_options.save_path); | ||
if(data.result && ibc.chaincode.details.version.indexOf('hyperledger/fabric/core/chaincode/shim') >= 0){//hyperledger response | ||
ibc.chaincode.details.deployed_name = data.result.message; | ||
} | ||
else ibc.chaincode.details.deployed_name = data.message; //obc-peer response | ||
if(cb){ | ||
var wait_ms = 45000; //default wait after deploy, peer may still be starting | ||
if(deploy_options && deploy_options.delay_ms && Number(deploy_options.delay_ms)) wait_ms = deploy_options.delay_ms; | ||
logger.log('\n\n\t deploy success [waiting another', (wait_ms / 1000) ,'seconds]'); | ||
logger.log('\t', ibc.chaincode.details.deployed_name, '\n'); | ||
if(!ibc.chaincode.details.deployed_name || ibc.chaincode.details.deployed_name.length < 32){ | ||
ibc.chaincode.details.deployed_name = ''; //doesnt look right, let code below catch error | ||
} | ||
if(ibc.chaincode.details.deployed_name === ''){ | ||
logger.error('\n\n\t deploy resp error - there is no chaincode hash name in response:', data); | ||
if(cb) cb(helper.eFmt('deploy() error no cc name', 502, data), null); | ||
} | ||
else{ | ||
ibc.prototype.save(tempDirectory); //save it to known place so we remember the cc name | ||
if(deploy_options && deploy_options.save_path != null) { //save it to custom route | ||
ibc.prototype.save(deploy_options.save_path); | ||
} | ||
setTimeout(function(){ | ||
logger.log('[ibc-js] Deploy Chaincode - Complete'); | ||
cb(null, data); | ||
}, wait_ms); //wait extra long, not always ready yet | ||
if(cb){ | ||
var wait_ms = 45000; //default wait after deploy, peer may still be starting | ||
if(deploy_options && deploy_options.delay_ms && Number(deploy_options.delay_ms)) wait_ms = deploy_options.delay_ms; | ||
logger.log('\n\n\t deploy success [waiting another', (wait_ms / 1000) ,'seconds]'); | ||
logger.log('\t', ibc.chaincode.details.deployed_name, '\n'); | ||
setTimeout(function(){ | ||
logger.log('[ibc-js] Deploy Chaincode - Complete'); | ||
cb(null, data); | ||
}, wait_ms); //wait extra long, not always ready yet | ||
} | ||
} | ||
} | ||
}; | ||
// ---- Failure ---- /// | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] deploy - failure:', statusCode); | ||
if(cb) cb(helper.eFmt('deploy() error', statusCode, e), null); | ||
}; | ||
rest.post(options, '', body); | ||
}); | ||
} | ||
@@ -865,11 +873,12 @@ | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js] Get Transaction - success:', data); | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js] Get Transaction - failure:', statusCode); | ||
if(cb) cb(helper.eFmt('read() error', statusCode, e), null); | ||
}; | ||
rest.get(options, ''); | ||
rest.get(options, null, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js] Get Transaction - failure:', statusCode); | ||
if(cb) cb(helper.eFmt('read() error', statusCode, data), null); | ||
} | ||
else{ | ||
logger.log('[ibc-js] Get Transaction - success:', data); | ||
if(cb) cb(null, data); | ||
} | ||
}); | ||
}; | ||
@@ -916,12 +925,13 @@ | ||
}; | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js]', name, ' - success:', data); | ||
ibc.q.push(Date.now()); //new action, add it to queue | ||
if(cb) cb(null, data); | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js]', name, ' - failure:', statusCode, e); | ||
if(cb) cb(helper.eFmt('invoke() error', statusCode, e), null); | ||
}; | ||
rest.post(options, '', body); | ||
rest.post(options, null, body, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js]', name, ' - failure:', statusCode, data); | ||
if(cb) cb(helper.eFmt('invoke() error', statusCode, data), null); | ||
} | ||
else{ | ||
logger.log('[ibc-js]', name, ' - success:', data); | ||
ibc.q.push(Date.now()); //new action, add it to queue | ||
if(cb) cb(null, data); | ||
} | ||
}); | ||
}; | ||
@@ -970,18 +980,19 @@ } | ||
options.success = function(statusCode, data){ | ||
logger.log('[ibc-js]', name, ' - success:', data); | ||
if(cb){ | ||
if(data){ | ||
if(data.error) cb(helper.eFmt('query() resp error', 400, data.error), null); | ||
else if(data.result) cb(null, data.result.message); | ||
else cb(null, data.OK); | ||
rest.post(options, null, body, function(statusCode, data){ | ||
if(statusCode != null){ | ||
logger.error('[ibc-js]', name, ' - failure:', statusCode, data); | ||
if(cb) cb(helper.eFmt('query() error', statusCode, data), null); | ||
} | ||
else{ | ||
logger.log('[ibc-js]', name, ' - success:', data); | ||
if(cb){ | ||
if(data){ | ||
if(data.error) cb(helper.eFmt('query() resp error', 400, data.error), null); | ||
else if(data.result) cb(null, data.result.message); | ||
else cb(null, data.OK); | ||
} | ||
else cb(helper.eFmt('query() resp error', 502, data), null); //something is wrong, response is not what we expect | ||
} | ||
else cb(helper.eFmt('query() resp error', 502, data), null); //something is wrong, response is not what we expect | ||
} | ||
}; | ||
options.failure = function(statusCode, e){ | ||
logger.error('[ibc-js]', name, ' - failure:', statusCode, e); | ||
if(cb) cb(helper.eFmt('query() error', statusCode, e), null); | ||
}; | ||
rest.post(options, '', body); | ||
}); | ||
}; | ||
@@ -988,0 +999,0 @@ } |
208
lib/rest.js
@@ -12,4 +12,4 @@ 'use strict'; | ||
/* | ||
Version: 0.6.6 | ||
Updated: 8/05/2016 | ||
Version: 0.7.3 | ||
Updated: 11/03/2016 | ||
----------------------------------------------------------------- | ||
@@ -21,14 +21,9 @@ Use: var rest = require('./rest'); | ||
path: PATH HERE, | ||
headers: { | ||
"Content-Type": "application/json", | ||
"Accept": "application/json" | ||
} | ||
headers: {"Accept": "application/json"} | ||
}; | ||
options.success = function(statusCode, data){ | ||
logger.log("Get - success"); | ||
} | ||
options.failure = function(statusCode, e){ | ||
logger.log("Get - failure", e); | ||
} | ||
rest.get(options, {'user':'david'}); | ||
rest.get(options, null, function(errCode, response){ | ||
if(errCode != null) logger.log('Get - failure', errCode, response); | ||
else logger.log('Get - success', response); | ||
}); | ||
----------------------------------------------------------------- | ||
@@ -44,3 +39,4 @@ | ||
method: A string specifying the HTTP request method. Defaults to 'GET'. | ||
path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. | ||
path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'. | ||
An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. | ||
headers: An object containing request headers. | ||
@@ -53,3 +49,4 @@ auth: Basic authentication i.e. 'user:password' to compute an Authorization header. | ||
keepAlive: {Boolean} Keep sockets around in a pool to be used by other requests in the future. Default = false | ||
keepAliveMsecs: {Integer} When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. Only relevant if keepAlive is set to true. | ||
keepAliveMsecs: {Integer} When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. | ||
Default = 1000. Only relevant if keepAlive is set to true. | ||
@@ -59,7 +56,4 @@ Plus my "options" values: | ||
quiet: If true will not print to logger. Defaults false. | ||
ssl: Iff false will use http instead of https. Defaults true. | ||
tls: Iff false will use http instead of https. Defaults true. | ||
timeout: Integer in milliseconds to time out requests. Defaults 20,000 | ||
cb: Node.js call back style of cb(error_obj, response). | ||
success: jQuery call back style of success(statusCode, response) | ||
failure: jQuery call back style of failure(statusCode, response) | ||
include_headers: If true the response argument will be {"response":<response>, "headers":<headers>} | ||
@@ -70,5 +64,6 @@ */ | ||
var http_mod = require('http'); | ||
var querystring = require('querystring'); | ||
var default_options = { | ||
quiet: false, | ||
ssl: true, | ||
tls: true, | ||
timeout: 20000, | ||
@@ -92,6 +87,4 @@ include_headers: false | ||
if(a[i] === undefined) { | ||
//logger.log(' - copying'); | ||
a[i] = JSON.parse(JSON.stringify(b[i])); | ||
} | ||
//else logger.log(' - not copying'); | ||
} | ||
@@ -102,44 +95,38 @@ return a; | ||
//main http request builder/handler/thingy | ||
function http_req(options, parameters, body, attempt){ | ||
var acceptJson = false, jQuery = false, nodeJs = false, http, http_txt = '', goodJSON = false; | ||
function http_req(options, query_params, body, attempt, cb){ | ||
var acceptJson = false, http, http_txt = '', request = null, formatted_body = null; | ||
var ids = 'abcdefghijkmnopqrstuvwxyz'; | ||
var id = ids[Math.floor(Math.random() * ids.length)]; //random letter to help id calls when there are multiple rest calls | ||
var id = ids[Math.floor(Math.random() * ids.length)]; //random letter to help id calls when there are multiple rest calls | ||
var cb_fired = false; | ||
var request = null; | ||
if(!attempt || isNaN(attempt)) attempt = 1; //defaults to attempt # 1 | ||
if(!attempt || isNaN(attempt)) attempt = 1; //defaults to attempt # 1 | ||
options = mergeBtoA(default_options, options); | ||
//// Handle Call Back //// | ||
function success(statusCode, headers, resp){ //go to success callback | ||
if(cb_fired === false){ | ||
// ----- Handle Call Back ----- // | ||
function call_cb(ret){ | ||
if(cb_fired === false){ //only call cb once! | ||
cb_fired = true; | ||
if(options.include_headers) resp = {response:resp, headers: headers}; | ||
if(jQuery) return options.success(statusCode, resp); | ||
else if(nodeJs) return options.cb(null, resp); //if neither callback set, don't do either | ||
if(options.include_headers) ret.msg = {response:ret.msg, headers: ret.headers}; | ||
if(ret.code <= 399 && ret.code !== 302) ret.code = null; | ||
if(cb) cb(ret.code, ret.msg); //1st arg is error status code, null if no error code | ||
return; | ||
} | ||
} | ||
function failure(statusCode, headers, msg){ //go to failure callback | ||
if(cb_fired === false){ //prevent mutliple callbacks b/c of on error and on timeout | ||
cb_fired = true; | ||
if(options.include_headers) msg = {response:msg, headers: headers}; | ||
if(jQuery) return options.failure(statusCode, msg); | ||
else if(nodeJs) return options.cb(statusCode, msg); //if neither callback set, don't do either | ||
} | ||
// ---- Pick HTTP vs HTTPS ---- // | ||
if(options.ssl === false || options.tls === false) { | ||
http = http_mod; //if options.tls === false use http | ||
http_txt = '[http ' + options.method + ' - ' + id + ']'; | ||
} | ||
if(typeof(options.ssl) === 'undefined' || options.ssl) { //if options.ssl not found or true use https | ||
else{ //else use https | ||
http = https_mod; | ||
http_txt = '[https ' + options.method + ' - ' + id + ']'; | ||
} | ||
else { | ||
http = http_mod; //if options.ssl == false use http | ||
http_txt = '[http ' + options.method + ' - ' + id + ']'; | ||
} | ||
if(!options.quiet) logger.debug(http_txt + ' ' + options.host + ':' + options.port); | ||
if(!options.quiet) logger.debug(http_txt + ' ' + options.path); | ||
//// Sanitize Inputs //// | ||
var querystring = require('querystring'); //convert all header keys to lower-case for easier parsing | ||
for(var i in options.headers) { | ||
// ---- Sanitize Inputs ---- // | ||
if(!options.headers) options.headers = {}; | ||
for(var i in options.headers) { //convert all header keys to lower-case for easier parsing | ||
var temp = options.headers[i]; | ||
@@ -152,94 +139,99 @@ delete options.headers[i]; | ||
if(typeof body === 'object'){ | ||
if(options.headers) options.headers['content-type'] = 'application/json'; | ||
else options.headers = {'content-type': 'application/json'}; | ||
body = JSON.stringify(body); //stringify body | ||
if(typeof body === 'object' && body != null){ | ||
options.headers['content-type'] = 'application/json'; | ||
formatted_body = JSON.stringify(body); //stringify body | ||
} | ||
else formatted_body = body; | ||
if(options.headers && options.headers['accept'] && options.headers['accept'].toLowerCase().indexOf('json') >= 0) acceptJson = true; | ||
if(options.success && options.failure) jQuery = true; | ||
else if(options.cb) nodeJs = true; | ||
if(options.headers.accept && options.headers.accept.indexOf('json') >= 0) acceptJson = true; | ||
if(query_params && typeof query_params === 'object') options.path += '?' + querystring.stringify(query_params); | ||
if(body){ | ||
if(options.headers) options.headers['content-length'] = Buffer.byteLength(body); | ||
else options.headers = {'content-lenght': Buffer.byteLength(body)}; | ||
} | ||
else if(options.headers['content-length']) delete options.headers['content-length']; //we don't need you | ||
if(!options.quiet && options.method.toLowerCase() !== 'get') { | ||
logger.debug(' body:', body); | ||
} | ||
if(formatted_body) options.headers['content-length'] = Buffer.byteLength(formatted_body); | ||
else if(options.headers['content-length']) delete options.headers['content-length']; //we don't need you | ||
if(!options.quiet && options.method.toLowerCase() !== 'get') logger.debug(' body:', formatted_body); | ||
//// Handle Request //// | ||
if(typeof parameters == 'object') options.path += '?' + querystring.stringify(parameters); //should be a json object | ||
// --------- Handle Request --------- // | ||
request = http.request(options, function(resp) { | ||
var str = '', temp, chunks = 0; | ||
var str = '', chunks = 0; | ||
if(!options.quiet) logger.debug(http_txt + ' Status code: ' + resp.statusCode); | ||
resp.setEncoding('utf8'); | ||
resp.on('data', function(chunk) { //merge chunks of request | ||
resp.on('data', function(chunk) { //merge chunks of request | ||
str += chunk; | ||
chunks++; | ||
}); | ||
resp.on('end', function() { //wait for end before decision | ||
if(resp.statusCode == 204){ //empty response, don't parse body | ||
resp.on('end', function() { //wait for end before decision | ||
var ret = { | ||
code: resp.statusCode, | ||
headers: resp.headers, | ||
msg: str | ||
}; | ||
// --------- Process Response - Debug Msgs --------- // | ||
if(resp.statusCode == 204){ //empty response, don't parse body | ||
if(!options.quiet) logger.debug(http_txt + ' Data: No Content'); | ||
success(resp.statusCode, resp.headers, str); | ||
} | ||
else if(resp.statusCode >= 200 && resp.statusCode <= 399){ //check status codes | ||
else if(resp.statusCode === 302){ //redirect | ||
if(!options.quiet) logger.error(http_txt + ' Error - got a redirect, not what we want'); | ||
} | ||
else if(resp.statusCode >= 200 && resp.statusCode <= 399){ //valid status codes | ||
if(acceptJson){ | ||
try{ | ||
temp = JSON.parse(str); | ||
goodJSON = true; | ||
ret.msg = JSON.parse(str); //all good [json resp] | ||
} | ||
catch(e){ | ||
goodJSON = false; | ||
if(!options.quiet) logger.error(http_txt + ' Error - response is not JSON: ', str); | ||
failure(500, resp.headers, 'Invalid JSON response: ' + str); | ||
ret.code = 500; | ||
ret.msg = 'Invalid JSON response: ' + str; | ||
} | ||
if(goodJSON){ | ||
//if(!options.quiet) logger.debug(http_txt + ' Data:', str); //all good [json resp] | ||
success(resp.statusCode, resp.headers, temp); | ||
} | ||
} | ||
else { //all good [not json resp] | ||
else { //all good [not json resp] | ||
if(!options.quiet) logger.debug(http_txt + ' Data:', str); | ||
success(resp.statusCode, resp.headers, str); | ||
} | ||
} | ||
else { | ||
else { //invalid status codes | ||
if(!options.quiet) logger.error(http_txt + ' Error - status code: ' + resp.statusCode, str); | ||
if(acceptJson){ | ||
try{ | ||
str = JSON.parse(str); //attempt to parse error for JSON | ||
ret.msg = JSON.parse(str); //attempt to parse error for JSON | ||
} | ||
catch(e){} | ||
} | ||
failure(resp.statusCode, resp.headers, str); | ||
} | ||
// --------- Call CallBack --------- // | ||
return call_cb(ret); | ||
}); | ||
}); | ||
request.on('error', function(e) { //handle error event | ||
if(e.code === 'ECONNRESET' && attempt < 8) { //try ECONNRESET's again | ||
if(!options.quiet) logger.warn(http_txt + ' Warning - detected ECONNRESET, will try HTTP req again. attempt:' + attempt); | ||
// --------- Handle Request Errors --------- // | ||
request.on('error', function(e) { //handle error event | ||
if(e.code === 'ECONNRESET' && attempt <= 3) { //try ECONNRESETs again | ||
if(cb_fired === false){ | ||
logger.warn(http_txt + ' Warning - detected ECONNRESET, will try HTTP req again. attempt:' + attempt); | ||
attempt++; | ||
return setTimeout(function(){ http_req(options, parameters, body); }, 250 * Math.pow(2, attempt)); | ||
cb_fired = true; //set this just in case | ||
setTimeout(function(){ http_req(options, query_params, body, attempt, cb); }, 250 * Math.pow(2, attempt+1)); | ||
} | ||
return; | ||
} | ||
else { | ||
if(!options.quiet) logger.error(http_txt + ' Error - unknown issue with request: ', e); //catch failed request (failed DNS lookup and such) | ||
failure(500, null, e); | ||
if(!options.quiet) logger.error(http_txt + ' Error - unknown issue with request: ', e);//catch failed request (failed DNS lookup and such) | ||
return call_cb({code: 500, headers: null, msg: e}); | ||
} | ||
}); | ||
// --------- Handle Request Timeouts --------- // | ||
request.setTimeout(Number(options.timeout) || default_options.timeout); | ||
request.on('timeout', function(){ //handle time out events | ||
request.on('timeout', function(){ //handle time out events | ||
if(!options.quiet) logger.error(http_txt + ' Error - request timed out'); | ||
failure(408, null, 'Request timed out'); | ||
return call_cb({code: 408, headers: null, msg: 'Request timed out'}); | ||
}); | ||
if(body && body !== '' && !isEmpty(body)){ | ||
request.write(body); | ||
// ----- Body ----- // | ||
if(formatted_body && formatted_body !== '' && !isEmpty(formatted_body)){ | ||
request.write(formatted_body); | ||
} | ||
request.end(); //send the request | ||
request.end(); //send the request | ||
} | ||
@@ -260,29 +252,29 @@ | ||
//http post | ||
module.exports.post = function (l_options, parameters, body){ | ||
module.exports.post = function (l_options, query_params, body, cb){ | ||
l_options.method = 'POST'; | ||
http_req(l_options, parameters, body); | ||
http_req(l_options, query_params, body, 1 , cb); | ||
}; | ||
//http put | ||
module.exports.put = function (l_options, parameters, body){ | ||
module.exports.put = function (l_options, query_params, body, cb){ | ||
l_options.method = 'PUT'; | ||
http_req(l_options, parameters, body); | ||
http_req(l_options, query_params, body, 1 , cb); | ||
}; | ||
//http delete | ||
module.exports.delete = function (l_options, parameters, body){ | ||
module.exports.delete = function (l_options, query_params, body, cb){ | ||
l_options.method = 'DELETE'; | ||
http_req(l_options, parameters, body); | ||
http_req(l_options, query_params, body, 1 , cb); | ||
}; | ||
//http get | ||
module.exports.get = function (l_options, parameters){ | ||
module.exports.get = function (l_options, query_params, cb){ | ||
l_options.method = 'GET'; | ||
http_req(l_options, parameters, ''); | ||
http_req(l_options, query_params, null, 1 , cb); | ||
}; | ||
//http head | ||
module.exports.head = function (l_options, parameters){ | ||
module.exports.head = function (l_options, query_params, cb){ | ||
l_options.method = 'HEAD'; | ||
http_req(l_options, parameters, ''); | ||
http_req(l_options, query_params, null, 1 , cb); | ||
}; |
{ | ||
"name": "ibm-blockchain-js", | ||
"version": "1.3.1", | ||
"version": "1.3.2", | ||
"description": "A library for easily interacting with IBM Blockchain.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
90191
1376