Reputation: 391
Having started working with express recently I have stumbled across the following problem:
The entire logic of my routes is defined in separate files which are then included by means of require(route_name). The respective get / post matches are done as follows:
app.get('/', routes.home) etc.
The line above implies that routes.home is a function called with the parameters req, res & next.
I have a bunch of utility functions stored in the utils object that I want every route to be able to access. Until now, I've been solving the problem as follows:
var utils = ...
app.get('/', function (req, res, next) {
routes.home(req, res, next, utils);
});
Is there a way to tell express that it should pass the utils object as a parameter to every route or generally a better solution to my problem?
Upvotes: 1
Views: 2416
Reputation: 391
Thanks for all the answers. I've found a solution to my problem by calling an "init(utils)" function on routes I want to have to the utils module.
Upvotes: 0
Reputation: 1810
I agree with JohnnyHK. And also why do you need to pass res and req twice? Why not do this in your app file:
app.get('/', routes.home);
And then in your required file something like this:
var utils = require('utils')
exports.home = function(req, res){
//code
}
Upvotes: 2