Skip to Content
Author's profile photo Martin Pankraz

How to use JavaScript in CPI Scripting

Dear all,

 

During my scripting journey with Cloud Platform Integration, I noticed that there are only scripting examples for groovy. This is probably due to the fact that most services in the SAP ecosystem are xml based. Also XML offers a lot of structure which is great for parsing, doing mashups, enrichment and all sorts of manipulations.

But JSON offers a similar grade of structure only with less overhead. Several benchmarks (e.g JSON-vs-XML) arrive at magnitudes of 21% overhead when it comes to XML. That impacts processing time and heap space consumption.

As promised, finally an JavaScript example for CPI that should get you up to speed. The imported classes up top make sure you can access your message headers, properties and body just like with groovy.

importClass(com.sap.gateway.ip.core.customdev.util.Message);
importClass(java.util.HashMap);
function processData(message) {
       var body = String(message.getBody( new java.lang.String().getClass()));
       //create json from string object
       body = JSON.parse(body);

return message;
}

Especially in the OData world it makes to consider working with lightweight JSON payloads and responses. Although you can mostly ask the standard SAP OData service to answer with XML instead of JSON if you need to.

For the sake of completeness: Groovy offers a library called “JsonSlurper” that allows you to work with the JSON payload just like you typically do with XML and XmlParser or XmlSlurper.

 

Kind regards

Martin

Assigned tags

      4 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Krishnakumar Ramadoss
      Krishnakumar Ramadoss

      Thanks for adding this post, I tired playing around Javascript in some of my integrations but SAP  has provided very little documentation when it comes to scripting support using JS, for instance I tried to use XMLHttpRequest object to query using script but I got an error message that  XMLHttpRequest is not defined.

      It would be really nice if SAP can add some inputs when they say that they  support Java Script  ?

      Author's profile photo Martin Pankraz
      Martin Pankraz
      Blog Post Author

      Dear Krishnakumar,

       

      This is not fully blown JS I suspect. They offer JavaScript mostly for OData parsing and the likes. Apart from that XMLHttpRequest would contradict the message monitor and controlled outbound communication. You should always use a receiver box for that.

       

      Kind regards

      Martin

      Author's profile photo Muniyappan Marasamy
      Muniyappan Marasamy

      Thank you for the blog Martin.

      Author's profile photo Guilherme Viana
      Guilherme Viana

      Thank you ! You are brilliant.

       

      Kind Regards

       

      Guilherme