3 const lazy = require('lazy.js');
4 const _ = require('lodash');
5 const persistence = require('gitter-web-persistence');
6 const calculateFavouriteUpdates = require('./calculate-favourite-updates');
7 const mongoReadPrefs = require('gitter-web-persistence-utils/lib/mongo-read-prefs');
9 const LEGACY_FAV_POSITION = 1000;
12 * For exporting things
14 function getCursorByUserId(userId) {
15 const cursor = persistence.UserTroupeFavourites.find({
19 .read(mongoReadPrefs.secondaryPreferred)
26 function findFavouriteTroupesForUser(userId) {
27 return persistence.UserTroupeFavourites.findOne({ userId: userId }, { favs: 1 }, { lean: true })
29 .then(function(userTroupeFavourites) {
30 if (!userTroupeFavourites || !userTroupeFavourites.favs) return {};
32 return lazy(userTroupeFavourites.favs)
35 // Replace any legacy values with 1000
36 if (a[1] === '1') a[1] = LEGACY_FAV_POSITION;
46 function addTroupeAsFavouriteInLastPosition(userId, troupeId) {
47 return findFavouriteTroupesForUser(userId).then(function(userTroupeFavourites) {
49 lazy(userTroupeFavourites)
55 setOp['favs.' + troupeId] = lastPosition;
57 return persistence.UserTroupeFavourites.update(
60 { upsert: true, new: true }
63 .thenReturn(lastPosition);
67 function addTroupeAsFavouriteInPosition(userId, troupeId, position) {
68 return findFavouriteTroupesForUser(userId).then(function(userTroupeFavourites) {
69 var values = lazy(userTroupeFavourites)
73 const newValues = calculateFavouriteUpdates(troupeId, position, values);
75 var inc = lazy(newValues)
77 return ['favs.' + a[0], 1];
82 set['favs.' + troupeId] = position;
84 var update = { $set: set };
85 if (!_.isEmpty(inc)) update.$inc = inc; // Empty $inc is invalid
87 return persistence.UserTroupeFavourites.update({ userId: userId }, update, {
92 .thenReturn(position);
96 function clearFavourite(userId, troupeId) {
98 setOp['favs.' + troupeId] = 1;
100 return persistence.UserTroupeFavourites.update({ userId: userId }, { $unset: setOp }, {})
105 function updateFavourite(userId, troupeId, favouritePosition) {
106 if (favouritePosition) {
107 /* Deal with legacy, or when the star button is toggled */
108 if (favouritePosition === true) {
109 return addTroupeAsFavouriteInLastPosition(userId, troupeId);
111 return addTroupeAsFavouriteInPosition(userId, troupeId, favouritePosition);
114 // Unset the favourite
115 return clearFavourite(userId, troupeId);
123 findFavouriteTroupesForUser