ensl_gathers/lib/chat/controller.js

77 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-07-21 14:10:24 +00:00
"use strict";
/*
* Chatroom Controller
*
* Server API
2015-09-14 21:10:26 +00:00
* message:append - New message to be added to history
2015-07-21 14:10:24 +00:00
* message:refresh - Reload all messages
*
* Client API
* message:new - New message has been created
* message:refresh - Retrieve most recent messages
2015-08-07 00:53:52 +00:00
* message:delete - Deletes message by ID (Admin only)
2015-07-21 14:10:24 +00:00
*
*/
2015-08-07 00:14:36 +00:00
var mongoose = require("mongoose");
2015-08-18 09:56:35 +00:00
var Message = mongoose.model("Message");
2015-07-21 14:10:24 +00:00
2015-08-10 23:56:53 +00:00
module.exports = namespace => {
2015-07-21 14:10:24 +00:00
2015-08-10 23:56:53 +00:00
var broadcastUpdate = message => {
2015-09-14 21:10:26 +00:00
namespace.emit("message:append", message);
2015-07-21 14:10:24 +00:00
};
2015-08-10 23:56:53 +00:00
var refreshMessages = socket => {
Message.list({}, (error, messages) => {
2015-08-07 00:53:52 +00:00
if (error) {
winston.error("Unable to retrieve messages. Error:", error);
return;
}
var receiver = (socket === undefined) ? namespace : socket;
receiver.emit("message:refresh", {
chatHistory: messages
});
});
};
2015-08-10 23:56:53 +00:00
namespace.on('connection', socket => {
2015-07-21 14:10:24 +00:00
2015-08-10 23:56:53 +00:00
socket.on('message:new', data => {
2015-08-07 00:14:36 +00:00
Message.create({
author: {
username: socket._user.username,
avatar: socket._user.avatar
},
2015-07-21 14:10:24 +00:00
content: data.content
2015-08-10 23:56:53 +00:00
}, (error, newMessage) => {
2015-08-07 00:14:36 +00:00
if (error) {
winston.error("Unable to store message. Error:", error);
return;
}
broadcastUpdate(newMessage)
});
2015-07-21 14:10:24 +00:00
});
2015-08-10 23:56:53 +00:00
socket.on('message:delete', data => {
2015-08-07 00:53:52 +00:00
var id = data.id;
if (id === undefined || !socket._user.admin) return;
2015-08-10 23:56:53 +00:00
Message.remove({_id: id}, error => {
2015-08-07 00:14:36 +00:00
if (error) {
2015-08-07 00:53:52 +00:00
winston.error("An error occurred when trying to delete message:", error);
2015-08-07 00:14:36 +00:00
return;
}
2015-08-07 00:53:52 +00:00
refreshMessages();
2015-07-21 14:10:24 +00:00
});
});
2015-08-07 00:53:52 +00:00
2015-08-10 23:56:53 +00:00
socket.on('message:refresh', () => {
2015-08-07 00:53:52 +00:00
refreshMessages(socket);
});
2015-07-21 14:10:24 +00:00
});
};