Skip to content

Instantly share code, notes, and snippets.

@A
Created March 7, 2014 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A/9411672 to your computer and use it in GitHub Desktop.
Save A/9411672 to your computer and use it in GitHub Desktop.
exports.getDialogs = function () {
return function (req, res) {
var dialogs = [];
_getUsersInDialogs(req.user._id, function (err, users) {
users.forEach(function (user, key, all) {
_getCountAndLastMessageInDialog(req.user._id, user, function (err, lastMessage, unread) {
dialogs.push({user: user, last_message: lastMessage, unread:unread});
if (key === all.length - 1) {
res.json(200, {
data: {
dialogs: dialogs
}
});
}
});
});
});
};
};
var _getUsersInDialogs = function (user, cb) {
var authors, users;
var next = new Countdown(2, function () {
users = users
.concat(authors)
.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
return cb(null, users);
});
Message
.distinct('author', {user: user}, function (err, _authors) {
authors = _authors;
next();
});
Message
.distinct('user', {author: user}, function (err, _users) {
users = _users;
next();
});
};
var _getCountAndLastMessageInDialog = function (requser, user, cb) {
var lastMessage, unread;
var next = new Countdown(2, function () {
return cb(null, lastMessage, unread);
});
Message
.findOne(null)
.or([{user: requser, author: user},{user: user, author: requser}])
.sort('-create_at')
.exec(function (err, _lastMessage) {
lastMessage = _lastMessage;
next();
});
Message
.find({user: requser, author: user, unread: true})
.count()
.exec(function (err, _unread) {
unread = _unread;
next();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment