0

What is the right way to redirect from within a keystone.js view?

I have this use case:

//req, res are the express request and response objects defined earlier
view.on('init', function(next){
 if (req.params['should-be-else-where']='true'{
    // do some logging stuff 
    // redirect to somewhere else
  }
});

as I understand the next param in the view.on() function is a callback for the async.js framework, and does not relate to the (req,res,next) middleware.

Should I call res.redirect('/somewhere-else) and then call next(), then call next() with a non-null error parameter, or should redirection be performed somewhere completely different?

Additional info: I'd like to stop processing because there is no reason to do the performance heavy database processing that following later in the queue

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Arjan
  • 1,034
  • 8
  • 29

1 Answers1

1

If you don't need a View but only redirect if the condition was met, you could do it like this:

module.exports = function (req, res, next) {

    if (req.params['should-be-else-where']) {
        // do some logging stuff 
        res.redirect('/somewhere-else');
    } else {
        var view = new keystone.View(req, res);
        // do something else then render the view
    }

}
Rudi
  • 2,987
  • 1
  • 12
  • 18
  • This topic is also nicely discussed here https://github.com/keystonejs/keystone/issues/303 with some other tips on Redirections in KeystoneJS. – exmaxx Apr 29 '16 at 16:42