Selaa lähdekoodia

Task 2: implement data writing security.

Frederic G. MARAND 9 vuotta sitten
vanhempi
sitoutus
b5da57708c
3 muutettua tiedostoa jossa 44 lisäystä ja 17 poistoa
  1. 3 16
      client/chat_page.js
  2. 39 0
      lib/ChatManager.js
  3. 2 1
      shared/methods.js

+ 3 - 16
client/chat_page.js

@@ -18,24 +18,11 @@ Template.chat_page.events({
     // see if we can find a chat object in the database
     // to which we'll add the message
     const chat = Chats.findOne({ _id: Session.get("chatId") });
-    if (chat) {// ok - we have a chat to use
-      let msgs = chat.messages; // pull the messages property
-      if (!msgs) {// no messages yet, create a new array
-        msgs = [];
-      }
-      // is a good idea to insert data straight from the form
-      // (i.e. the user) into the database?? certainly not.
-      // push adds the message to the end of the array
-      msgs.push({
-        text: event.target.chat.value,
-        sender: Meteor.userId()
-      });
+    if (chat) {
+      // OK - we have a chat to use.
+      Meteor.call("chats.pushMessage", chat, event.target.chat.value);
       // reset the form
       event.target.chat.value = "";
-      // put the messages array onto the chat object
-      chat.messages = msgs;
-      // update the chat object in the database.
-      Chats.update(chat._id, chat);
     }
   }
 });

+ 39 - 0
lib/ChatManager.js

@@ -71,6 +71,14 @@ ChatManager = class ChatManager {
     }
   }
 
+  /**
+   * Meteor Method: insert a chat.
+   *
+   * @param {Object} chat
+   *   A chat object, with user1Id, user2Id, and messages keys.
+   * @returns {String}
+   *   The id of the inserted chat document.
+   */
   static insertMethod(chat) {
     check(chat, {
       user1Id: String,
@@ -81,4 +89,35 @@ ChatManager = class ChatManager {
     // Meteor._debug("chats.insert", chat, chatId);
     return chatId;
   }
+
+  /**
+   * Meteor Method: push a message to a chat.
+   *
+   * @param {Object} chat
+   *   A chat object, with user1Id, user2Id, and messages keys.
+   * @param {String} chatValue
+   *   The message to push.
+   */
+  static pushMessageMethod(chat, chatValue) {
+    check(chat, {
+      _id: String,
+      user1Id: String,
+      user2Id: String,
+      messages: Array
+    });
+
+    // is a good idea to insert data straight from the form
+    // (i.e. the user) into the database?? certainly not.
+    // push adds the message to the end of the array
+    const changes = {
+      $push: {
+        messages: {
+          text: chatValue,
+          sender: this.userId
+        }
+      }
+    };
+    // update the chat object in the database.
+    Chats.update(chat._id, changes);
+  }
 };

+ 2 - 1
shared/methods.js

@@ -1,3 +1,4 @@
 Meteor.methods({
-  "chats.insert": ChatManager.insertMethod
+  "chats.insert": ChatManager.insertMethod,
+  "chats.pushMessage": ChatManager.pushMessageMethod
 });