[英]Dynamically return config value (node.js)
我正在構建一個內容中間件,它從我們的外部發布者那里收集內容。 發布者將在 rss 或 json 中共享他們的內容,並且鍵/值字段將彼此不同。 為了讓事情變得更簡單,我創建了一個配置文件,我可以在其中預定義鍵/值和提要類型。 問題是,如何根據發布者名稱動態返回此配置值。
示例:要獲得 Publisher #1 提要類型,我可以使用
我的配置文件
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;
}
您可以通過變量訪問對象的屬性
您可以使用Object.entries(articles)
或Object.values(articles)
與Array.prototype.forEach()
一起循環文章,或者由於您已經有了發布者的名稱,您可以使用config.articles[publisher].url_feed
訪問該條目config.articles[publisher].url_feed
,像這樣:
const config = { 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 publishers = ['rojak_daily', 'rojak_weekly'] function getFeedType(publisher) { return config.articles[publisher].url_feed; } publishers.forEach(publisher => console.log(getFeedType(publisher)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.