1
votes

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.

I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:

[{"itemId":1,"charge":9,"itemSize":2,"id":2}]

I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:

//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));

//same: code to inject new attribute 
json.platform = 'Powered by IBM API Connect';

//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);

Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.

3

3 Answers

1
votes

You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?

var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object

json.platform = 'Powered by IBM API Connect'; //add new property

apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
0
votes

You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:

apim.readInputAsJSON(function (error, json) {
if (error)
{
    // handle error
    apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
    //APIC: get the payload
    var json = apim.getvariable('message.body');
    //console.error("json %s", JSON.stringify(json));
    if(json){
        //same: code to inject new attribute 
        json.platform = 'Powered by IBM API Connect';

        //APIC: set the payload
        //message.body = json;
        apim.setvariable('message.body', json);
    }
}
});

Reference: IBM Reference

0
votes

You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.