سؤال

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?

هل كانت مفيدة؟

المحلول

You can use globals to to do this. Initialize it somewhere in, or from, your initial code (top of app.js maybe - or whatever Sails runs from when you 'lift', as I think they call it).

globals.Q = require('q);

See the node doc on globals.

Of course, you are either accessing it as (e.g.)

var deferred = globals.Q.defer();

which feels clunky to me. Or,

var Q = globals.Q;
var deferred = Q.defer();

which doesn't really save you more than a few keystrokes over the require approach, in that you still need to explicitly make it available via the simple variable name.

But those are your options. You could also create some kind of common module that loads all your globals, e.g. consider a common.js

module.exports = { Q: require('q'),
                 util: require('util') };

And then in another file, you can just include them all at once.

var c = require('../path/to/common');
var deferred = c.Q.defer();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top