yupyupyup
yupyupyup

Reputation: 103

chaining sequential api calls and returning the data to be sorted

I'm building an Express REST api. In the GET, i want to be able to be able to make the api call shown below, and then for each of the results, call the same api at a different endpoint (not shown) using a value from the result as a param.

I was having trouble figuring out how to situate the api call shown here with another one to a different endpoint so that the second call waits for the first one to finish. I thought using the 'then' method would help here.

I also would like to know if there's another way of grabbing the data without using the chunk logic shown. Ideally it would be a clean instantiation of two sequential api calls, then be able to sort the returned data before returning it. right now i know its a bit messy and any suggestions on a cleaner way of doing this would be great.

const express = require('express');
const router = express.Router();
const https = require('https');

const url = '/https://github.com/:user/:reponame'

router.get(url, async function (req, res) {
    const user = req.params.user;
    const reponame = req.params.reponame;
    const options = {
        hostname: 'api.github.com',
        path: '/repos/' + user + '/' + reponame + '/commits',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36'
        },
        OAUth: <key>
    }   


    https.get(options, function (apiResponse) {
        let data = '';

        // a data chunk has been received.
        apiResponse.on('data', (chunk) => {
          data += chunk;
        });
      
        apiResponse.on('end', () => {
          res.send(JSON.parse(data))
        });
       
    }).on('error', (e) => {
        console.log(e);
        res.status(500).send('Error');
    })
})//2nd api call here?

module.exports = router;```

Upvotes: 2

Views: 1599

Answers (1)

Anatoly
Anatoly

Reputation: 22803

You need to convert this https.get function with a callback into async function using Promise (see this answer, for instance).

async function getAsync(options) {
  return new Promise((resolve, reject) => {
https.get(options, function (apiResponse) {
        let data = '';

        // a data chunk has been received.
        apiResponse.on('data', (chunk) => {
          data += chunk;
        });
      
        apiResponse.on('end', () => {
          resolve(data);
        });
       
    }).on('error', (e) => {
        reject(e);
    })
  })
}

Usage:

try {
  const data = await getAsync(options);
} catch(err) {
  console.error(err);
  res.status(500).send('Error');
  return;
}
try {
  const anotherData = await getAsync(anotherOptions);
} catch(err) {
  console.error(err);
  res.status(500).send('Another error');
  return;
}

Upvotes: 2

Related Questions