0

I am building a restful API to fetch data from an external API (https://api.exchangeratesapi.io/latest). The fetch is successful. However, I want a situation where if you query like so "/api/rates?currency=EUR,GBP,USD", you will get

"rates": {
   "EUR": 0.0377244605,
   "GBP": 0.033795458,
   "USD": 0.044824204
}

And if there is no query parameter, all the rates will be returned. I tried using ternary operator to pull out the figures when a query parameter is present, but I get the error "TypeError: Cannot read property 'rates' of undefined"

Below is my app.js file

const express = require("express");
const request = require('request');
const apiCallFromRequest = require('./Requests')

const app = express();
const exchangeRouter = express.Router();
const port = process.env.PORT || 4001;

exchangeRouter.route(`/rates`)
  .get((req, res) => {
    const queryParameter = req.query;
    // console.log(queryParameter.currency)
    
    apiCallFromRequest.callApi(function(response) {
      let cur = queryParameter.currency

      res.json({
        results: {
          base: queryParameter.base ? queryParameter.base : response.base,
          date: response.date,
          rates: queryParameter.currency ? queryParameter.currency.response.rates : response.rates
        }
      })
      res.end();
    });
  });

app.use('/api', exchangeRouter);

app.get('/', (req, res) => {
  res.send('Welcome to my nodemon API')
});

app.listen(port, () => {
  console.log(`Running on port ${port}`);
})

And my Request.js file

const request = require('request');
 
const URL = `https://api.exchangeratesapi.io/latest`;

const callExternalApiUsingRequest = (callback) => {
    request(URL, { json: true }, (err, res, body) => {
    if (err) { 
        return callback(err);
     }
    //  console.log("body: ", body)
    return callback({
        base: body.base,
        date: body.date,
        rates: body.rates
    });
    });
}

module.exports.callApi = callExternalApiUsingRequest;
1
  • queryParameter.currency.rates returns undefined @Mike Malyi. I don't know why I'm blocked from commenting under your your comment. Commented Feb 9, 2021 at 22:01

2 Answers 2

1

As I can see you're trying to filter the response. It would be better to inject your query params into your external api call.

You're expecting currency as a query parameter /api/rates?currency=EUR,GBP,USD on your api. There is no response under currency that's why queryParameter.currency.rates is undefined

According to https://exchangeratesapi.io/ you can use symbols to achieve the same result:

GET https://api.exchangeratesapi.io/latest?symbols=USD,GBP HTTP/1.1

you may use the same query params as the external api for yours and use a function to inject them into the external call

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

Comments

1

The solution. My app.js file should look like this:

const express = require("express");
const request = require('request');
const apiCallFromRequest = require('./Requests')

const app = express();
const exchangeRouter = express.Router();
const port = process.env.PORT || 4001;

exchangeRouter.route(`/rates`)
  .get((req, res) => {
    
    apiCallFromRequest.callApi(function(response) {
      if (!base && !currency) {
        return res.status(200).json({
          results: {
            "base": response.base,
            "date": response.date,
            "rates": response.rates
          }
        })
      }

      // If there is a query parameter but no value
      if (!base) {
        return res.status(400).json({ message: "Please specify your home currency" })
      }
      if (!currency) {
        return res.status(400).json({ message: "Please specify exchange currency or currencies" })
      }

      // If there is query parameter and a value
      const exchangeRates = currency.toUpperCase().split(',')
      let currencyExchangeRates = {};
      for (const exchangeRate of exchangeRates) {
        //trim white space
        const value = exchangeRate.trim();
        currencyExchangeRates = { ...currencyExchangeRates, [value]: response.rates[value] }
      }
      console.log(currencyExchangeRates);
      res.json({
        results: {
          "base": base,
          "date": response.date,
          "rates": currencyExchangeRates
        }
      })
      res.end();
    });
  });

app.use('/api', exchangeRouter);

app.get('/', (req, res) => {
  res.send('Welcome to my nodemon API')
});

app.listen(port, () => {
  console.log(`Running on port ${port}`);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.