Error while adding a key to the request object using JavaScript policy

We have a use case to modify the request object. In the request, we get a field called "userDefinedFields" which is an array of string objects. We need to explode this array into individual keys in the request that gets sent to the backend service.

For example:

Input => { ... "userDefinedFields": ["string1", "string2", "string3"] ... }

Output => { ... "udf1": "string1", "udf2": "string2", "udf3": "string3" ... }

I have written a javascript code to perform the same:

body = JSON.parse(context.getVariable("request.content"));


userDefinedFields = context.getVariable("hosted.userDefinedFields");
userDefinedFields = userDefinedFields.toString().replaceAll('\\[','').replaceAll('\\]','').replaceAll(' ','').replaceAll('"','').split(',');
print(userDefinedFields.length);


for (var i=0 ; i<userDefinedFields.length ; i++){
    print(userDefinedFields[i]);
    body["udf" + i] = userDefinedFields[i];
}


request.content = '';
request.content = context.setVariable("request.content", JSON.stringify(body));
print(JSON.stringify(body));

But I am getting an error as:

{
    "fault": {
        "faultstring": "Execution of JS-AddUDF failed with error: Javascript runtime error: \"Access to Java class \"java.lang.Class\" is prohibited. (JS_AddUDF_js#13)\"",
        "detail": {
            "errorcode": "steps.javascript.ScriptExecutionFailed"
        }
    }
}

I have tried the code on JSFiddle, and it is working as expected.

On some research, I found a link which says that Apigee uses Java compiled JavaScript which has some limitations.

What could be the reason for this? And how can I add keys to the JSON request.content?

0 2 489
2 REPLIES 2

What is the "hosted.userDefinedFields" thing? What sets that thing?

Can you use a Different name for that variable? Can you make it

"hosted_userDefinedFields" (underscore, not dot)

Then try your JS logic.

Thanks for the reply Dino!

The "hosted.userDefinedFields" is a custom flow variable that I am creating. It gets populated from the "userDefinedFields" array from the request payload, through an ExtractVariables policy.

I have tried using different variable names, including "hosted_userDefinedFields", in case "hosted" might be an apigee flow variable, but the issue still remains.

The error comes from the line 'body["udf"+ i]= userDefinedFields[i];'. If I comment the line, then the policy executes properly. The line dynamically adds keys to the existing JSON object(request payload).

I have also tried a simple JavaScript policy having the code as:

body = JSON.parse(context.getVariable("request.content"));


field = 'abc';


for (var i=0 ; i<5 ; i++){
    body[field + String(i)] = 'def';
}


context.setVariable("request.content", JSON.stringify(body));

And this works.