Jon Cursi
Jon Cursi

Reputation: 3371

Meteor - How to Retry Failed HTTP Request without Losing Context?

In my Meteor 1.0 app, I'm running a batch of server-side HTTP requests in order to retrieve fixture data in a synchronous fashion. Once a request completes and computations are run on that data, startNumber is incremented (by 5000) and the request is re-run with that new value. This loop system will continue until the API returns a blank response array, signifying all the data has been captured. This HTTP request is part of a larger, complex function that helps set the context of the request.

functionName = function(param1,param2,param3) {
  // ...
  // ...
  var startNumber = 1;
  do {
    var request = Meteor.http.call("GET", "https://url-to-api-endpoint",
      { params:
        {
          "since": startNumber
        },
        timeout: 60000
      }
    );
    if(request.statusCode === 200) {
      var response = request.data;
      // perform calculations on the response
      startNumber+=5000;
    }
  } (while response.length>0);
  // ...
  // ...
};

The do-while loop system is working fine, except that every few iterations the request is returning with Error: getaddrinfo ENOTFOUND. The URL is perfectly valid, and it appears these errors are resulting from a finicky/unreliable API as sometimes the same exact request will go through or error out. I want to replay failed requests in order to make sure my app is retrieving data chronologically before proceeding.

How can I replay a failed HTTP request as though it were being run for the first time? In other words, without losing the current context of all the variables, etc., in functionName?

Upvotes: 1

Views: 588

Answers (1)

Jon Cursi
Jon Cursi

Reputation: 3371

FYI, incase someone else ends up in this predicament, I solved this problem by wrapping the HTTP request in a try-catch block. In the case of an error such as getaddrinfo ENOTFOUND or ETIMEDOUT, the error gets caught. Within the catch block, I call the functionName and pass in parameters for the current state (i.e. the current startNumber) - this allows me to essentially "replay" the request all over again.

// ...
// ...
try {
    var request = Meteor.http.call("GET", "https://url-to-api-endpoint",
      { params:
        {
          "since": startNumber
        },
        timeout: 60000
      }
    );
} catch(err) {
    console.log(err + '\nFailed...retrying');
    functionName(param1,param2,param3);
}
// ...
// ...

Upvotes: 1

Related Questions