Home > Software design >  How to group API calls in a middleware nodejs application?
How to group API calls in a middleware nodejs application?

Time:09-01

I need to write a nodejs script that communicates with the server, with the number of tasks as a comma-separated string ("1, 2, 3") in the URI. The thing is, I am getting 414 for many tasks. I am not able to think to come up with a solution. How to batch process it? Like for each and every 50 ids, the API should be called like api/${1, 2, ... 50} and api/${51, 52, ... 100}

My API call is:

const patchProducts = async (ids) => {
  try {
    await axios.patch(`api/${ids}`);
  } catch (error) {
    console.log(error);
  }
};

CodePudding user response:

You can split the list of ids into lists of (say) 50 items at most, and process each separately:

const patchProducts = async (ids) => {
  const arr = ids.split(', ');
  try {
    while (arr.length) {
      const batch = arr.splice(0, 50);
      await axios.patch(`api/${ batch.join(', ') }`);
    }
  } catch (error) {
    console.log(error);
  }
};
  • Related