Search code examples
meteorroutesiron-router

dynamic query object for iron-router route


I have a current route as follows:

Router.route('/:arg',   function(){
    this.render('tmpResults', {
        data:   function(){
            return hcDrefs.find({name: {$regex: this.params.query.q}})
        }
    });
}, {name: 'showSome'});

As you can see, the query is hard coded to really only take a single input (see block below). What I want to do is execute this route where the query object would need to be of a variable form...sometimes I only need a simple query, other times, the query may contain an AND operation. I currently call this route with:

    Router.go('showSome', {arg: 1},
              {query: '?q=' + e.target.value});
}

...what I want to know is if I can pass some kind of query object to the route somehow, but I haven't seem to hit on a syntax that work....not even sure IF it can work. I have tried some brute force stuff like defining a query object:

query_object = {name: {$regex: pattern}}

and attempting to get it to the router somehow like:

    Router.go('showSome', {arg: 1},
              {query: query_object});
}
//----------------------------------------------------------
    Router.route('/:arg',   function(){
        this.render('tmpResults', {
            data:   function(){
                return hcDrefs.find(this.params.query.q}})
            }
        });
    }, {name: 'showSome'});

but that seems to be a no go.

What would be a good way to set the data context of a route where the query to yield the data context could be of a variable form? I would think a global object would probably work, but I am curious is there is a more strategic way passing through the router. I am still digging through the iron router docs for something I can hook onto.


Solution

  • There is no client-side POST, so the data you can pass to a client-side route is limited by what you can put into the URL (similar to a GET request). So, no, I don't think there is a more elegant solutions.

    I think you have two options:

    1. Stringifying your object into the URL:
    Router.go('showSome', {arg: 1},
              {query: JSON.stringify(query_object)});
    
    //----------------------------------------------------------
    
    Router.route('/:arg',   function(){
       this.render('tmpResults', {
           data:   function(){
               return hcDrefs.find(JSON.parse(this.params.query)}})
           }
       });
    }, {name: 'showSome'});
    

    2) use a global or session variable:

    Session.set('query', query_object);
    Router.go('showSome', {arg: 1});
    //----------------------------------------------------------
    
    Router.route('/:arg',   function(){
        this.render('tmpResults', {
            data:   function(){
                return hcDrefs.find(Session.get('query'))}})
            }
        });
    }, {name: 'showSome'});