Last active
August 29, 2015 14:01
-
-
Save joaoneto/a0742837dd3f2eb1484f to your computer and use it in GitHub Desktop.
Config with dot getter and setter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DEVELOPMENT | |
module.exports = exports = { | |
"db": { | |
"connection1": { | |
"driver": "mongodb", | |
"url": "mongodb://localhost:27017/database_dev" | |
}, | |
"connection2": { | |
"driver": "redis", | |
"url": "redis://localhost" | |
} | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var env = process.env.NODE_ENV || 'development'; | |
var _parseKeys = function (str) { | |
if (/\./.test(str)) return str.split('.'); | |
return; | |
}; | |
var _getter =function (key, obj) { | |
var keys = _parseKeys(key); | |
if (keys) return _getter(keys.slice(1), obj[keys[0]]); | |
return obj[key]; | |
}; | |
var _setter = function (key, val, obj) { | |
var keys = _parseKeys(key); | |
if (keys) { | |
if (!obj[keys[0]] || typeof obj[keys[0]] !== 'object') { | |
obj[keys[0]] = {}; | |
} | |
return _setter(keys.slice(1), val, obj[keys[0]]); | |
} | |
obj[key] = val; | |
return; | |
}; | |
var config = module.exports = exports = require('./' + env); | |
config.env = env; | |
config.get = function (key) { | |
return _getter(key, this); | |
}; | |
config.set = function (key, val) { | |
_setter(key, val, this); | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment