user14872626
user14872626

Reputation:

How to perform HTTP requests in NodeJS with a Priority value?

I have an array of objects which contains the url and priority number (which is an integer). I need to perform the http requests in ascending order of the priority value. For eg, if the array is like

const requestArray = [
  {
    url: "http://google.com",
    priority: 4
  },
  {
    url: "http://facebook.com",
    priority: 1
  },
  {
    url: "http://failed.example.gibberish.com",
    priority: 2
  }
];

First, the Facebook should be pinged as it's with priority 1 and a valid response to be logged (as it's valid) and failed.example.gibberish.com should be pinged as its priority is 2 and it should be rejected as its invalid URL and google.com should be pinged as it's with largest priority number value and whatever the response, it should be logged. I tried to achieve this with os.setPriority ( I am new to Node.js. I don't know how exactly to follow with this )

Demo: jdoodle.com/ia/jDx

In case of no priority value, like { url: 'http://jsonplaceholder.typicode.com/posts' }, I should set 1 to that particular object's priority value and it should come before any other request with priority greater than 1

Upvotes: 0

Views: 367

Answers (1)

dwsndev
dwsndev

Reputation: 790

Map missing priorities then sort your array by priority before executing your HTTP calls through a loop.

const requestArray = [
  {
    url: "http://google.com",
    priority: 4
  },
  {
    url: "http://facebook.com",
    priority: 1
  },
  {
    url: "http://failed.example.gibberish.com",
    priority: 2
  },
  {
    url: "http://nopriority.com"
  }
];

const cleanRequests = requestArray
  .map((req) => req.hasOwnProperty('priority') ? req : { ...req, priority: 1 })
  .sort((a, b) => (a.priority > b.priority) ? 1 : -1);

for (let request of cleanRequests) {
   const { priority, url } = request;
   console.log({ priority, url });
   // HTTP calls here...
}

Upvotes: 1

Related Questions