Hi friends,
Do you use the JS policy? We've quietly released a little handy feature that may make your life simpler.
Let's take a step back. The JS policy in Apigee Edge allows you to do ... lots of things, any custom action that you can't do easily using ther built-in policies. Let's say you want to add a single field to a JSON response - it's really easy with a JS policy, whereas it might be tricky with any of the other 30+ builtin policies in Apigee Edge.
The basic syntax for a JS policy looks like this:
<JavaScript name='JS-1'> <ResourceURL>jsc://otherFileContainingJavaScript.js</ResourceURL> </JavaScript>
There are obviously more options than just that, and you can look at the policy reference to see them all. But that shows the most basic JS policy. If you want to run your own bit of JavaScript, you need at least 2 files: one to specify the policy XML, and the other to hold the actual JavaScript. You can see that the policy XML holds only 2 pieces of information: the name of the policy (in this case, JS-1), and the pointer to the JavaScript source (otherFileContainingJavaScript.js).
Ever since I started using Apigee Edge, which is more than 6 years ago, I wanted a simpler way of specifying the JS source, preferably a way to specify the source in the JS policy itself. Sometimes my JS code is very short. A line or two. And it feels over-engineered to require that the source code for a JS policy be stored in a separate .js file.
There are good reasons to store JS code alone, in filesystem files that end with .js.
All of those are good reasons.
But there are some cases when it sure would be nice to have a little bit of Source code in one small policy. The new Source element in the JavaScript policy supports that goal. Here's what it looks like:
<JavaScript name='JS-Indent'> <Source> // indent each line in the request content by 4 spaces var r = new RegExp('^\S*','mg'); var c = context.getVariable('request.content'); c = c.replace(r, ' $1'); context.setVariable('request.content', c); </Source> </JavaScript>
You can use this new element immediately in any cloud organization.
Some notes:
We think this little feature is useful and hope you will think so too.
I'd love to hear your feedback on this.
ps: I don't know when this feature gets pulled into OPDK, but I think it's 1901 !
@Dino-at-Google This is cool, thanks for letting us know.
Is there any limitation on the lines of code or any other restrictions for the source written inline?
This is a nifty feature, makes bundles more readable. Thanks !
There is no limitation on the number of lines of code. I suppose that after a certain limit - 10 lines? 20? - it will become impractical, and you will do better with a separate JS module.