cybermach
cybermach

Reputation: 125

Reroute Express dynamically via next()

Does anybody know how to reroute a call dynamically in Express (Node.js)? My route conditionally diverges at some point and I would like to change the "next()" parameter somehow to do that.

For example, let's say I have the following routes:
route1 = func1, func2, func3
route2= func4, func5

I'd like the following flow to occur:
func1 => func2 (reroute to route2 if Android) => func4 => func5
func1 => func2 (don't reroute if iOS) => func3

I considered res.redirect(/route2), but I'd like the reroute to occur internally without the client-side knowing about it.

Any help is appreciated,

Thanks!
Henri

Upvotes: 0

Views: 51

Answers (1)

cybermach
cybermach

Reputation: 125

I ended up using async.waterfall to address my issue in a rather clean way. For those running into the same problem and wanting to reuse existing functions used by other routes, you can use async.waterfall and use "cb" for the "next" parameter as such:

 conditionalReroute: function(req, res, next) {

      if(someCondition) {
        async.waterfall([
                         function(cb){route1.someFunction(req, res, cb); }, 
                         function(cb){ route2.someOtherFunction(req, res, cb); }, 
                         function(cb){ route1.soomeFunction2(req, res, cb); }, 
                         }
                    ]);

      } else {
          next();
      } 
}

Upvotes: 0

Related Questions