Ryan Endacott
Ryan Endacott

Reputation: 9172

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.

Upvotes: 5

Views: 5625

Answers (1)

Serdar Dogruyol
Serdar Dogruyol

Reputation: 5157

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)

Upvotes: 10

Related Questions