Skip to content

Commit

Permalink
[IMPROVE] Use MongoBD aggregation to get users from a room (#12566)
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo authored and sampaiodiego committed Dec 4, 2018
1 parent d11daee commit 0644caf
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions server/methods/getUsersOfRoom.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Meteor } from 'meteor/meteor';

Meteor.methods({
getUsersOfRoom(rid, showAll) {
async getUsersOfRoom(rid, showAll) {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getUsersOfRoom' });
Expand All @@ -16,17 +16,32 @@ Meteor.methods({
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getUsersOfRoom' });
}

const subscriptions = RocketChat.models.Subscriptions.findByRoomIdWhenUsernameExists(rid, { fields: { 'u._id': 1 } }).fetch();
const userIds = subscriptions.map((s) => s.u._id); // TODO: CACHE: expensive
const options = { fields: { username: 1, name: 1 } };

const users = showAll === true
? RocketChat.models.Users.findUsersWithUsernameByIds(userIds, options).fetch()
: RocketChat.models.Users.findUsersWithUsernameByIdsNotOffline(userIds, options).fetch();
const subscriptions = RocketChat.models.Subscriptions.findByRoomIdWhenUsernameExists(rid);

return {
total: userIds.length,
records: users,
total: subscriptions.count(),
records: await RocketChat.models.Subscriptions.model.rawCollection().aggregate([
{ $match: { rid } },
{
$lookup:
{
from: 'users',
localField: 'u._id',
foreignField: '_id',
as: 'u',
},
},
{
$project: {
'u._id': 1,
'u.name': 1,
'u.username': 1,
'u.status': 1,
},
},
...(showAll ? [] : [{ $match: { 'u.status': 'online' } }]),
{ $replaceRoot: { newRoot: { $arrayElemAt: ['$u', 0] } } },
]).toArray(),
};
},
});

0 comments on commit 0644caf

Please sign in to comment.