I have a client-server connection via websocket that communicate with JSON objects. My server has several functions:
function FirstFunction(arg1, arg2) {
...
}
function SecondFuction(argOther) {
...
}
How could my client send a JSON object that contains the name of the function I want to call plus the parameters, and make the server call that function? Something like this (pseudo-code, doesn't work)
data = {"method" : "FirstFunction", "params" : {"arg1" : 10, "arg2" : 20} }
result = data["mehod"](data.params.arg1, data.params.arg2)
The reason I want to do it this way is because my client uses Python and my server Javascript
CodePudding user response:
This sounds like a big security issue, but if that's not a problem for you here's how you can do it:
function FirstFunction(arg1, arg2) { /* ... */ }
function SecondFunction(argOther) { /* ... */ }
const functions = {
FirstFunction,
SecondFunction
}
// You didn't specify how you receive the JSON
// so I'm just going to hard code it
const jsonString = `{"method" : "FirstFunction", "params" : {"arg1" : 10, "arg2" : 20} }`
function callFunction (json) {
const { method, params } = JSON.parse(json)
functions[method](...params)
}
callFunction(jsonString)
Note: The example is case sensitive
The trick here is assigning the functions you want to make available to the client as properties of an object which can be accessed with strings.