node.jsexpressknox-amazon-s3-client

Pass configuration to controller


I am building a node.js app that will upload files to my S3 bucket using knox. I am able to interact with S3 as expected, but I would like to make my controller to receive configuration so I can dynamically construct my client with configuration values.

My questions is how do I get configuration paramters down the call stack to my controller without being careless?

Disclaimer: I am rather new to Node.js so it could be simply my lack of knowledge in the difference between exports. and module.exports.*

Here is an example of how the interaction works with my code:

app.js

...
config = require('./config/config')['env'];
require('./config/router')(app, config);
...

router.js

module.exports = function(app, config) {
...
  var controller = require('../app/controllers/home'); //Is there a way for me to pass config here?
  app.post('/upload', controller.upload); //Or here?
...
}

home.js

var knox = require('knox');

var client = knox.createClient({ ... }); //I want to use config.key, config.secret, etc instead of hard-coded values
...
exports.upload = function(req, res) {
  //Use client
}
...

Solution

  • Try doing something like this...

    var config = require('./config/config')['env'];
    
    // The use function will be called before your 
    //  action, because it is registered first.
    app.use(function (req, res, next) {
    
      // Assign the config to the req object
      req.config = config;
    
      // Call the next function in the pipeline (your controller actions).
      return next();
    
    });
    
    // After app.use you register your controller action
    app.post('/upload', controller.upload); 
    

    And then in your controller action...

    exports.upload = function(req, res) {
    
      //Your config should be here...
      console.log(req.config);
    
    }
    

    Ps. I can not try it right now, but I solved a similar issue like this.