I have https server written in express js. And I added domains to my server. App.js file:
var d = require('domain').create();
d.on('error', function(error) {
console.error("Domain caught error: "+ error.stack);
});
d.run(function() {
var express = require('express');
var appServer = express();
var https = require('https').createServer(options, appServer);
https.listen(8000, function() {
log.info('Server is listening on port ' + 8000);
});
appServer.use(appServer.router);
var routes = require('./routes')(appServer); //my routes file
});
I have route handler functions in other files. How can I use domain created in my app.js file in my route files without exporting it from app.js file.
Update:
routes.js file:
var auth = require('./auth');
module.exports = function(app) {
app.namespace('/login', function(){
app.post('/user', auth.verifyUser);
});
};
auth.js file:
exports.verifyUser = function(req,res) {
//here I want to see my domain
};
You can pass it when you
requireyour routes:Then within your
routes/index.jsfile:Update
To update the answer based on the question update, here's a possible solution to include the
domainwithin each route definition. There are a couple ways to do this (you could make each route a class, which would be instantiated and passed thedomain, then have a function defined per route, for example). Because the intent is to keep these route definition signaturesfunction(req, res)as you've defined above forverifyUser, we're going to need to pass thedomainto this route prior to calling the function. Keeping this very simple, we can do just that with asetDomainfunction:Same code in your main
index.jswhen yourequireyour routes:In your
routes.js, you can pass thedomainto the routes via thesetDomainfunction:Finally, in your
auth.jsfile, you can get the domain, and have access to it within the scope of the file to use it in theverifyUserfunction:I'm not sure I really like this solution, but again, it's keeping the signature the same for
verifyUser. Maybe you'll think of a better one, or want to refactor your code to better make use of this domain you're passing around within your code (maybe define it somewhere else and pull it from there wherever it's needed).