After that I realized defining menu variable will run every function in the object to store the value in the properties which is not what I'm trying to do.
What you have looks like it would work just fine. Declaring the menu
structure does not execute the functions you've assigned as properties. It just defines the functions and assigns them as properties (waiting to be called later).
You could save a little execution overhead by moving the static menu
definition outside the function so it just gets defined once (I'm assuming this is private module scope so moving the symbol outside the function is fine) and change it to const
.
You can also remove the async
and await
since neither add anything here. You're just returning a promise anyway so you can just return the promise directly without async
and await
. I also added more explicit error checking for the category name.
const methodMap = {
'feed': () => steem.api.getDiscussionsByFeed(query),
'blog': () => steem.api.getDiscussionsByBlog(query),
'new': () => steem.api.getDiscussionsByCreated(query),
'hot': () => steem.api.getDiscussionsByHot(query),
'trend': () => steem.api.getDiscussionsByTrending(query)
};
const getContent = (category, tag) => {
const query = { 'tag':tag, 'limit':10 };
if (methodMap.hasOwnProperty(category)) {
return methodMap[category]();
} else {
return Promise.reject(new Error(`Unknown Category: ${category}`));
}
}
You could also remove some redundancy from the table by making the table only be the steem method name you want to call.
const methodMap = {
'feed': 'getDiscussionsByFeed',
'blog': 'getDiscussionsByBlog',
'new': 'getDiscussionsByCreated',
'hot': 'getDiscussionsByHot',
'trend': 'getDiscussionsByTrending'
};
const getContent = (category, tag) => {
const query = { 'tag':tag, 'limit':10 };
if (methodMap.hasOwnProperty(category)) {
return steem.api[methodMap[category]](query);
} else {
return Promise.reject(new Error(`Unknown Category: ${category}`));
}
}
This layout also does more explicit error checking on a "supported" category being passed in.
menu
object does not run any of the functions that are assigned as properties. It just defines those functions. \$\endgroup\$ – jfriend00 Nov 27 '17 at 4:30