Sunday, May 10, 2015

XML-RPC Service Binding to JavaScript Functions in Google Apps Script

I was recently asked for some assistance using the Google Apps Script library I wrote for XML-RPC: XmlRpcMessageService (see post). This made me go back to the code I wrote some months ago. Looking at my code, I realized I missed a step in making XML-RPC easy to use from GAS. The way XML-RPC is defined, it is very easy to conceptually bind a JavaScript function with an XML-RPC method call:

XML-RPCJavaScript
methodNameFunction name
paramsFunction arguments

So, looking at the example from the previous post, instead of the verbose method call:
var methodCall = {
   methodName : "LogIn",
   params : [ "", "", "en", "OS Test User Agent" ]
}
var url = "http://api.opensubtitles.org/xml-rpc";
var methodResponse;
var onSuccess = function(mr) { methodResponse = mr; };
XmlRpcMessageService.execMethodCall(url, methodCall, onSuccess);

We can do a native JavaScript function call:
var service = XmlRpcMessageService.bind(url);
var result = service.LogIn("", "", "en", "OS Test User Agent");

This is possible because the mapping is very simple, as written in the table above. In addition, the response is treated with the following behavior:
If the response contains a 'fault' element - this is an error, throw an exception. Otherwise, a single 'param' element is expected, with the return value.

One more thing - did you notice that the service methods were discovered by "magic"? No magic, just using the XML-RPC specification, or more precisely the "system.listMethods" method call. This method is usually implemented by XML-RPC servers. It returns the names of all supported methods. Since JavaScript is dynamic and does not really enforce the function arguments, this is enough for creating the functions binding. There are two more useful XML-RPC methods ("system.methodHelp" and "system.methodSignature") which I did not find a reason to use yet.
In case the server you want to use does not support the "system.listMethods" method, you can give the "bind" method an array of the method names:
var service = XmlRpcMessageService.bind(url, ["LogIn"]);
var result = service.LogIn("", "", "en", "OS Test User Agent");

The code is available in GitHub:
https://github.com/yinonavraham/GoogleAppsScripts/tree/master/XmlRpcMessageService


No comments:

Post a Comment