Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to call express routes from another?

I have a route that could do many different things. For example:

A route file:

exports.index = function (req, res) {
    if (x)
        exports.login(req,res);
    else
        exports.dostuff(req,res);
};

exports.login = function(req, res) {
    res.render('login');
};

exports.dostuff = function(req, res) { 
    res.render('otherfile');
};

Is this bad practice? Is there a better way of going about such a situation? Thanks.

like image 635
Ryan Endacott Avatar asked Dec 18 '12 02:12

Ryan Endacott


1 Answers

Well this is not a bad practice but also not the most suited one for this situation.

You could do something like this to achieve better routing solution.

  • Configure your routes in the router file and handle your behaviours in a specific controller.

E.g something like this. (router.js)

//First requiring your controller for actions
var jobController = require("../controllers/job_controller");

module.exports = function(app) {

    app.get("/jobs", jobController.getJobIndex);
    app.get("/jobs/create", jobController.createJobView);
    app.get("/jobs/update/:id", jobController.updateJobView);
    app.get("/jobs/delete/:id", jobController.deleteJob);
    app.get("/jobs/:id", jobController.getJobDetails);

    app.post("/jobs/create", jobController.createJobPost);
    app.post("/jobs/update", jobController.updateJobPost);

};

And require the router.js in your main app.js

var router = require('./routes/router')(app)
like image 55
Serdar Dogruyol Avatar answered Oct 01 '22 16:10

Serdar Dogruyol