Reputation: 6242
My project directory looks something like this:
MyProject
-app.js
-routes
-routeone
-routetwo
Inside of my app.js file it looks like this:
var express = require('express');
var app = express();
var myModule= require('myModule');
app.use(myModule());
var routeone = require('./routes/routeone');
var routetwo = require('./routes/routetwo');
app.use('/routeone', routeone);
app.use('/routetwo', routetwo);
.
.
.
Each route file looks something like this:
var express = require('express');
var router = express.Router();
router.post('/', urlencodedParser, function(req, res, next) {
//Need to call myModule's createUser function. How do I call it here?
});
module.exports = router;
As you can see I have a dependency on the myModule module. I need to call a function in this module in every route.I may have many more routes in the future. I would like to avoid specifying this (calling require) in every single route file because in the future if I have hundreds of route and say the module now accepts options I would need to to every single file and since this manually. Is there a way to require it once (e.g in the app.js file) and then be able to use it everywhere?
Upvotes: 1
Views: 428
Reputation: 2691
You can write your route modules as such that during the time of creation(require call
) they get their dependencies injected. I have added a sample below
route.js
module.exports = function(myModule, router, dep1, dep2){
router.post()
//use my module, dep1 and dep2
}
app.js
var mymodule = require('./myModule')
var dep1 = require('./dep1');
var dep2 = require('./dep2');
var router = express.Router();
var route = require('route')(mymodule, router, dep1, dep2);
route.js
module.exports = function(myModule, dep1, dep2){
router.post()
//other router invocations
return router
}
In app.js
var customRouter = require('route')(mymodule, router, dep1, dep2);
the customRouter will be an router instance since thats what is being returned by te invoked function in route.js
Upvotes: 2