Iron-router base route and users routes

78 Views Asked by At

Currently i'm building a social network with Meteor.js, and faced a routing problem. Thats the required router behavior:

  1. On '/', if user is not logged, redirects to a langing page with login.
  2. On '/', if user is logged in, grabs his username and redirects to a profile page by '/:username'
  3. On '/:username', grabs a user by a passed username and renders his profile

Thats my solution:

Router.map ->

  @route 'base', 

    path: '/'

    waitOn: ->
      waitOnUser()

    action: ->

      say 'base route'
      user = Meteor.user()

      if user? 

        say 'redirecting to username from base route'
        username = user.profile.username
        @redirect '/user/' + username

      else

        @redirect 'hello'

  @route 'profile', {

    path: 'user/:username'
    layoutTemplate: 'mainLayout'
    template: 'profileLayout'

    waitOn: ->

      [ 
        waitOnUser(),
        Meteor.subscribe('pageOwner', @params.username)
      ]

    onBeforeAction: ->

      Session.set('profileOwner', Meteor.users.findOne({'profile.username': @params.username}))
      @next()

    data: ->

      if @ready()

        user = Meteor.users.findOne({'profile.username': @params.username})
        profile = user.profile
        id = user._id
        owner = Meteor.user().profile.username is profile.username
        {
          profile: profile
          userId: id
          owner: owner
        }

    action: ->

      @render()

waitOnUser = ->

  user = Meteor.user()

  handle = 

    ready: ->

      if user?
        true
      else
        false

The problem is that base route works everytime the '/:username' is called and redirects to a logged in users home page, so that becomes impossible to watch some other users page.

Can you please suggest some better solution for my case?

1

There are 1 best solutions below

0
On BEST ANSWER

Found the solution, just need to change the order of routes definitions, so that 'profile' route gets called before 'base'