diff --git a/src/test/database-test.js b/src/test/database-test.js index 080125eb8..9aec6ffdc 100644 --- a/src/test/database-test.js +++ b/src/test/database-test.js @@ -522,6 +522,36 @@ describe('database', function () { }); }); + it('can get all with group ids paged', function (done) { + userdb.getAllWithGroupIdsPaged(1, 2, function (error, all) { + expect(error).to.not.be.ok(); + expect(all.length).to.equal(2); + + var userCopy; + + userCopy = _.extend({}, USER_0); + userCopy.groupIds = []; + expect(all[0]).to.eql(userCopy); + + userCopy = _.extend({}, USER_1); + userCopy.groupIds = []; + expect(all[1]).to.eql(userCopy); + + userdb.getAllWithGroupIdsPaged(2, 2, function (error, all) { + expect(error).to.not.be.ok(); + expect(all.length).to.equal(1); + + var userCopy; + + userCopy = _.extend({}, USER_2); + userCopy.groupIds = []; + expect(all[0]).to.eql(userCopy); + + done(); + }); + }); + }); + it('can get all admins', function (done) { userdb.getAllAdmins(function (error, all) { expect(error).to.not.be.ok(); diff --git a/src/userdb.js b/src/userdb.js index 3b30e24c2..0516d99ae 100644 --- a/src/userdb.js +++ b/src/userdb.js @@ -8,6 +8,7 @@ exports = module.exports = { getByResetToken: getByResetToken, getOwner: getOwner, getAllWithGroupIds: getAllWithGroupIds, + getAllWithGroupIdsPaged: getAllWithGroupIdsPaged, getAllAdmins: getAllAdmins, add: add, del: del, @@ -115,6 +116,30 @@ function getAllWithGroupIds(callback) { }); } +function getAllWithGroupIdsPaged(page, perPage, callback) { + assert.strictEqual(typeof page, 'number'); + assert.strictEqual(typeof perPage, 'number'); + assert.strictEqual(typeof callback, 'function'); + + var query = `SELECT ${USERS_FIELDS},GROUP_CONCAT(groupMembers.groupId) AS groupIds + FROM users LEFT OUTER JOIN groupMembers ON users.id = groupMembers.userId + GROUP BY users.id + ORDER BY users.username + ASC LIMIT ${(page-1)*perPage},${perPage}`; + + database.query(query, function (error, results) { + if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error)); + + results.forEach(function (result) { + result.groupIds = result.groupIds ? result.groupIds.split(',') : [ ]; + }); + + results.forEach(postProcess); + + callback(null, results); + }); +} + function getAllAdmins(callback) { assert.strictEqual(typeof callback, 'function');