|
@@ -0,0 +1,71 @@
|
|
|
+ChatManager = class ChatManager {
|
|
|
+
|
|
|
+ * Constructor.
|
|
|
+ *
|
|
|
+ * @param {Collection} chats
|
|
|
+ * A Chats collection instance.
|
|
|
+ */
|
|
|
+ constructor(chats) {
|
|
|
+ this.chats = chats;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * Order two comparable objects as min, max
|
|
|
+ *
|
|
|
+ * @param {Object} s1
|
|
|
+ * @param {Object} s2
|
|
|
+ * @returns {*[]}
|
|
|
+ * An array of the two objects, minimum first, maximum last.
|
|
|
+ */
|
|
|
+ static ordered(s1, s2) {
|
|
|
+ let id1;
|
|
|
+ let id2;
|
|
|
+
|
|
|
+ if (s1 <= s2) {
|
|
|
+ id1 = s1;
|
|
|
+ id2 = s2;
|
|
|
+ }
|
|
|
+ else {
|
|
|
+ id1 = s2;
|
|
|
+ id2 = s1;
|
|
|
+ }
|
|
|
+ return [id1, id2];
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * Find the id of a chat between two users.
|
|
|
+ *
|
|
|
+ * @param {String} myId
|
|
|
+ * The current user id.
|
|
|
+ * @param {String} otherUserId
|
|
|
+ * The id of an other user.
|
|
|
+ * @param {Session} session
|
|
|
+ * The session global.
|
|
|
+ *
|
|
|
+ * @returns {void}
|
|
|
+ */
|
|
|
+ assignChatId(myId, otherUserId, session) {
|
|
|
+ let [user1Id, user2Id] = ChatManager.ordered(myId, otherUserId);
|
|
|
+
|
|
|
+
|
|
|
+ const chat = this.chats.findOne({ user1Id, user2Id });
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ if (!chat) {
|
|
|
+ Meteor.call("chats.insert", { user1Id, user2Id }, function (err, chatId) {
|
|
|
+ if (err) {
|
|
|
+ throw new Meteor.Error("access-denied", "Could not insert new chat.");
|
|
|
+ }
|
|
|
+ session.set("chatId", chatId);
|
|
|
+ console.log("--- No chat found between " + user1Id + " and " + user2Id + ". Created " + chatId);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ else {
|
|
|
+ const chatId = chat._id;
|
|
|
+ session.set("chatId", chatId);
|
|
|
+ console.log("--- Chat " + chatId + " found between " + user1Id + " and " + user2Id + ".");
|
|
|
+ }
|
|
|
+ }
|
|
|
+};
|