Created
March 7, 2014 13:40
-
-
Save A/9411672 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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