3 var _
= require('lodash');
4 var lazy
= require('lazy.js');
5 var persistence
= require('gitter-web-persistence');
6 const mongoReadPrefs
= require('gitter-web-persistence-utils/lib/mongo-read-prefs');
11 function getCursorByUserId(userId
) {
12 const cursor
= persistence
.UserGroupFavourites
.find({
16 .read(mongoReadPrefs
.secondaryPreferred
)
25 * Based on gitter-web-rooms/lib/recent-room-core.js
27 function addGroupAsFavouriteInLastPosition(userId
, groupId
) {
28 return findFavouriteGroupsForUser(userId
).then(function(userGroupFavourites
) {
30 lazy(userGroupFavourites
)
36 setOp
['favs.' + groupId
] = lastPosition
;
38 return persistence
.UserGroupFavourites
.update(
41 { upsert
: true, new: true }
44 .thenReturn(lastPosition
);
50 * Based on gitter-web-rooms/lib/recent-room-core.js
52 function addGroupAsFavouriteInPosition(userId
, groupId
, position
) {
53 return findFavouriteGroupsForUser(userId
).then(function(userGroupFavourites
) {
54 var values
= lazy(userGroupFavourites
)
57 return a
[1] >= position
&& a
[0] !== groupId
;
65 // NB: used to be i = 1
66 for (var i
= 0; i
< values
.length
; i
++) {
70 /* Only increment those values before this one */
71 values
.splice(i
, values
.length
);
74 /* This dude needs an increment */
79 var inc
= lazy(values
)
81 return ['favs.' + a
[0], 1];
86 set['favs.' + groupId
] = position
;
88 var update
= { $set: set };
89 if (!_
.isEmpty(inc
)) update
.$inc
= inc
; // Empty $inc is invalid
91 return persistence
.UserGroupFavourites
.update({ userId
: userId
}, update
, {
96 .thenReturn(position
);
102 * Based on gitter-web-rooms/lib/recent-room-core.js
104 function clearFavourite(userId
, groupId
) {
106 setOp
['favs.' + groupId
] = 1;
108 return persistence
.UserGroupFavourites
.update({ userId
: userId
}, { $unset
: setOp
}, {})
113 function findFavouriteGroupsForUser(userId
) {
114 return persistence
.UserGroupFavourites
.findOne({ userId
: userId
}, { favs
: 1 }, { lean
: true })
116 .then(function(userGroupFavourites
) {
117 if (!userGroupFavourites
|| !userGroupFavourites
.favs
) return {};
119 return lazy(userGroupFavourites
.favs
)
125 function updateFavourite(userId
, groupId
, favouritePosition
) {
126 if (favouritePosition
) {
127 /* Deal with legacy, or when the star button is toggled */
128 if (favouritePosition
=== true) {
129 return addGroupAsFavouriteInLastPosition(userId
, groupId
);
131 return addGroupAsFavouriteInPosition(userId
, groupId
, favouritePosition
);
134 // Unset the favourite
135 return clearFavourite(userId
, groupId
);
141 findFavouriteGroupsForUser
: findFavouriteGroupsForUser
,
142 updateFavourite
: updateFavourite