I want to split my routes into different files, where one file contains all the routes and the other contains the corresponding actions. I currently have a solution to achieve this, however I need to make the global instance of the application available to 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);
Controllers / index.js:
exports.posts = require('./posts'); exports.index = function(req, res) {
Controllers / posts.js:
exports.index = function(req, res) {
However, this setup has a big problem: I have a database and an instance application that I need to pass to actions (controllers / *. Js). The only option I could think of was to make both variables global, which is not really a solution. I want to separate routes from activities because I have many routes and you want them in a central place.
What is the best way to pass variables into actions, but separate actions from routes?
Claudio Albertin Apr 10 2018-12-12T00: 00Z
source share