fixed batch requests, error reporting and made batch requests for async properties working

This commit is contained in:
Fabian Vogelsteller 2015-07-15 17:12:11 +02:00
parent 203a83f074
commit c776c8b61e
2 changed files with 43 additions and 4 deletions

View File

@ -21,6 +21,8 @@
*/
var RequestManager = require('./requestmanager');
var Jsonrpc = require('./jsonrpc');
var errors = require('./errors');
var Batch = function () {
this.requests = [];
@ -47,11 +49,14 @@ Batch.prototype.execute = function () {
results = results || [];
requests.map(function (request, index) {
return results[index] || {};
}).map(function (result, index) {
return requests[index].format ? requests[index].format(result.result) : result.result;
}).forEach(function (result, index) {
if (requests[index].callback) {
requests[index].callback(err, result);
if (!Jsonrpc.getInstance().isValidResponse(result)) {
requests[index].callback(errors.InvalidResponse(result));
}
requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result));
}
});
});

View File

@ -22,6 +22,7 @@
*/
var RequestManager = require('./requestmanager');
var utils = require('../utils/utils');
var Property = function (options) {
this.name = options.name;
@ -53,6 +54,19 @@ Property.prototype.formatOutput = function (result) {
return this.outputFormatter && result !== null ? this.outputFormatter(result) : result;
};
/**
* Should be used to extract callback from array of arguments. Modifies input param
*
* @method extractCallback
* @param {Array} arguments
* @return {Function|Null} callback, if exists
*/
Property.prototype.extractCallback = function (args) {
if (utils.isFunction(args[args.length - 1])) {
return args.pop(); // modify the args array!
}
};
/**
* Should attach function to method
*
@ -79,7 +93,10 @@ Property.prototype.attachToObject = function (obj) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
};
obj[toAsyncName('get', name)] = this.getAsync.bind(this);
var func = this.getAsync.bind(this);
func.request = this.request.bind(this);
obj[toAsyncName('get', name)] = func;
};
/**
@ -112,5 +129,22 @@ Property.prototype.getAsync = function (callback) {
});
};
/**
* Should be called to create pure JSONRPC request which can be used in batch request
*
* @method request
* @param {...} params
* @return {Object} jsonrpc request
*/
Property.prototype.request = function () {
var payload = {
method: this.getter,
params: [],
callback: this.extractCallback(Array.prototype.slice.call(arguments))
};
payload.format = this.formatOutput.bind(this);
return payload;
};
module.exports = Property;