Home > OS >  Dynamic function call from dynamic string using nodejs
Dynamic function call from dynamic string using nodejs

Time:09-24

I'm using express nodejs, in my project, one scenario occurred while doing work on a specific module. I have made different functions for different roles, so based on the logged-in user's role, dynamically calling the other function. I want a trick that code should be a minimum of lines. So please suggest me a good solution.

if (userRole.code === ROLE.REFERRINGPROVIDER) {
  query = await referralUser(tabCode, userId, query);
} else if (userRole.code === ROLE.CONSULTINGPROVIDER) {
  query = await consultingUser(tabCode, userId, query);
} else if (userRole.code === ROLE.PARENT) {
  query = await parentUser(tabCode, userId, query);
} else if (userRole.code === ROLE.PHYSICIAN) {
  query = await physicianUser(tabCode, userId, query);
}

As shown in the above example I have to write that code for different users, so I have to make it a simple one-line function.

CodePudding user response:

You can use this solution :)

const userRole = { code: 'referral' };

async function referralUser(tabCode, userId, query){
 console.log(tabCode, userId, query);
 return "referralUser Called!";
}

async function consultingUser(tabCode, userId, query){
 console.log(tabCode, userId, query);
 return "consultingUser Called!";
}

async function parentUser(tabCode, userId, query){
 console.log(tabCode, userId, query);
 return "parentUser Called!"
}

let functionName = userRole.code   'User';
eval(functionName)("tabCode", "userId", "query").then((results)=>{
  console.log(results);
});

CodePudding user response:

You can call functions by their string name. For instance:

function funcOne() {
  console.log('funcOne');
}

function funcTwo() {
  console.log('funcTwo');
}

function funcThree() {
  console.log('funcThree');
}

function funcFour() {
  console.log('funcFour');
}

function funcFive() {
  console.log('funcFive');
}

const func: { [K: string]: Function } = {
  funcOne,
  funcTwo,
  funcThree,
  funcFour,
  funcFive
};

// console log output: "funcOne"
func['funcOne']();

// console log output: "funcFour"
func['funcFour']();

// console log output: "funcTwo"
func['funcTwo']();

In your case, use ROLE to map its keys to functions:

const func: { [K: string]: Function } = {
  [ROLE.REFERRINGPROVIDER]: referralUser,
  [ROLE.CONSULTINGPROVIDER]: consultingUser,
  [ROLE.PARENT]: parentUser,
  [ROLE.PHYSICIAN]: physicianUser
};

query = await func[userRole.code](tabCode, userId, query);
  • Related