javascript - 动态返回配置值(node.js)
问题描述
我正在构建一个内容中间件,它从我们的外部发布者那里收集内容。发布者将在 rss 或 json 中共享他们的内容,并且键/值字段将彼此不同。为了让事情变得更简单,我创建了一个配置文件,我可以在其中预定义键/值和提要类型。问题是,如何根据发布者名称动态返回此配置值。
示例:要获得 Publisher #1 提要类型,我可以使用config.articles。rojak_daily .url_feed
我的配置文件/config/index.js
module.exports = {
batch:100,
mysql: {
database: process.env.database,
host: process.env.host,
username: process.env.username,
password: process.env.password
},
articles:{
rojak_daily:{ // Publisher 1
url: 'xxx',
url_feed: 'rss',
id: null,
Name: 'title',
Description: 'description',
Link: 'link',
DatePublishFrom: 'pubDate',
LandscapeImage: 's3image',
SiteName: 'Rojak Daily',
SiteLogo: null
},
rojak_weekly:{ // publisher 2
url: 'xxx',
url_feed: 'json',
id: null,
Name: 'Name',
Description: 'Desc',
Link: 'link',
DatePublishFrom: 'pubDate',
LandscapeImage: 's3image',
SiteName: 'Rojak Weekly',
SiteLogo: null
}
}
}
我的主要应用程序脚本
const config = require('@config'); // export from config file
class Main {
constructor(){
this.publishers = ['rojak_daily','rojak_weekly'];
}
// Main process
async startExport(){
try{
for(let publisher of this.publishers){
const feedType = await this.getFeedType(publisher)
const result = (feedType == 'rss')? await this.rss.start(publisher): await this.json.start(publisher)
return result
}
}catch(err){
console.log("Error occured: ", err)
}
}
// Get feed type from config
async getFeedType(publisher){
return await config.articles.rojak_daily.url_feed;
// this only return publisher 1 url feed.
// my concern is to dynamically passing variable
// into this config file (example: config.articles.<publisher>.url_feed)
}
}
module.exports = Main
解决方案
async getFeedType(publisher){
return await config.articles[publisher].url_feed;
}
您可以通过变量访问对象的属性
推荐阅读
- ios - Xcode 10 无法下载配置文件
- python - 如何在另一个过程中调用一个过程
- python - “如何不均匀地迭代两个列表”
- python - 计算斐波那契时的模数问题
- javascript - 如何在一个对话框中添加多选输入?
- html - 在 Foundation for Email、Zurb 中转义“<”字符
- angular - 强制重新加载 Angular 6 组件
- c++ - LLVM - 如何将 ConstantExpr 转换为 ConstantDataArray,以便打印全局变量 char* 的值?
- asp.net - 使用锁防止重复 api 提交 ASP.NET Core Web API
- android - LinearLayout 在中间显示第二个项目,而不是在第一个项目的正下方,最后一个项目(按钮)位于屏幕的按钮上