I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve this, however I need to make the app-instance global to be able to access it in the actions.
My current setup looks like this:
app.js:
var express = require('express');
var app = express.createServer();
var routes = require('./routes');
var controllers = require('./controllers');
routes.setup(app, controllers);
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
routes.js:
exports.setup = function(app, controllers) {
app.get('/', controllers.index);
app.get('/posts', controllers.posts.index);
app.get('/posts/:post', controllers.posts.show);
// etc.
};
controllers/index.js:
exports.posts = require('./posts');
exports.index = function(req, res) {
// code
};
controllers/posts.js:
exports.index = function(req, res) {
// code
};
exports.show = function(req, res) {
// code
};
However, this setup has a big issue: I have a database- and an app-instance I need to pass to the actions (controllers/*.js). The only option I could think of, is making both variables global which isn't really a solution. I want to separate routes from the actions because I have a lot of routes and want them in a central place.
What's the best way to pass variables to the actions but separate the actions from the routes?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…