0

I'm trying to create REST API. My API should return a list of users taken from a 3rd party (after some manipulations) and return it.

Here is my code:

function getUsersFrom3rdParty(options) {
    https.get(options, (resp) => {

    let data ='';
    // A chunk of data has been received.
    resp.on('data', (chunk) => {
        data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
        console.log(JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: " + err.message);
});

}

  exports.getUsers = (req, res, next) => {

   var data = getUsersFrom3rdParty();
 //do the manilupations and return to the api
};

I don't get the data in getUsers function.

Joel
  • 477
  • 1
  • 8
  • 14

2 Answers2

0

I'd suggest using something like axios - npmjs - for making asynchronous calls to a 3rd party API:

const axios = require('axios')

function getUsersFrom3rdParty(options) {
  const processResponse = (response) => {
    const processedResponse = ...

    // do whatever you need to do, then return

    return processedResponse
  }
  return axios.get('/example.com')
    .then(processResponse)
}

// then, you can use `getUsersFrom3rdParty` as a promise
exports.getUsers = (req, res, next) => {
  const handleResponse = (data) => {
    res.json({ data }) // or whatever you need to do
  }
  const handleError = (err) => {
    res.json({ error: 'Something went wrong!' }) // or whatever you need to do
  }

  getUsersFrom3rdParty(...)
    .then(handleResponse)
    .catch(handleError)
}

This way, you're waiting for your API call to finish before you render something and/or return a response.

goto
  • 4,336
  • 15
  • 20
0

You are not passing options variable when you are calling getUsersFrom3rdParty function

var data = getUsersFrom3rdParty(options);

You have to pass options to make it work and I suggest to use request module .It works better than https module.

Here is your code using request

const request = require("request");

function getUsersFrom3rdParty(options) {
  request(options, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      //Returned data
      console.log(JSON.parse(body));
    }
  });
}

exports.getUsers = (req, res, next) => {
  var data = getUsersFrom3rdParty(options);
};
David
  • 734
  • 5
  • 10