Javascript JSON object not being cached

Not applicable

When you try to cache a JSON object (or any object) there is an issue where it can only be retrieved intermittently.

This happens when you try to store a JSON object in the cache, e.g.

var myJson = {"Name": "value"};

context.setVariable("VAR_NAME", myJson);

When you then try to cache VAR_NAME it will store it in the MP but Cassandra will not accept it as an object. This means that when you try to lookup the cache it will work on the original MP that tried to store it but not on any others, i.e. sometimes you'll get the value, sometimes you'll get null.

The way to fix this is to store the JSON object as a string by either:

var myJson = {"Name": "value"};

context.setVariable("VAR_NAME", JSON.stringify(myJson));

or simply

var myJson = '{"Name": "value"}';

One advantage of this over, say wrapping your object in single quotes, is that you can reference the lookup variable in javascript as follows:

context.getVariable("lookup_var")
1 3 711
3 REPLIES 3

I may be misunderstanding, but context.setVariable doesn't work with the cache. Variables set to context should only live for the duration of the request/response. They should never persist across multiple requests. ??? http://apigee.com/docs/api-services/reference/javascript-object-model

I wasn't clear enough in my original post. There is a Populate Cache policy and a Lookup Cache policy.

We use javascript to create a variable (myJson->VAR_NAME) in the context. This variable is then used in Populate Cache to store in the cache:

<PopulateCache async="false" continueOnError="false" enabled="true" name="Populate-Cache">
  <DisplayName>Populate Cache</DisplayName>
  <CacheResource>CacheName</CacheResource>
  <Source>MY_VAR</Source> 
  <Scope>Global</Scope>
  <CacheKey> 
    <Prefix>Node1</Prefix>
    <KeyFragment ref="request.header.apikey"/>
  </CacheKey> 
</PopulateCache>

____________________________

We then use Lookup Cache to access the cache and populate a flow variable:

<LookupCache async="false" continueOnError="false" enabled="true" name="Lookup-Cache-1"> 
  <DisplayName>Lookup Cache</DisplayName> 
  <CacheResource>CacheName</CacheResource>
  <AssignTo>NEW_VAR</AssignTo> 
  <Scope>Global</Scope> 
  <CacheKey> 
    <Prefix>Node1</Prefix> 
    <KeyFragment ref="response.header.apikey"/>
  </CacheKey> 
</LookupCache>

From here we can do what we like with NEW_VAR.

____________________________

The issue we saw was that the output from Lookup Cache depended on the original myJson in the javascript prior to Populate Cache:

var myJson ={"Name":"value"}; //returns null 50% of the time (depending on number of MPs)
var myJson ='{"Name": "value"}'; //returns the correct value every time.

Ohhh! Lightbulb! Interesting. Thanks for clarifying.