0

I am accessing an API that streams (RFC2616 for HTTP/1.1) the response. The stream never ends, but from time to time it throughs an error requiring the program to restart the request. I can't figure out how in NodeJS to restart the request without restarting the program. I've tried loops to check if an error occurred, but I end up creating a blocking code that stops the request methods. The code below works until an error occurs.

const request = require('request');

const options = {
  method: 'GET',
  url: 'https://api.tradestation.com/v3/marketdata/stream/quotes/IWM',
  headers: {Authorization: 'Bearer ' + api.token,},
};

request(options)
  .on('data', function (data) {
    console.log(data.toString());
    //Process data here
  })
  .on('error', function (err) {
    console.error(err);
  });

If it helps, the documentation to the API for streaming is here, and the API call is here.

On a side note, I tried using Axios but it doesn't seem to like endless streams (tried onDownloadProgress).

YT_Xaos
  • 335
  • 4
  • 19
Scott Taylor
  • 25
  • 1
  • 7

1 Answers1

0

I would stick your request inside a function, you can then call it again on error.. I would also put a slight delay on the retry..

eg.

function callAPI() {
  request(options)
    .on('data', function (data) {
      console.log(data.toString());
      //Process data here
    })
    .on('error', function (err) {
      console.error(err);
      setTimeout(callAPI, 1000); //wait a second and retry.
    });
}
Keith
  • 22,005
  • 2
  • 27
  • 44
  • That sort of works. The problem now is that when the error is resolved, two requests are running. If I remove the `setTimeout(callAPI, 1000);` line, the program exists without retrying. I added `setInterval(() => {}, 1 << 30);` to keep the program from exiting, but then the API isn't restarting. Adding back in the `setTimeout(callAPI, 1000);`, I'm back to having two "requests" running. – Scott Taylor Dec 12 '21 at 19:19