Search code examples
node.jsexpresscontrollerroutesexpress-4

How to delegate route processing in express?


I have expressjs application with straitfort route processing like the following:

app.route('/').get(function(req, res, next) {
   // handling code;
});

app.route('/account').get(function(req, res, next) {
   // handling code;    
});

app.route('/profile').get(function(req, res, next) {
   // handling code;
});

At now I put all my code inside route handler but I want try to delegate it to some class such as the following.

app.route('/').get(function(req, res, next) {
   new IndexPageController().get(req, res, next);
});

app.route('/account').get(function(req, res, next) {
   new AccountPageController().get(req, res, next);
});

app.route('/profile').get(function(req, res, next) {
   new ProfilePageController().get(req, res, next);
});

So what do you thing about the approach above and meybe you know the better one?


Solution

  • As you can see in the Express Response documentation - the response (req) can send information to the client by a few methods. The easiest way is to use req.render like:

    // send the rendered view to the client
    res.render('index');
    

    Knowing this means that you can do whatever you want in another function, and at the end just call res.render (or any other method that sends information to the client). For example:

    app.route('/').get(function(req, res, next) {
       ndexPageController().get(req, res, next);
    });
    
    // in your IndexPageController:
    
    function IndexPageController() {
        function get(req, res, next) {
            doSomeDatabaseCall(function(results) {
                res.render('page', results);
            }
        }
    
        return {
            get: get
        }
    }
    // actually instantiate it here and so module.exports
    // will be equal to { get: get } with a reference to the real get method
    // this way each time you require('IndexPageController') you won't
    // create new instance, but rather user the already created one
    // and just call a method on it.
    module.exports = new IndexPageController();
    

    There isn't strict approach to this. You can pass the response and someone else call render. Or you can wait for another thing to happen (like db call) and then call render. Everything is up to you - you just need to somehow send information to the client :)