0

I am trying to condense a potentially large switch case into a simple expression in nodejs. This is what I current have

exports.ManagerRequest = functions.https.onCall(async (data, context) => {

              console.log('[INDEX], @request1',data);

              const func = data.function
              const data1 = data.value

                switch (func) {
                  case 'request1':
                     const res = manager.request1(data1)
                    break;
                  case 'request2':
                     const res = manager.request2(data1)

                  default:
                    console.log(`Sorry, we are out of ${func}.`);
                }

 
    return res

})

I have manager imported and many functions in manager which i am calling based on the requested function in data. The switch cases will significantly expand. is there a way to call automatically insert the function name and associated data. something that look like this

const res = manager.'{func(data)}'

How can the function name and data be dynamically generated ?

e.iluf
  • 1,389
  • 5
  • 27
  • 69
  • Take a look at https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – AlexSp3 Jul 23 '21 at 18:57

2 Answers2

0
  • Call them in this way:

    window["Namespace"]["functionName"](arguments);
    
  • In your case it would be:

    window["manager"][func](data1);
    
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
0

I'm not sure I understand the question. Do you mean to dynamically dispatch a method call to manager based on a string input? If so it can be done like this:

exports.ManagerRequest = functions.https.onCall(async (data, context) => {

              console.log('[INDEX], @request1',data);

              const functionName = data.function
              const data1 = data.value
              const func = manager[functionName];

              if (func && func instanceof Function) {
                  return func(data1);
              } else {
                  console.log(`Sorry, we are out of ${functionName}.`);
              }
}

Just be careful that the input is trusted, otherwise this could very well become an attack surface as it allows the client call an arbitrary method of manager.