We have a requirement where we want to build api calls based on query param array for (contentId[]=1&contentId[]=2....and so on ), and then make async calls appending id to the api end point e.g http://xxxx/content/contentId.
Based on the response we need to aggregate and wrap the content with fields contentId, responsecode that we receive when we hit the individual api endpoints
{
{ "contentd": "1",
"responsecode": 200,
"messsage": "",
content{
}
}
{ "contentd": "2",
"responsecode": 200,
"messsage": "",
content{
}
...
}
We are using promise to do the same. I used promise all as below.
Promise.all(req.query.contentId
.map(function (contentId) {
console.log('processing the content id'+contentId);
return getContent(contentId);
}))
.then(function (all_content) {
//convert each resolved promised into JSON and convert it into an array.
res.json(all_content.map(function (content) {
return JSON.parse(content)
}));
})
.catch(function(rej) {
//here when you reject the promise
console.log("404 received"+rej);
}) ;
} catch (e) {
res.send(e.message);
}
});
// this is the function that makes the call to the backend. Note usage of request promise
function getContent(contentId) {
console.log('content id received to fetch the content'+contentId);
var options = {
uri: 'http://xxxxx/api/content/'+contentId,
headers: {
'Authorization': 'Basic YWRtaW46YWRtaW4='
},
qs: {
_format: 'json'
}
};
return rp(options);
}
Problems -The problem we are facing is that for the calls when we get http status code as 200 the result comes fine. However, for http status code 404(not found) the processing is not done. It seems to fail fast.
Also, how do I insert own fields for response, status while processing the content response as above in JSON.parse. thanks