Question

I´m trying associate a method or a property on a app object in kraken.js application, like follows:

controllers/index.js

'use strict';

var IndexModel = require('../models/index');


module.exports = function (app) {

    var model = new IndexModel();
    app.get('/', function (req, res) {
        console.log(app.adventurer);
        /* Console should be showing "Bilbo Bagins", but I'm getting 'undefined'.
         * See the next source file. */
        res.render('index', model);        
    });

};

/index.js

var kraken = require('kraken-js'),
    app = {
        adventurer: 'Bilbo Bagins'
    };


app.configure = function configure(nconf, next) {
    // Async method run on startup.
    next(null);
};


app.requestStart = function requestStart(server) {
    // Run before most express middleware has been registered.
};


app.requestBeforeRoute = function requestBeforeRoute(server) {
    // Run before any routes have been added.
};


app.requestAfterRoute = function requestAfterRoute(server) {
    // Run after all routes have been added.
};


if (require.main === module) {
    kraken.create(app).listen(function (err) {
        if (err) {
            console.error(err.stack);
        }
    });
}


module.exports = app;

Also, i´ve tried publish the property on /config/app.json

Any Thoughts?

Was it helpful?

Solution

Simply add the following key to .config/app.json or make a new .config/app-development.json:

"adventurer": "bilbo"

app.json will look like this:

{
//blah
//blah
"adventurer": "bilbo"
}

and then in ./index.js do this in configure:

app.configure = function configure(nconf, next) {
    // Async method run on startup.
    next(null);
    console.log('my traveler is: ', nconf.get('adventurer'));
};

In response to your comment, if you want to get an app config from the ./controllers/index.js then require the nconf lib and use nconf.get like so:

'use strict';
var nconf = require('nconf');

var IndexModel = require('../models/index');

module.exports = function (app) {

    var model = new IndexModel();

    //or attach it directly to the app object like so
    app.set('adventurer', nconf.get('adventurer'));
    console.log('adventurer directly set on app object', app.get('adventurer'));

    console.log('controller with app adventurer:', nconf.get('adventurer'));

    app.get('/', function (req, res) {

        res.render('index', model);

    });

};

Fire it up with npm start and watch the console. Peace!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top