Consume API Node services

0

Dear, I have a microservice (a) or a small API that requires you to use the services of another API (b), which consists of about 4 ENDPOINT (Address, municipality, province, region, etc).

I am currently using a NODE module called request:

const request = require('request');

but I can only call an endpoint:

 request(
        'http://localhost:3000/v1/api/endpoint/${parametro_1}/? 
         parametroQuery=${parametroQuery}',
        { json: true }, (err, res, body) => {
          if (err) { return console.log(err); }
          if (body.data) {
            body.data.forEach((o) => {

            })
          }
        }
      );

With the data I get, specifically an id that comes from that endpoint, I must call another service, and so on about 4 services in succession.

How do you suggest doing it to make it more optimal and efficient?

    
asked by Rodrigo 23.08.2018 в 18:38
source

1 answer

0

Using the request module, if each request needs the value of the previous one, each new call you should make it in the callback of the previous one, but instead you can use promises, with the module request-promise and you would do something like:

var request = require('request-promise');

var url1 = "ejemplo1.com";
var url2 = "ejemplo2.com";
var url3 = "ejemplo3.com";

request(url1)
  .then(respuesta => {
    // respuesta de url1 y modifico url2
    return request(url2)
  })
  .then(respuesta => {
    // respuesta de url2 y modifico url3
    return request(url3)
  })
  .then(respuesta => {
    //luego de todas las respuestas
  })
  .catch(err => console.log(err)) 
    
answered by 23.08.2018 в 19:02