How to define global application variables that are accessible from all mojit controllers and any middleware?

As the topic title states, I would like to define a variable that is available everywhere in my Mojito app, be it in JS files that will serve as middleware or the mojit controllers.

Based on the Mojito documentation it appears that Addons would be one option, i.e. the variables would be attached to the ActionContext object, however that object is not accessible in the middleware. What is the right way to do this?

Thanks a lot!

  • BL
  • Oct 1, 2012
1 Reply
  • I see that you posted this question a long time ago. However, I had the same question and hacked out an answer. Here's what I've got. I don't like the answer because it uses a "private" value; however, I really wanted this functionality.

    1. Configure your application as you would just as if it were a normal mojito app in the application.json file.
    2. Add YCB to your application

      npm install ycb --save
    3. Put your middleware some place nice. I put mine in the recommended <app>/middleware subdirectory as "recommended" by Extending Mojito / Middleware / Location of Middleware.
    4. Require ycb in your middleware file and get the application.json loaded.

      var fs = require('fs')
        , ycb = require('ycb')
        , path = require('path')
        , configPath = path.join(__dirname, '../', 'application.json')
        , appConfigRaw = JSON.parse(fs.readFileSync(configPath, 'utf8'))
        , appConfig = new ycb.Ycb(appConfigRaw, {})
    5. Now, in your handler, you can hack the current context and get the resolved configuration for the mojito application. That use of req.app.store._config.context is what bothers me because I assume that _config is "private".

      module.exports = function (req, res, next) {
        var config = appConfig.read(req.app.store._config.context)
        // Do stuff with your config here, like look at the
        // assigned port with config.appPort
    6. Profit!

Recent Posts

in Yahoo! Mojito