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 ?

1

2 Answers 2

0
  • Call them in this way:

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

    window["manager"][func](data1);
    
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.