Friday, 17 March 2017

Breaking up nested Node.js Request calls

I am working on adding proper error handling to all the Request calls in my Node.JS app. Utilizing Request-Promise, I've been able to go through and do this without issue, but there's one function that had nested requests, seen here:

function getLead(req, res) {
  console.log('GET Lead');
  let endpoint = 'http://example.com/endpoint';
  request(endpoint, (err, response, body) => {
     let post = JSON.parse(body)[0];
     let postId = post.ID;
     let getFullPost = 'http://example.com/endpoint2=' + postId;
     request(getFullPost, (err, response, body) => {
        let fullPost = JSON.parse(body);
        console.log(fullPost);
        res.send(fullPost);
    })
  })
}

In our CMS a user can add an article to a "Zone", which allows us to control article order and highlight specific articles in parts of the site. I can make a GET request to this Zone endpoint, but it doesn't return the full article object that I need, requiring me to grab the ID of the article and make another call to the article endpoint using the ID to get the full article object.

I know nested requests are typically a no-no and can lead to many problems, so I've tried to break up the above function a bit while using the new Request-Promise. Here's the refactored function, although I feel it could potentially be DRY-er:

function getLead(req, res) {
  console.log('GET Lead');
  let getZonePost = 'http://example.com/endpoint';

  rp({
     uri: getZonePost
  }).then((data) => {
     return JSON.parse(data)[0];
  }).then((post) => {
     getFullPost(post.ID);
  }).catch((err) => {
     handleError("getLatest Error: ", err, req, res);
  });

  let getFullPost = function(postId) {
    let getPost = 'http://example.com/endpoint2=' + postId;
    rp({
       uri: getPost
    }).then((data) => {
       return JSON.parse(data);
    }).then((fullPost) => {
       res.send(fullPost);
    }).catch((err) => {
       handleError("getLeadStory Error: ", err, req, res);
    });
  }
}

I'm our sole in-house developer, I'm looking for someone to either confirm that this is a solution or point out flaws/ways it could be refactored further. Thanks for reading!



via cortharlow

No comments:

Post a Comment