How to effectively process a rest request in node/express js where request body contains an array of object

Viewed 53

I have a request body like following -

[
        {
         id:"1234",
         name:"Jayesj",
         amount:100
        },
     {
         id:"123",
         name:"Yogesh",
         amount:2090
        },
     {
         id:"12345",
         name:"Ram",
         amount:100
        },
     {
         id:"6674",
         name:"Shyam",
         amount:5000
        },
    ]

And I am processing each object with the help of loop -

For each object I have to do the following processing -

  1. validate if all parameters in object has valid format.
  2. Check if given id is present in db or not.
  3. if present send request to payment gateway
  4. after getting response from payment gateway I have to make an response object to put in reponse array for respective request object.

Example of response array -

[
    {
             id:"1234",
             pg_resp:{
                      msg:"success"
                 }
            },
         {
             id:"123",
              pg_resp:{
                      msg:"error"
                 }
            },
         {
             id:"12345",
             pg_resp:{
                      msg:"success"
                 }
            },
         {
             id:"6674",
            pg_resp:{
                      msg:"error"
                 }
            },
]

I have find two ways to process this request that are -

first method -

i. loop on each object ii. after getting the complete response from payment gateway for first object iii. make response object for first object iv. then do this for all objects v. then send the reponse.

in this method the request with 10 objects take 47 seconds to get response from my server

second method -

   i. loop on each object
   ii. send request for first object to payment gateway
  iii. dont wait for payment gateway response but return a promise
   iv. do it for all objects.
  v. promise.all all promises and make response array from that resolved promises

in this method the request with 10 objects take 7 seconds to get response from my server

Second method is looking more efficient but loop in it also block the event loop when objects in array are more.

I want to ask what is the most scalable way of doing such tasks in nodejs , (using a queue or what ) PLease suggest it is very imp for my business product.

Thanks to all in advanced.

0 Answers
Related