3

I use totally default Kraken.js app.

I want to define some configs for .dust templates (select options) in a config.js file. Then I need to get these configs in my controller. How may I get a config in a controller? Here is an example code:

'use strict';
var Post = require('../../models/post');
var mongoose = require("mongoose");

// How to get config, for example, here??
var config = require(".....config.....")


module.exports = function (router) {


    // or how to get a config here as the third argument of a function, for example?
    router.get('/', function (req, res) {

        // Here I want to get data from config
        res.render('posts', {
            foo: config.foo,
            bar: config.selects.selectOne.bar
        });
    }
Green
  • 28,742
  • 61
  • 158
  • 247

2 Answers2

6

This question was duplicated at the krakenjs repo.

Assuming you're using Kraken < v1.0, configuration is handled by nconf. nconf, relying on node's module caching, provides a singleton. In other words, any time you include nconf, you'll get the exact same instance. For this reason, you can access the kraken config with something like the following:

var config = require('nconf');

var shouldHide = config.get('middleware:myModule:hideWidget');

if (shouldHide === true) {
  // ... do something ...
}

If, on the other hand, you are using kraken >= v1.0, kraken leverages confit for configuration. Since confit—by design—does not expose a singleton, it is recommended you attempt to deal with config entirely in the onConfig handler. Again, that is the recommended approach.

That said, there are certain instances where you can not handle all configuration during the init phase but, rather, at route resolution. For those times, we store the kraken config on the app instance as app.kraken. So, as long as you have access to your app instance, you have access to your config.

Here's an example of accessing that config from a route handler:

// ./routes/secure.js
'use strict';

module.exports = function (req, res) {
  var shouldHide = req.app.kraken.get('middleware:myModule:hideWidget');
  if (shouldHide === true) {
    // ... do something ...
  }
};
Jean-Charles
  • 366
  • 2
  • 11
1

You can add a config.json file, and import the "nconf" package from NPM.

var nconf = require('nconf');

nconf.env().file({ file: 'config.json' });

var adminUsername = nconf.get("ADMIN");

And in your config.json:

{
    "ADMIN": "Test",
}
Erik Elkins
  • 629
  • 5
  • 14