Last active
August 29, 2015 14:02
-
-
Save bodokaiser/59019e2f18b75751da2c to your computer and use it in GitHub Desktop.
Setup environment based configuration with path support.
This file contains 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 path = require('path'); | |
/** | |
* Your configuration may look like: | |
* | |
* { | |
* "name": "my-app", | |
* "static": { | |
* "path": "/public" | |
* } | |
* } | |
* | |
* Note you may need to adjust paths to match your directory structure! | |
*/ | |
// app is an instance of express or koa | |
module.exports = function(app) { | |
// merge the default configuration | |
merge(app, require('../../etc/configuration')); | |
// merge env-based configuration (can overwrite default) | |
if (app.env === 'production') { | |
merge(app, require('../../etc/production')); | |
} | |
if (app.env === 'development') { | |
merge(app, require('../../etc/development')); | |
} | |
if (app.env === 'test') { | |
merge(app, require('../../etc/testing')); | |
} | |
// lets update all relative paths to absolute | |
each(app, resolve); | |
}; | |
function each(object, callback) { | |
Object.keys(object).forEach(function(key) { | |
callback(object[key], key, object); | |
}); | |
} | |
function merge(source, object) { | |
each(object, function(value, key) { | |
if (Object(value) !== value || Array.isArray(value)) { | |
source[key] = value; | |
} else { | |
source[key] = source[key] || {}; | |
merge(source[key], value); | |
} | |
}); | |
} | |
function resolve(value, key, source) { | |
// if we have a string beginning with "/" we propably have a | |
// relative path which we need to update | |
if (typeof value === 'string' && value.startsWith('/')) { | |
source[key] = path.join(__dirname + '/../../', value); | |
} | |
// iterate on arrays and object to resolve all (nested) paths | |
if (typeof value === 'object') { | |
if (Array.isArray(value)) { | |
value.forEach(resolve); | |
} else { | |
each(value, resolve); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment