Implement load old chat messages functionality

This commit is contained in:
Chris Blanchard 2015-09-20 18:05:22 +01:00
parent 215cdc7a98
commit a436a65c45
4 changed files with 45 additions and 10 deletions

View file

@ -28,8 +28,17 @@ messageSchema.methods.toJson = () => {
};
messageSchema.statics.list = (options, callback) => {
return this.find({deleted: false})
.sort({createdAt: -1})
let query = this.find({deleted: false})
if (options.before) {
query.where({
createdAt: {
$lt: new Date(options.before)
}
});
}
return query.sort({createdAt: -1})
.limit(30)
.exec((error, messages) => {
if (error) return callback(error);

View file

@ -25,9 +25,7 @@ module.exports = namespace => {
};
var refreshMessages = socket => {
Message.list({
deleted: false
}, (error, messages) => {
Message.list({}, (error, messages) => {
if (error) {
winston.error("Unable to retrieve messages. Error:", error);
return;
@ -41,6 +39,20 @@ module.exports = namespace => {
});
};
var retrievePreviousMessages = (options, socket) => {
Message.list({
before: options.before
}, (error, messages) => {
if (error) {
winston.error("Unable to retrieve messages. Error:", error);
return;
}
socket.emit("message:append", {
messages: messages
});
});
}
namespace.on('connection', socket => {
socket.on('message:new', data => {
@ -56,7 +68,7 @@ module.exports = namespace => {
return;
}
winston.info("New Message", JSON.stringify(newMessage));
broadcastUpdate(newMessage)
broadcastUpdate(newMessage);
});
});
@ -74,7 +86,10 @@ module.exports = namespace => {
});
});
socket.on('message:refresh', () => {
socket.on('message:refresh', data => {
if (data && data.before) {
return retrievePreviousMessages(data, socket);
}
refreshMessages(socket);
});
});

View file

@ -12,13 +12,20 @@ var Chatroom = React.createClass({
socket.on("message:append", data => {
let history = self.props.history;
history.push(data);
let historicalUpdate = !!data.messages;
if (historicalUpdate) {
history = history.concat(data.messages);
} else {
history.push(data);
}
self.setProps({
history: history.sort((a, b) => {
return new Date(a.createdAt) - new Date(b.createdAt);
})
});
self.scrollToBottom();
if (!historicalUpdate) {
self.scrollToBottom();
}
});
// Message History Retrieved
@ -39,8 +46,10 @@ var Chatroom = React.createClass({
},
loadMoreMessages() {
var earliestMessage = this.props.history[0];
if (earliestMessage === undefined) return;
socket.emit("message:refresh", {
// before:
before: earliestMessage.createdAt
});
},
@ -66,6 +75,7 @@ var Chatroom = React.createClass({
<ul className="chat" id="chatmessages" ref="messageContainer">
<li className="text-center">
<a href="#"
onClick={this.loadMoreMessages}
className="btn btn-primary btn-xs">
Load more messages
</a>

View file

@ -64,6 +64,7 @@ describe("Message Model", function () {
done();
});
});
it ("retrieves messages before a date if specified");
it ("does not list deleted messages", function (done) {
helper.createMessage({
content: "FOOBAR"