mohamed adel
mohamed adel

Reputation: 715

NodeJS reusable HTTP requests using axios

I have to make tons of API calls in my app. I have like 8 trillion Axios calls.

So I decided to make a helper function for axious and pass the URL to it every time I want to do HTTP Request .

But I get an error here are my files:

apiUtils.js:

const axios = require("axios")
const handleError = require('./apiHandleError')
const SERVER_DOMAIN = process.env.HOST;
const AuthorizationHeader = process.env.AUTH
const getHeaders = () => {
    return {
        headers: {
            'Authorization': AuthorizationHeader
        },
    };
};
// HTTP GET Request - Returns Resolved or Rejected Promise
const getRequest = (url) => {
    return new Promise((resolve, reject) => {
        axios.get(`${SERVER_DOMAIN}${url}`, getHeaders())
            .then(response => {
                resolve(response)
            })
            .catch(error => {
                reject(handleError(error))
            });
    });
};
module.exports = getRequest

 //apihandleError.js - Common Error Handler Function
 const handleError = (error) => {
     let {
         status,
         message
     } = error.response;

     switch (status) {
         case 401:
             console.log(status)
             break;
             // do something when you're unauthenticated
         case 403:
             console.log(status)
             // do something when you're unauthorized to access a resource
             break;
         case 404:
             message = ({
                 status: `Couldn't reach Arena Gaming Server. Try again later`,
                 result: 404
             })
             // do something when the resource isnot found
             break;
         case 500:
             console.log(status)
             // do something when your server exploded
             break;
         default:
             // handle normal errors with some alert or whatever
     }
     return message; // I like to get my error message back
 }
 module.exports = handleError

And this is how I call the function:

const userId = getRequest(`/api/reports/users/${userId}/general`)
  .then(data => {
    console.log(data);
    // do something with User #5
  })
  .catch(errorMessage => {
    console.log(errorMessage);
    // the error has already been handled by handleError
    // the message get's passed here
    // do something like store it in redux, etc.
  });

I get errorMessage result is : status: `Couldn't reach Arena Gaming Server. Try again later`, result: 404

Upvotes: 1

Views: 1800

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

I don't think you need to wrap the axios.get which already returns a promise in another promise. you could simplify this like this

const axios = require("axios");
const handleError = require("./apiHandleError");
const SERVER_DOMAIN = process.env.HOST;
const AuthorizationHeader = process.env.AUTH;
const getHeaders = () => {
  return {
    headers: {
      Authorization: AuthorizationHeader
    }
  };
};
// HTTP GET Request - Returns Resolved or Rejected Promise
const getRequest = async url => {
  try {
    const response = await axios.get(`${SERVER_DOMAIN}${url}`, getHeaders());
    return response;
  } catch (err) {
    return handleError(err);
  }
};

Usage can be as you are using or async/await

Hope this helps

Upvotes: 1

Related Questions