Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / modules / groups / lib / group-browser-service.js
blob1db95448876d31242448cc83cd0a0025044209b9
1 'use strict';
3 var Promise = require('bluebird');
4 var Troupe = require('gitter-web-persistence').Troupe;
5 var assert = require('assert');
6 var groupRoomFinder = require('./group-room-finder');
8 function sumUserCountForQuery(query) {
9 return Troupe.aggregate([
11 $match: query
14 $group: {
15 _id: '1',
16 count: { $sum: '$userCount' }
20 $project: {
21 _id: 0,
22 count: 1
26 .exec()
27 .then(function(results) {
28 return (results && results[0] && results[0].count) || 0;
29 });
32 function findRoomsWithPagination(groupId, userId, options) {
33 assert(groupId, 'groupId is required');
35 return groupRoomFinder.queryForAccessibleRooms(groupId, userId).then(function(query) {
36 var pipeline = [
37 { $match: query },
39 $sort: {
40 userCount: -1,
41 uri: 1
46 if (options && options.skip && options.skip > 0) {
47 pipeline.push({
48 $skip: options.skip
49 });
52 var limit = (options && options.limit) || 30;
53 pipeline.push({
54 $limit: limit
55 });
57 if (options.includeUsers) {
58 pipeline.push(
60 $lookup: {
61 from: 'troupeusers',
62 localField: '_id',
63 foreignField: 'troupeId',
64 as: 'troupeuser'
68 $project: {
69 _id: 1,
70 uri: 1,
71 userCount: 1,
72 userIds: {
73 $slice: ['$troupeuser', 10]
78 $project: {
79 _id: 1,
80 uri: 1,
81 userCount: 1,
82 userIds: {
83 $map: {
84 input: '$userIds',
85 as: 'troupeuser',
86 in: '$$troupeuser.userId'
94 return Promise.join(
95 Troupe.aggregate(pipeline).exec(),
96 Troupe.count(query),
97 sumUserCountForQuery(query),
98 function(results, total, totalUsers) {
99 return {
100 results: results,
101 total: total,
102 totalUsers: totalUsers
109 module.exports = {
110 findRoomsWithPagination: findRoomsWithPagination