From e9e85036d55897d904fcba1ba8ede26f8f75de0b Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Fri, 7 Aug 2015 01:53:52 +0100 Subject: [PATCH] Added delete message method --- db/models/message.js | 1 - lib/chat/controller.js | 33 +++++++++++++++++++++++++++------ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/db/models/message.js b/db/models/message.js index c4783e9..32f7f8d 100644 --- a/db/models/message.js +++ b/db/models/message.js @@ -33,7 +33,6 @@ messageSchema.methods.toJson = function () { }; }; - messageSchema.statics.list = function (options, callback) { return this.find({deleted: false}).sort({createdAt: -1}).limit(30).exec(callback); }; diff --git a/lib/chat/controller.js b/lib/chat/controller.js index 7052506..b0417be 100644 --- a/lib/chat/controller.js +++ b/lib/chat/controller.js @@ -10,6 +10,7 @@ * Client API * message:new - New message has been created * message:refresh - Retrieve most recent messages + * message:delete - Deletes message by ID (Admin only) * */ @@ -22,6 +23,21 @@ module.exports = function (namespace) { namespace.emit("message:new", message.toJson()); }; + var refreshMessages = function (socket) { + Message.list({}, function (error, messages) { + if (error) { + winston.error("Unable to retrieve messages. Error:", error); + return; + } + + var receiver = (socket === undefined) ? namespace : socket; + + receiver.emit("message:refresh", { + chatHistory: messages + }); + }); + }; + namespace.on('connection', function (socket) { socket.on('message:new', function (data) { @@ -40,16 +56,21 @@ module.exports = function (namespace) { }); }); - socket.on('message:refresh', function () { - Message.list({}, function (error, messages) { + socket.on('message:delete', function (data) { + var id = data.id; + if (id === undefined || !socket._user.admin) return; + + Message.remove({_id: id}, function (error) { if (error) { - winston.error("Unable to retrieve messages. Error:", error); + winston.error("An error occurred when trying to delete message:", error); return; } - socket.emit("message:refresh", { - chatHistory: messages - }); + refreshMessages(); }); }); + + socket.on('message:refresh', function () { + refreshMessages(socket); + }); }); };