batch.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. This file is part of web3.js.
  3. web3.js is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. web3.js is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @file batch.js
  16. * @author Marek Kotewicz <marek@ethdev.com>
  17. * @date 2015
  18. */
  19. "use strict";
  20. var Jsonrpc = require('./jsonrpc');
  21. var errors = require('web3-core-helpers').errors;
  22. var Batch = function (requestManager) {
  23. this.requestManager = requestManager;
  24. this.requests = [];
  25. };
  26. /**
  27. * Should be called to add create new request to batch request
  28. *
  29. * @method add
  30. * @param {Object} jsonrpc requet object
  31. */
  32. Batch.prototype.add = function (request) {
  33. this.requests.push(request);
  34. };
  35. /**
  36. * Should be called to execute batch request
  37. *
  38. * @method execute
  39. */
  40. Batch.prototype.execute = function () {
  41. var requests = this.requests;
  42. var sortResponses = this._sortResponses.bind(this);
  43. this.requestManager.sendBatch(requests, function (err, results) {
  44. results = sortResponses(results);
  45. requests.map(function (request, index) {
  46. return results[index] || {};
  47. }).forEach(function (result, index) {
  48. if (requests[index].callback) {
  49. if (result && result.error) {
  50. return requests[index].callback(errors.ErrorResponse(result));
  51. }
  52. if (!Jsonrpc.isValidResponse(result)) {
  53. return requests[index].callback(errors.InvalidResponse(result));
  54. }
  55. try {
  56. requests[index].callback(null, requests[index].format ? requests[index].format(result.result) : result.result);
  57. }
  58. catch (err) {
  59. requests[index].callback(err);
  60. }
  61. }
  62. });
  63. });
  64. };
  65. // Sort responses
  66. Batch.prototype._sortResponses = function (responses) {
  67. return (responses || []).sort((a, b) => a.id - b.id);
  68. };
  69. module.exports = Batch;