我在游戏中有点晚了,但我在这里或其他地方都找不到我需要的东西,所以我自己写了一些东西。
我对配置机制的要求如下:
支持前端。如果前端不能使用该配置有什么意义?
支持settings-override .js -看起来一样,但允许重写settings.js中的配置。这里的思想是在不更改代码的情况下轻松修改配置。我发现它对saas很有用。
尽管我不太关心支持环境,但它将解释如何轻松地将其添加到我的解决方案中
var publicConfiguration = {
"title" : "Hello World"
"demoAuthToken" : undefined,
"demoUserId" : undefined,
"errorEmail" : null // if null we will not send emails on errors.
};
var privateConfiguration = {
"port":9040,
"adminAuthToken":undefined,
"adminUserId":undefined
}
var meConf = null;
try{
meConf = require("../conf/dev/meConf");
}catch( e ) { console.log("meConf does not exist. ignoring.. ")}
var publicConfigurationInitialized = false;
var privateConfigurationInitialized = false;
function getPublicConfiguration(){
if (!publicConfigurationInitialized) {
publicConfigurationInitialized = true;
if (meConf != null) {
for (var i in publicConfiguration) {
if (meConf.hasOwnProperty(i)) {
publicConfiguration[i] = meConf[i];
}
}
}
}
return publicConfiguration;
}
function getPrivateConfiguration(){
if ( !privateConfigurationInitialized ) {
privateConfigurationInitialized = true;
var pubConf = getPublicConfiguration();
if ( pubConf != null ){
for ( var j in pubConf ){
privateConfiguration[j] = pubConf[j];
}
}
if ( meConf != null ){
for ( var i in meConf ){
privateConfiguration[i] = meConf[i];
}
}
}
return privateConfiguration;
}
exports.sendPublicConfiguration = function( req, res ){
var name = req.param("name") || "conf";
res.send( "window." + name + " = " + JSON.stringify(getPublicConfiguration()) + ";");
};
var prConf = getPrivateConfiguration();
if ( prConf != null ){
for ( var i in prConf ){
if ( prConf[i] === undefined ){
throw new Error("undefined configuration [" + i + "]");
}
exports[i] = prConf[i];
}
}
return exports;
解释
undefined means this property is required
null means it is optional
meConf - currently the code is target to a file under app. meConf is the overrides files which is targeted to conf/dev - which is ignored by my vcs.
publicConfiguration - will be visible from front-end and back-end.
privateConfiguration - will be visible from back-end only.
sendPublicConfiguration - a route that will expose the public configuration and assign it to a global variable. For example the code below will expose the public configuration as global variable myConf in the front-end. By default it will use the global variable name conf.
app.get("/backend/conf", require("conf").sendPublicConfiguration);
覆盖逻辑
privateConfiguration与publicConfiguration和meConf合并。
publicConfiguration检查每个键是否有覆盖,并使用该覆盖。这样我们就不会暴露任何隐私。
添加环境支持
即使我不觉得“环境支持”有用,也许有人会。
要添加环境支持,您需要将meConf require语句更改为以下内容(伪代码)
If (environment == "production") {
meConf = require("../conf/dev/meConf").production;
}
If (environment == "development") {
meConf = require("../conf/dev/meConf").development;
}
类似地,每个环境可以有一个文件
meConf.development.js
meConf.production.js
然后导入正确的。
其余的逻辑保持不变。