0

I am trying to call a GET API under three different configurations for region parameter, and combine the results into a single result object which I want the API to return as a JSON.

Here is my approach, which uses an array of Promises.

app.get("/api/v2/leagues/games", (req, res) => {
  const regions = ['uk', 'us', 'au'];
  let result = {};

  let promiseArray = regions.map(region => {
    return new Promise((resolve, reject) => {
      const uri = `https://api.the-odds-api.com/v3/odds/?apiKey=${functions.config().theoddsapi.key}&sport=${req.query.league}&region=${region}&mkt=${req.query.mkt}`;
      console.log(uri);
      request.get(uri, (error, response, body) => {
        if (body) {
          result[region] = JSON.parse(body).data;
          resolve(body);
        }
        else {
          console.error("error:", error); 
          console.log("statusCode:", response && response.statusCode); 
          reject(error);
        }
      });
    });
  });

  Promise.all(promiseArray).then(() => {
    return res.json(result)
  }).catch(() => response.errorCode);
});
});
isaacsultan
  • 3,784
  • 3
  • 16
  • 29

1 Answers1

0

The approach you are using it correct, however you have made a little mistake.

Though I have not tested it but the following code should do what you want it to do.

app.get("/api/v1/leagues/games", (req, res) => {
const promiseRequest = (sport, region, mkt) => {
return new Promise(resolve => {
    const theOddsApiUrl = `https://api.the-odds-api.com/v3/odds/?apiKey=${functions.config().theoddsapi.key}&sport=${sport}&region=${region}&mkt=${mkt}`; 
    request.get(theOddsApiUrl, (error, response, body) => {
    if (body) {
        resolve(body)
    }
    });
})
}
var sport = req.query.sport;
var mkt = req.query.mkt;

let allRegionsOdds = {};
Promise.all([
    promiseRequest(sport, 'uk', mkt),
    promiseRequest(sport, 'us', mkt),
    promiseRequest(sport, 'au', mkt)
]).then(body => {
    var response = allRegionsOdds[region] = body; // you can deide if this assignment is necessary or not for you
    res.json(response); // You want to return the response for the main Get after all the promises have been fulfilled.
}).catch(); // You can handle special cases in the catch, forexample when some promises fail.


//if you return the json at the end of function, your Promise.all hasn't gotten the time to be complete yet 
//and hence the variable response is still empty

//res.json(response);  

});
KillerX
  • 1,436
  • 1
  • 15
  • 23
Ahsun Ali
  • 314
  • 1
  • 6