API Calls with retries

abhinavsachdeva

Abhinav Sachdeva

Posted on May 12, 2020

API Calls with retries

Have you run into a situation when you needed to call a buggy API that responds with an error ever so often?
What's the solution if you have no control over that API?

Retries to the rescue!

As it happens...

  1. Our fetchDataWithRetries function takes in the maxReties (uses 3 as a default value)
  2. When called, this function returns a function and we make use of closure to capture the value of tries and maxTries
  3. The returned function - apicall - takes in the URL to be called.
    1. If the response is a success - return it as is
    2. If there's an error increment the tries, check for max retry limit and recursively call itself

    const fetch = require('node-fetch');

    function fetchDataWithRetries(maxTries) {
        maxTries = parseInt(maxTries);
        if(!maxTries) maxTries =  3;
        let tries =  0;
            return function apicall(url) {
                if (!url) return Promise.reject("URL required")
                console.log("APICALL " + (tries + 1));
                return fetch(url)
                    .then(function (res) {
                        console.log("fetch success");
                        return res.json();
                    })
                    .catch(e => {
                        console.log("Fetch Error")
                        if (++tries < maxTries)
                            return apicall(url);
                        return Promise.reject(e)
                    });
            }
   }

 const  retyCount = 2, APIURL = 'https://jsonplaceholder.typicode.com/users/1';

fetchDataWithRetries(retyCount)(APIURL)
    .then(data => console.log(data))
    .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
abhinavsachdeva
Abhinav Sachdeva

Posted on May 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

API Calls with retries
node API Calls with retries

May 12, 2020