routes.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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("Routing 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");
  16. return Meteor.subscribe("chats");
  17. },
  18. action: function (req, wtf, func) {
  19. Meteor._debug("Action", req.url);
  20. if (this.ready()) {
  21. console.log("- Now ready");
  22. // The user they want to chat to has id equal to the id sent in after /chat/...
  23. const otherUserId = this.params._id;
  24. // find a chat that has two users that match current user id
  25. // and the requested user id
  26. const filter = {
  27. $or: [
  28. {
  29. user1Id: Meteor.userId(),
  30. user2Id: otherUserId
  31. },
  32. {
  33. user2Id: Meteor.userId(),
  34. user1Id: otherUserId
  35. }
  36. ]
  37. };
  38. const chat = Chats.findOne(filter);
  39. // Meteor._debug(filter, chat);
  40. // No chat matching the filter - need to insert a new one.
  41. let chatId;
  42. if (!chat) {
  43. chatId = Chats.insert({
  44. user1Id: Meteor.userId(),
  45. user2Id: otherUserId
  46. });
  47. console.log("--- No chat found between " + Meteor.userId() + " and " + otherUserId + ". Created " + chatId);
  48. }
  49. // There is a chat going already - use that.
  50. else {
  51. chatId = chat._id;
  52. console.log("--- Chat " + chatId + " found between " + Meteor.userId() + " and " + otherUserId + ".");
  53. }
  54. // Looking good, save the id to the session.
  55. if (chatId) {
  56. Session.set("chatId", chatId);
  57. }
  58. this.render("navbar", { to: "header" });
  59. this.render("chat_page", {
  60. to: "main",
  61. data: function () {
  62. const other = Meteor.users.findOne({ _id: otherUserId });
  63. console.log("--- Routing data, other: " + (other ? other.profile.username : "not available"));
  64. return {
  65. other: other
  66. };
  67. }
  68. });
  69. }
  70. else {
  71. console.log("- Not yet ready");
  72. this.render("Loading");
  73. }
  74. }
  75. });