Reputation: 205
I need to abstract a set of REST APIs in to one simple to use API. I was planning on creating a simple nodejs/express API that makes the individual callouts asynchronously and then returns all of the results at one time.
The JS scene changes rapidly and a lot of information I've seen seems to be outdated. I was hoping someone could give me some advice and point me in the way of the best practices or frameworks that might be set up for a scenario like this.
Upvotes: 0
Views: 955
Reputation: 707466
This just sounds like a simple Express app - nothing complicated. I'd use the request-promise
module to give you a nice promise-based interface for making requests of other hosts and then use promises to coordinate the multiple requests into one response.
Other than that, you'd have to show us more details on exactly what you're trying to do for us to offer more specifics.
Here's a rough outline example if you just wanted to make three simultaneous requests and then combine the results:
const rp = require('request-promise');
const express = require('express');
const app = express();
app.get('/getAll', (req, res) => {
// construct urls
let p1 = rp(url1);
let p2 = rp(url2);
let p3 = rp(url3);
Promise.all([p1, p2, p3]).then(results => {
// construct full response from the results array
req.send(fullResponse);
}).catch(err => {
res.status(500).send(err.message);
});
});
app.listen(80);
EDIT Jan, 2020 - request() module in maintenance mode
FYI, the request
module and its derivatives like request-promise
are now in maintenance mode and will not be actively developed to add new features. You can read more about the reasoning here. There is a list of alternatives in this table with some discussion of each one. I have been using got()
myself and it's built from the beginning to use promises and is simple to use.
Upvotes: 3
Reputation: 391
Personally, I use async for nodejs (Link Here), the async.parallel method takes an array of ajax calls, each with it's own optional callback, as well as a callback for when all are done.
Upvotes: 1