Skip to content

Instantly share code, notes, and snippets.

@adamrneary
Created January 28, 2015 15:24
Show Gist options
  • Select an option

  • Save adamrneary/57e39a8556efda849f98 to your computer and use it in GitHub Desktop.

Select an option

Save adamrneary/57e39a8556efda849f98 to your computer and use it in GitHub Desktop.
// This API method returns a limited number of objects based on the limit, but
// it relies on the query parameters to define the pagination filtes (currently
// managed in Angular)
//
// Because it has to make three separate queries, we make use of Mongoose-Q to
// manage the promises in a way that is performant and readable
UserService.prototype.find = function(params, callback) {
// First we parse the parameters
var query = buildUserQuery(params);
var sort = (params.descending ? '-' : '') + params.sort || 'displayName';
var limit = params.limit || 30;
// Then we will create a return object to which the functions below can add.
var returnObject = {};
// These "find" chains return promises
findNextFewUsers = User
.find(query)
.where('deleted').ne(true)
.sort(sort)
.limit(limit)
.populate('company')
findConsultantCount = User
.find(query)
.where('deleted').ne(true)
.where({accountType: 'USER'})
.count()
findCompanyCount = User
.find(query)
.where('deleted').ne(true)
.where({accountType: 'COMPANY'})
.count()
// These functions handle the returned data from each promise
function processUsers(users) {
if (params.projectKey) {
users = sortUsersByProjectScore(users, params.projectKey);
}
returnObject.users = users;
}
function processConsultantCount(count) {
returnObject.numberOfCompanies = count;
}
function processCompanyCount(count) {
returnObject.numberOfConsultants = count;
};
// And boom goes the dynamite.
findNextFewUsers
.execQ()
.then(processUsers)
.then(findConsultantCount)
.then(processConsultantCount)
.then(findCompanyCount)
.then(processCompanyCount)
.then(function() {
callback(null, returnObject)
})
.catch(function(err) {
callback(err, null);
})
.done();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment