Skip to content

Instantly share code, notes, and snippets.

@albertosouza
Last active August 29, 2015 14:05
Show Gist options
  • Save albertosouza/4b4e05e7fa49e6cb73cd to your computer and use it in GitHub Desktop.
Save albertosouza/4b4e05e7fa49e6cb73cd to your computer and use it in GitHub Desktop.
Sails.js config getter funcion

If i try to get one sub depth attribute in sails.config and a sub attribute dont exists it will return a error but if i have a getter it can return a undefined even if a sub attribute dont exists

This is a good feature to core or is best to write a npm module (sails.utils.extra?) and plug this helpers with hook or bootstrap function?

May be something like:

/**
 * Get one sails.js config getter
 * 
 * Use it for get one depth config withouth undefined error if one sub 
attrib dont exist
 * 
 * @param  {string} configString Sails.js config to get ex.: sails.config.port
 * @return {Object|Array|String|undefined} config value or undefined
 */
sails.getConfig = function(s){
  // with try and catch to be easy to read
    var o = sails.config;

    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    while (a.length) {
        var n = a.shift();
        if (n in o) {
            o = o[n];
        } else {
            return;
        }
    }
    return o;
  }
}

Example If sails.config.email === undefined :

// will throw a error
var provider = sails.config.email.provider.default;

//but if have one getter it can return a error
var provider = sails.getConfig('email.provider.default');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment