Stumbled on the Javascript REST Resource the other day. It’s a pretty cool asset that when configured correctly lets you run server-side Javascript to manipulate the response from a HTTP request to another system.
We’ve got a lot of systems in our business that we can expose via SOAP web service, so it’s useful to be able to perform queries, calculations, and put some logic in the responses we get back. For instance I’ve just finished a neat intranet tool to get data from our order entry system and perform calculations using the very latest figures.
Some may consider server-side Javascript an awkward idea, but it’s picking up a bit of momentum with projects like Javascript REST Resource. Admittedly the Matrix implementation isn’t that fancy, but it’s still quite useful in some scenarios.
Checking for Requirements
To set this up you will need to install a third party Javascript engine. Your operating system probably won’t come with one installed by default, so attempting to run any Javascript with this asset will just fail silently.
You can tell if the Javscript engine is installed on your server by checking the Matrix configuration: “System Configuration” → “External Tools Configuration” → “JavaScript Configuration” → “Javascript Command”. This should default to something like “/usr/bin/js”.
If the command is present, you should be able to run it on your server and get the Javascript console.
# js js>
Installing Javascript
There’s a few different Javascript engines, but I’m using Javascript REST Resource from Mozilla. You may also consider using Rhino or V8.
If you’re using Red Hat or Fedora, check to see if your distribution has a js and js-devel package in the repository. If not, you can find one on Javascript REST Resource.
Using Javascript
Dealing with Javascript on the server is a bit different to using it in the context of the browser. The main thing you will probably notice is that there’s no global ‘document’ object, and a number of the more helpful libraries from modern Javascript are missing.
Regardless it still quite a powerful when you work out what you’re doing. Here’s a few tips to get you started:
- Safely load and save JSON by including a Javascript REST Resource.
[*] Create XML documents with the following syntax:var newDocument = new XML('');
[*]If you have a requirement for a Javascript templating language, consider using Javascript REST Resource.