routes.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. Meteor.subscribe("users");
  2. // set up the main template the the router will use to build pages
  3. Router.configure({
  4. layoutTemplate: "ApplicationLayout"
  5. });
  6. // specify the top level route, the page users see when they arrive at the site
  7. Router.route("/", function () {
  8. console.log("rendering root /");
  9. this.render("navbar", { to: "header" });
  10. this.render("lobby_page", { to: "main" });
  11. });
  12. // specify a route that allows the current user to chat to another users
  13. Router.route("/chat/:_id", {
  14. subscriptions: function () {
  15. Meteor._debug('subscriptions', arguments);
  16. return Meteor.subscribe("chats");
  17. },
  18. action: function () {
  19. Meteor._debug('action', arguments);
  20. if (this.ready()) {
  21. Meteor._debug("Ready");
  22. // the user they want to chat to has id equal to
  23. // the id sent in after /chat/...
  24. const otherUserId = this.params._id;
  25. // find a chat that has two users that match current user id
  26. // and the requested user id
  27. const filter = {
  28. $or: [
  29. {
  30. user1Id: Meteor.userId(),
  31. user2Id: otherUserId
  32. },
  33. {
  34. user2Id: Meteor.userId(),
  35. user1Id: otherUserId
  36. }
  37. ]
  38. };
  39. const chat = Chats.findOne(filter);
  40. Meteor._debug(filter, chat);
  41. // No chat matching the filter - need to insert a new one.
  42. let chatId;
  43. if (!chat) {
  44. chatId = Chats.insert({
  45. user1Id: Meteor.userId(),
  46. user2Id: otherUserId
  47. });
  48. Meteor._debug("No chat found between " + Meteor.userId() + " and " + otherUserId + ". Created " + chatId);
  49. }
  50. // There is a chat going already - use that.
  51. else {
  52. chatId = chat._id;
  53. Meteor._debug("Chat " + chatId + " found between " + Meteor.userId() + " and " + otherUserId + ".");
  54. }
  55. // Looking good, save the id to the session.
  56. if (chatId) {
  57. Session.set("chatId", chatId);
  58. }
  59. this.render("navbar", { to: "header" });
  60. this.render("chat_page", { to: "main" });
  61. }
  62. else {
  63. Meteor._debug('not ready');
  64. this.render("Loading");
  65. }
  66. }
  67. });