Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing config variables from other config files

Tags:

sails.js

I am having problems using in a config file a config var set in another config file. E.g.

// file - config/local.js
module.exports = {
  mongo_db : {
    username : 'TheUsername',
    password : 'ThePassword',
    database : 'TheDatabase'
  }
}

// file - config/connections.js
module.exports.connections = {
  mongo_db: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    user: sails.config.mongo_db.username,
    password: sails.config.mongo_db.password,
    database: sails.config.mongo_db.database
  },
}

When I 'sails lift', I get the following error:

user: sails.config.mongo_db.username,
      ^
ReferenceError: sails is not defined

I can access the config variables in other places - e.g, this works:

// file - config/bootstrap.js
module.exports.bootstrap = function(cb) {
  console.log('Dumping config: ', sails.config);
  cb();
}

This dumps all the config settings to the console - I can even see the config settings for mongo_db in there!

I so confuse.

like image 996
onblur Avatar asked Sep 02 '14 12:09

onblur


1 Answers

You can't access sails inside of config files, since Sails config is still being loaded when those files are processed! In bootstrap.js, you can access the config inside the bootstrap function, since that function gets called after Sails is loaded, but not above the function.

In any case, config/local.js gets merged on top of all the other config files, so you can get what you want this way:

// file - config/local.js
module.exports = {
  connections: {
    mongo_db : {
      username : 'TheUsername',
      password : 'ThePassword',
      database : 'TheDatabase'
    }
  }
}

// file - config/connections.js
module.exports.connections = {
  mongo_db: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017
  },
}

If you really need to access one config file from another you can always use require, but it's not recommended. Since Sails merges config files together based on several factors (including the current environment), it's possible you'd be reading some invalid options. Best to do things the intended way: use config/env/* files for environment-specific settings (e.g. config/env/production.js), config/local.js for settings specific to a single system (like your computer) and the rest of the files for shared settings.

like image 120
sgress454 Avatar answered Sep 28 '22 08:09

sgress454