0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@RossBassett - Well it's often not "necessary" to include external libraries (you could always just rewrite it all yourself), but in my opinion, the #1 advantage of node.js is the huge repository of modules in NPM that have already done a lot of the work for you and avoiding already built, tested and maintained code that solves a problem you have is just counterproductive. This is server-side code. It costs you nothing (and saves you a lot of time and bugs) to include an already built module that does something you need. And, the full source is there if you have questions.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.