I'm kinda new to Sails/Node, but I'm using the Q library to run queries in parallel. For example, I have a controller method which searches results, but also provides the total count of records in the response object:
search: function(req, res)
{
//parse parameters
var where = req.param('where') || {};
var limit = req.param('limit')|| 0;
var skip = req.param('skip') || 0;
//in case limit or skip are strings, convert to numbers
if (limit) { limit = +limit; }
if (skip) { skip = +skip; }
//prepare query promises for total records and a limited result set
var countPromise = User.count(where);
var findPromise = User.find({
limit: limit,
skip: skip,
sort: req.param('sort'),
where: where
});
console.log('Searching Users: limit: '+limit+', skip: '+skip+', where:',where);
//run asynchronous queries in parallel and
//return composite JSON object on success
Q.all([countPromise,findPromise])
.spread(function(numRecords, matchingRecords){
console.log(numRecords + " total users found, sending " + matchingRecords.length + " records starting from " + skip + ".");
//package response
var response = {};
response.total = numRecords;
response.users = matchingRecords || [];
//send response
return res.json(response);
}).fail(function(err){
//return server error
return res.serverError(err);
});
}
Although Waterline uses the Q library underneath, I had to require the q library at the top of the controller in order to use the all
method. Is there a way to make the Q library available to all controllers/my entire app? Or should I just include the require statement at the top of each controller that needs it?