How to modify and construct json payload request in Javascript policy ?

Not applicable

How to modify and construct json payload request in Javascript policy ?

While Modifying the json payload I need to add some additional parameter values which should unique always for every request? What is the best way to generate and maintain unique values (either numbers or alpha numeric values) in JSON payload request while passing the request to Target systems.

0 5 8,351
5 REPLIES 5

adas
Participant V
@Venkateswarlu Pesala

the apigee runtime generates a unique messageid for every request. You could rely on this variable. You can access this variable in your javascript using the below code:

var uniqueId = context.getVariable('messageid');

If you want to write your own unique id generator (not recommended if you only care about unique string per request), you can do something like this:

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

var uuid = guid();
context.setVariable('response.header.x-apigee-uuid', uuid); 
//this returns the uuid as a response header called x-apigee-uuid

Hi @Arghya, Thanks for your response.

Any idea how to add additional parameters like guid() to new JSON payload request.

var req = JSON.parse(context.proxyRequest.content);

var finalRequest = { 
                endUserId: req.endUserId, 
                description: req.description,
                amount: req.amount,
                referenceCode: guid(),
                clientCorrelator: guid()+1,
                purchaseCategoryCode : req.purchaseCategoryCode,
                serviceID: req.serviceID,
                productID: req.productID,
                currency: req.currency,
                transactionOperationStatus: req.transactionOperationStatus };

context.proxyRequest.content = JSON.stringify(finalRequest);		

I tried above code. It is throwing javascript error.


What error is it throwing? give us a hint.

Keep in mind that there is a unique ID generated by Apigee Edge for every inbound message.

It is available in the context variable 'messageid'. An example message id looks like:

rrt-8b9972bb-b-ea-16486-16859636-3

So you may need not to generate a UUID at all.

var jsonObject = JSON.parse(context.getVariable('request.content')); //get request json

//update json object

jsonObject.guid = "sdf239hsd90fh23f"; //adding new key to json

delete jsonObject.age; // remove key 'age' from json

context.setVariable('request.content', JSON.stringify(jsonObject)); //set updated json