Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

RestAPI with multidimensional data/multilevel data in sql database in node.js?

RestAPI with multidimensional data/multilevel data in sql database in node.js?

Problem

In node.js it is recommended that we should not use blocking calls to database or any other place. But if I go according to this rule I am facing a problem with rest api with sql database. It might be achievable in nosql databases.

Problem :

I have a table in database with columns username,col1,column2,time. The rest api data I want is something like this

{ 
  username:A,
  max(col1):123,
  deviation_column2: [{
       time:10:00,
       column2:54
     },
     { 
       time:10:05,
       column2:59
     }
  ]
},
{ 
  username:B,
  max(col1):123,
  deviation_column2: [{
       time:10:00,
       column2:54
     },
     { 
       time:10:05,
       column2:59
     }
  ]
}

I want to generate rest api which gives me avg of col1, and standard deviation of column2 with time.

I could achieve this by two blocking calls to database and merging the data but in Node.js it is not advisable, so how can I give this type of rest response to my client without using blocking calls?

I can achieve the following result separately by using stdev and max function on group of username and time.

Problem courtesy of: Gaurav

Solution

You can achieve such results easily with Fibers and their derivatives. wait.for is especially pretty. With these tools, you can run synchronous calls to database without blocking the event loop.

Notice that Fibers are a bit controversial, as they significantly change the way you think in Node, albeit there's no actual disadvantage in using them.

Solution courtesy of: Hubert OG

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

RestAPI with multidimensional data/multilevel data in sql database in node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×