ChatManager.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. ChatManager = class ChatManager {
  2. /**
  3. * Constructor.
  4. *
  5. * @param {Collection} chats
  6. * A Chats collection instance.
  7. */
  8. constructor(chats) {
  9. this.chats = chats;
  10. }
  11. /**
  12. * Order two comparable objects as min, max
  13. *
  14. * @param {Object} s1
  15. * @param {Object} s2
  16. * @returns {*[]}
  17. * An array of the two objects, minimum first, maximum last.
  18. */
  19. static ordered(s1, s2) {
  20. let id1;
  21. let id2;
  22. // Ensure ordering as id1 <= id2. Equality should not happen, but handle it correctly nonetheless.
  23. if (s1 <= s2) {
  24. id1 = s1;
  25. id2 = s2;
  26. }
  27. else {
  28. id1 = s2;
  29. id2 = s1;
  30. }
  31. return [id1, id2];
  32. }
  33. /**
  34. * Find the id of a chat between two users.
  35. *
  36. * @param {String} myId
  37. * The current user id.
  38. * @param {String} otherUserId
  39. * The id of an other user.
  40. * @param {Session} session
  41. * The session global.
  42. *
  43. * @returns {void}
  44. */
  45. assignChatId(myId, otherUserId, session) {
  46. let [user1Id, user2Id] = ChatManager.ordered(myId, otherUserId);
  47. // Since ids are ordered, we do not need a $or.
  48. const chat = this.chats.findOne({ user1Id, user2Id });
  49. // Meteor._debug(filter, chat);
  50. // No chat matching the filter - need to insert a new one.
  51. if (!chat) {
  52. Meteor.call("chats.insert", { user1Id, user2Id }, function (err, chatId) {
  53. if (err) {
  54. throw new Meteor.Error("access-denied", "Could not insert new chat.");
  55. }
  56. session.set("chatId", chatId);
  57. console.log("--- No chat found between " + user1Id + " and " + user2Id + ". Created " + chatId);
  58. });
  59. }
  60. // There is a chat going already - use that.
  61. else {
  62. const chatId = chat._id;
  63. session.set("chatId", chatId);
  64. console.log("--- Chat " + chatId + " found between " + user1Id + " and " + user2Id + ".");
  65. }
  66. }
  67. };