chunk_response_parser.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ChunkResponseParser = void 0;
  4. const web3_errors_1 = require("web3-errors");
  5. class ChunkResponseParser {
  6. constructor(eventEmitter, autoReconnect) {
  7. this.eventEmitter = eventEmitter;
  8. this.autoReconnect = autoReconnect;
  9. }
  10. clearQueues() {
  11. if (typeof this._clearQueues === 'function') {
  12. this._clearQueues();
  13. }
  14. }
  15. onError(clearQueues) {
  16. this._clearQueues = clearQueues;
  17. }
  18. parseResponse(data) {
  19. const returnValues = [];
  20. // DE-CHUNKER
  21. const dechunkedData = data
  22. .replace(/\}[\n\r]?\{/g, '}|--|{') // }{
  23. .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{
  24. .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{
  25. .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{
  26. .split('|--|');
  27. dechunkedData.forEach(_chunkData => {
  28. // prepend the last chunk
  29. let chunkData = _chunkData;
  30. if (this.lastChunk) {
  31. chunkData = this.lastChunk + chunkData;
  32. }
  33. let result;
  34. try {
  35. result = JSON.parse(chunkData);
  36. }
  37. catch (e) {
  38. this.lastChunk = chunkData;
  39. // start timeout to cancel all requests
  40. if (this.lastChunkTimeout) {
  41. clearTimeout(this.lastChunkTimeout);
  42. }
  43. this.lastChunkTimeout = setTimeout(() => {
  44. if (this.autoReconnect)
  45. return;
  46. this.clearQueues();
  47. this.eventEmitter.emit('error', new web3_errors_1.InvalidResponseError({
  48. id: 1,
  49. jsonrpc: '2.0',
  50. error: { code: 2, message: 'Chunk timeout' },
  51. }));
  52. }, 1000 * 15);
  53. return;
  54. }
  55. // cancel timeout and set chunk to null
  56. clearTimeout(this.lastChunkTimeout);
  57. this.lastChunk = undefined;
  58. if (result)
  59. returnValues.push(result);
  60. });
  61. return returnValues;
  62. }
  63. }
  64. exports.ChunkResponseParser = ChunkResponseParser;
  65. //# sourceMappingURL=chunk_response_parser.js.map