我正在使用Confidence我的项目中用于配置管理的库(在 HapiJS 套件中)(此配置文件专门用于 WinstonJS 传输),我想知道是否可以为过滤对象中的单个项目设置默认值。我不确定我的解释是否正确,我不确定正确的术语是什么,所以这里有一个例子:
我的配置设置的一部分目前如下所示:
module.exports = {
$filter: 'env',
development: {
level: {
console: 'debug',
file: 'debug'
},
path: 'app-core.log'
},
staging: {
level: {
console: 'warn',
file: 'warn'
},
path: 'app-core.log'
},
production: {
level: {
console: 'error',
file: 'error'
},
path: 'prod-app-core.log'
}
}
但是由于所有env
项的path
应该是相同的,除了生产
之外,我希望我可以仅为 path
值设置默认值。像这样的事情:
module.exports = {
$filter: 'env',
development: {
level: {
console: 'debug',
file: 'debug'
}
},
staging: {
level: {
console: 'warn',
file: 'warn'
}
},
production: {
level: {
console: 'error',
file: 'error'
},
path: 'prod-app-core.log'
},
$default: {
path: 'app-core.log'
}
}
显然,这是行不通的,但我希望它能说明我正在努力实现的目标。我找不到为对象内的单个配置项设置默认值的方法,如果我应用过滤器(例如 staging
),那么它会获取整个 staging 对象,甚至不会查看$default
对象。
谢谢!
P.S.虽然我想知道这是否可以通过信心(用于其他目的)实现,但如果事实证明这是不可能的,那么有没有办法设置默认路径用于 WinstonJS 文件传输?
最佳答案
我认为您正在寻找$base
。请参阅shared values文档中的部分:
If you have values that you would like to share between various configuration objects without duplicating them for each option, you can create a
$base
object.
以下是它在您的示例中的使用方式:
const Confidence = require('confidence');
const document = {
$filter: 'env',
$base: {
path: 'app-core.log'
},
development: {
level: {
console: 'debug',
file: 'debug'
}
},
staging: {
level: {
console: 'warn',
file: 'warn'
}
},
production: {
level: {
console: 'error',
file: 'error'
},
path: 'prod-app-core.log'
}
};
const store = new Confidence.Store(document);
console.log(store.get('/', { env: 'production' }));
console.log(store.get('/', { env: 'development' }));
控制台输出:
{ path: 'prod-app-core.log',
level: { console: 'error', file: 'error' } }
{ path: 'app-core.log',
level: { console: 'debug', file: 'debug' } }
那么 $default
是做什么用的呢?
$default
用于定义当 env 值在文档中没有相应键时应使用的对象。如果没有 $default
,您只会得到该路径的 undefined
:
const document = {
$filter: 'env',
$base: {
path: 'app-core.log'
},
$default: {
level: {
console: 'something-else',
file: 'something-else'
}
},
development: {
level: {
console: 'debug',
file: 'debug'
}
},
staging: {
level: {
console: 'warn',
file: 'warn'
}
},
production: {
level: {
console: 'error',
file: 'error'
},
path: 'prod-app-core.log'
}
};
const store = new Confidence.Store(document);
console.log(store.get('/', { env: 'dunno' }));
控制台输出:
{ path: 'app-core.log',
level: { console: 'something-else', file: 'something-else' } }
在 $default
级别定义的任何内容或特定匹配过滤器值将优先于在 $base
定义的值。
关于javascript - 在 HapiJS Confidence 配置对象中设置过滤对象的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35900082/